【问题标题】:Fixture order of execution in pytestpytest中的夹具执行顺序
【发布时间】:2020-07-29 00:54:12
【问题描述】:
我是使用 Pytest 的新手。我对我的项目中正确使用固定装置和依赖注入的方法感到有些困惑。我的框架如下:
conftest.py
@pytest.fixture(scope="session")
def test_env(request):
//some setup here for the entire test module test_suite.py
@pytest.fixture(scope="function")
def setup_test_suite(test_env):
//some setup that needs to be done for each test function
//eventually parameterize? for different input configuration
test_suite.py
def test_function(setup_test_suite)
//some testing code here
- 将 setup 函数放在 conftest.py 或测试套件本身有什么区别?
- 我希望为整个会话设置一次测试环境。如果 setup_test_suite 依赖于 test_env,test_env 会执行多次吗?
- 如果我要参数化 setup_test_suite,调用固定装置的顺序是什么?
【问题讨论】:
标签:
python
testing
dependency-injection
pytest
fixtures
【解决方案1】:
-
conftest.py 和本地测试模块中的夹具之间的区别在于可见性。夹具将对同一级别的所有测试模块以及该级别以下的模块可见。如果夹具设置为autouse=True,它将针对这些模块中的所有测试执行。
欲了解更多信息,请查看What is the use of conftest.py files
-
如果test_env 是基于会话的,它只会在会话中执行一次,即使它在多个测试中被引用。如果它产生一个对象,同一个对象将被传递给所有引用它的测试。
例如:
@pytest.fixture(scope="session")
def global_fixt():
print('global fixture')
yield 42
@pytest.fixture(scope="function")
def local_fixt(global_fixt):
print('local fixture')
yield 5
def test_1(global_fixt, local_fixt):
print(global_fixt, local_fixt)
def test_2(global_fixt, local_fixt):
print(global_fixt, local_fixt)
给出pytest -svv的输出:
...
collected 2 items
test_global_local_fixtures.py::test_1 global fixture
local fixture
42 5
PASSED
test_global_local_fixtures.py::test_2 local fixture
42 5
PASSED
...
- 夹具参数按照它们提供给夹具的顺序被调用。例如,如果您有:
@pytest.fixture(scope="session", params=[100, 1, 42])
def global_fixt(request):
yield request.param
def test_1(global_fixt):
assert True
def test_2(global_fixt):
assert True
测试将按以下顺序执行:
test_1 (100)
test_2 (100)
test_1 (1)
test_2 (1)
test_1 (42)
test_2 (42)