首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只有在测试失败时,我才能运行夹具?

只有在测试失败时,我才能运行夹具?
EN

Stack Overflow用户
提问于 2022-02-25 03:01:34
回答 2查看 1.2K关注 0票数 3

我有以下例子:

conftest.py:

代码语言:javascript
复制
@pytest.fixture:
def my_fixture_1(main_device)
  yield
  if FAILED:
    -- code lines --
  else:
    pass

main.py:

代码语言:javascript
复制
def my_test(my_fixture_1):
  main_device = ...
  -- code lines --
  assert 0

  -- code lines --
  assert 1

例如,当断言为0时,测试应该失败并执行my_fixture_1。如果测试通过,夹具就不能执行。我试过使用钩子,但没有找到解决方案,即使测试通过,夹具也总是在执行。

请注意,main_device是连接到测试运行位置的设备。

EN

回答 2

Stack Overflow用户

发布于 2022-02-26 10:39:53

您可以使用request作为夹具的参数。由此,您可以检查相应测试的状态,即它是否失败。如果失败,您可以在失败时执行要执行的代码。在代码中,读取为

代码语言:javascript
复制
@pytest.fixture
def my_fixture_1(request):
  yield
  if request.session.testsfailed:
    print("Only print if failed")

当然,夹具将始终运行,但只有当相应的测试失败时,分支才会被执行。

票数 1
EN

Stack Overflow用户

发布于 2022-02-27 15:51:14

Simon Hawe's answer中,request.session.testsfailed表示该特定测试运行中的测试失败次数。

这是我能想到的另一种解决方案。

代码语言:javascript
复制
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作为参数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71260532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档