首页 > 解决方案 > 将测试标记为从 pytest 中的夹具内部通过

问题描述

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

import pytest

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

def test(fixture):
    assert False

标签: pythonunit-testingtestingpytestpython-unittest

解决方案


不幸的是,我不知道使用夹具通过测试的方法,但是您可以在测试中使用 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.04s 内跳过 ================== =======


推荐阅读