我有以下例子:
conftest.py:
@pytest.fixture:
def my_fixture_1(main_device)
yield
if FAILED:
-- code lines --
else:
passmain.py:
def my_test(my_fixture_1):
main_device = ...
-- code lines --
assert 0
-- code lines --
assert 1例如,当断言为0时,测试应该失败并执行my_fixture_1。如果测试通过,夹具就不能执行。我试过使用钩子,但没有找到解决方案,即使测试通过,夹具也总是在执行。
请注意,main_device是连接到测试运行位置的设备。
发布于 2022-02-26 10:39:53
您可以使用request作为夹具的参数。由此,您可以检查相应测试的状态,即它是否失败。如果失败,您可以在失败时执行要执行的代码。在代码中,读取为
@pytest.fixture
def my_fixture_1(request):
yield
if request.session.testsfailed:
print("Only print if failed")当然,夹具将始终运行,但只有当相应的测试失败时,分支才会被执行。
发布于 2022-02-27 15:51:14
在Simon Hawe's answer中,request.session.testsfailed表示该特定测试运行中的测试失败次数。
这是我能想到的另一种解决方案。
import os
@pytest.fixture(scope="module")
def main_device():
return None
@pytest.fixture(scope='function', autouse=True)
def my_fixture_1(main_device):
yield
if os.environ["test_result"] == "failed":
print("+++++++++ Test Failed ++++++++")
elif os.environ["test_result"] == "passed":
print("+++++++++ Test Passed ++++++++")
elif os.environ["test_result"] == "skipped":
print("+++++++++ Test Skipped ++++++++")
def pytest_runtest_logreport(report):
if report.when == 'call':
os.environ["test_result"] = report.outcome您可以在pytest_runtest_logreport钩子本身中直接执行实现。但缺点是,除了报告之外,您将无法访问其他设备。
因此,如果您需要main_device,您必须使用像上面所示的自定义夹具。
使用@pytest.fixture(scope='function', autouse=True),它将为每个测试用例自动运行它。您不必将所有测试函数中的main_device作为参数。
https://stackoverflow.com/questions/71260532
复制相似问题