如何在pytest中对固定装置施加命令



我正试图使用pytest依赖项使固定装置按顺序发生,无论它们的命名方式如何,也无论它们在测试参数列表中的显示顺序如何。

我需要这一点的原因是,创建需要初始化的固定装置,这些固定装置依赖于需要初始化的其他固定装置,并且它们必须按顺序发生。我有很多这样的,我不想依赖于参数列表中的命名或顺序。

我也不想使用pytest_sessionstart,因为它不能接受fixture输入,这会导致代码非常不干净。


文档中的一个简单示例显示了如何为测试创建程序依赖项:

import pytest
@pytest.mark.dependency()
@pytest.mark.xfail(reason="deliberate fail")
def test_a():
assert False
@pytest.mark.dependency()
def test_b():
pass
@pytest.mark.dependency(depends=["test_a"])
def test_c():
pass
@pytest.mark.dependency(depends=["test_b"])
def test_d():
pass
@pytest.mark.dependency(depends=["test_b", "test_c"])
def test_e():
pass

这适用于输出:

============================= test session starts =============================
collecting ... collected 5 items
test_sanity.py::test_z XFAIL (deliberate fail)                           [ 20%]
@pytest.mark.dependency()
@pytest.mark.xfail(reason="deliberate fail")
def test_z():
>       assert False
E       assert False
test_sanity.py:6: AssertionError
test_sanity.py::test_x PASSED                                            [ 40%]
test_sanity.py::test_c SKIPPED (test_c depends on test_z)                [ 60%]
Skipped: test_c depends on test_z
test_sanity.py::test_d PASSED                                            [ 80%]
test_sanity.py::test_w SKIPPED (test_w depends on test_c)                [100%]
Skipped: test_w depends on test_c

=================== 2 passed, 2 skipped, 1 xfailed in 0.05s ===================

现在我想对固定装置做同样的事情

我的尝试:

conftest.py:

import pytest
pytest_plugins = ["dependency"]

@pytest.mark.dependency()
@pytest.fixture(autouse=True)
def zzzshould_happen_first():
assert False

@pytest.mark.dependency(depends=["zzzshould_happen_first"])
@pytest.fixture(autouse=True)
def should_happen_last():
assert False

test_sanity.py:

def test_nothing():
assert True

输出

test_sanity.py::test_nothing ERROR                                       [100%]
test setup failed
@pytest.mark.dependency(depends=["zzzshould_happen_first"])
@pytest.fixture(autouse=True)
def should_happen_last():
>       assert False
E       assert False
conftest.py:15: AssertionError

我预料到zzzshould_happen_first会出现错误。


是否有一种方法可以强制对固定装置进行订购,例如

  1. 他们的名字被忽略
  2. 它们在参数列表中的顺序被忽略
  3. 其他pytest功能(如autouse(仍然可以应用

您可以直接使用pytest将fixture作为依赖项。类似这样的东西:

import pytest

@pytest.fixture(autouse=True)
def zzzshould_happen_first():
assert False

@pytest.fixture(autouse=True)
def should_happen_last(zzzshould_happen_first):
assert False

def test_nothing():
assert True

它提供你想要的:

test setup failed
@pytest.fixture(autouse=True)
def zzzshould_happen_first():
>       assert False
E       assert False
answer.py:7: AssertionError

最新更新