【问题标题】:Mark test as passed from inside a fixture in pytest将测试标记为从 pytest 中的夹具内部通过
【发布时间】:2020-08-19 10:48:13
【问题描述】:

使用pytest.skippytest.xfail,我可以从夹具内部将测试标记为已跳过或xfailed。不过,没有pytest.pass。如何标记为通过?

import pytest

@pytest.fixture
def fixture():
    #pytest.skip()
    pytest.xfail()

def test(fixture):
    assert False

【问题讨论】:

  • 结束测试是通过
  • 返回一些值,这意味着“通过”测试,我想。不知道你为什么要这样做:)
  • 针对pytest LOL 提出问题
  • 一个测试只有在它已经执行并且没有引发的情况下才能通过。如果测试没有执行,它会被跳过。如果您必须撒谎并在测试失败或未运行时将测试显示为通过,那么测试设计是严重错误的。虽然您可以将测试结果从未通过修改为通过,但它被隐藏是有原因的。
  • @finefoot 我不是故意要听起来傲慢,对此感到抱歉。我也不是反对者。尽管如此,我仍然建议不要更改测试结果来模拟统计数据。您能否提供一个更好地描述您的问题的minimal reproducible example

标签: python unit-testing testing pytest python-unittest


【解决方案1】:

不幸的是,我不知道使用夹具通过测试的方法,但您可以在测试中使用 pytest.skip 和 msg,例如“pass”,来自 conftest.py 的钩子将检查这个“pass” msg 并生成测试通过:

conftest.py

import pytest


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(call):
    outcome = yield
    if outcome.get_result().outcome == 'skipped' and call.excinfo.value.msg == 'pass':
        outcome.get_result().outcome = 'passed'

test_skip.py

# -*- coding: utf-8 -*-
import pytest


def test_skip_pass():
    pytest.skip('pass')


def test_skip_pass_2():
    pytest.skip('skip')

结果:

正在收集...收集了 2 件物品

test_skip.py::test_skip_pass 已通过 [50%]
test_skip.py::test_skip_pass_2 跳过 [100%]
跳过:跳过

======================== 1 次通过,1 次在 0.04 秒内跳过 =============== ==========

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 2020-02-17
    • 1970-01-01
    • 2022-06-27
    • 2013-03-28
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多