pytest:如何在 pytest_sessionstart() 中访问 tmp_path?
pytest: How to access tmp_path in pytest_sessionstart()?
我正在使用 pytest
编写一些单元测试。
我知道我可以在任何测试或夹具中访问 tmp_path
临时目录,但是否也可以在 pytest_sessionstart()
方法中访问它?
本质上,这是我想要实现的目标的示例
def pytest_sessionstart(session, tmp_path):
"""Create hello.txt before any test is ran and make available to all tests"""
p = tmp_path.join("hello.txt")
p.write("content")
谢谢
为所有测试创建临时文件的推荐方法是使用具有内置 tmp_path_factory 夹具的会话范围夹具。
来自 pytest docs :
# contents of conftest.py
import pytest
@pytest.fixture(scope="session")
def image_file(tmp_path_factory):
img = compute_expensive_image()
fn = tmp_path_factory.mktemp("data").join("img.png")
img.save(str(fn))
return fn
# contents of test_image.py
def test_histogram(image_file):
img = load_image(image_file)
# compute and test histogram
我正在使用 pytest
编写一些单元测试。
我知道我可以在任何测试或夹具中访问 tmp_path
临时目录,但是否也可以在 pytest_sessionstart()
方法中访问它?
本质上,这是我想要实现的目标的示例
def pytest_sessionstart(session, tmp_path):
"""Create hello.txt before any test is ran and make available to all tests"""
p = tmp_path.join("hello.txt")
p.write("content")
谢谢
为所有测试创建临时文件的推荐方法是使用具有内置 tmp_path_factory 夹具的会话范围夹具。
来自 pytest docs :
# contents of conftest.py
import pytest
@pytest.fixture(scope="session")
def image_file(tmp_path_factory):
img = compute_expensive_image()
fn = tmp_path_factory.mktemp("data").join("img.png")
img.save(str(fn))
return fn
# contents of test_image.py
def test_histogram(image_file):
img = load_image(image_file)
# compute and test histogram