[英]How to replace test functions in py.test while collecting tests?
我有一个带有测试功能的模块,我想编写conftest.py
文件,以在收集阶段之后和测试运行之前修饰模块中的所有功能。 而且我不想使用测试功能来编辑模块。 我这样尝试过:
def test_foo ():
assert 1 == 42
def pytest_generate_tests (metafunc):
def test_bar ():
assert 1 == 2
metafunc.function = test_bar
运行测试时,我得到以下信息:
==================================== FAILURES =====================================
____________________________________ test_foo _____________________________________
def test_foo ():
> assert 1 == 42
E assert 1 == 42
但是我期望断言错误大约为1 == 2
。
如果要在测试前运行某个功能,请定义一个夹具并将夹具名称用作测试参数。
import pytest
@pytest.fixture
def fixture1():
assert 1 == 2
def test_foo(fixture1):
assert 1 == 42
输出:
@pytest.fixture
def fixture1():
> assert 1 == 2
E assert 1 == 2
如果要在每次测试之前运行某个功能,请使用autouse=True
定义一个夹具 。 我想这就是你想要的。
import pytest
@pytest.fixture(autouse=True)
def fixture1():
assert 1 == 2
def test_foo():
assert 1 == 42
输出:
@pytest.fixture(autouse=True)
def fixture1():
> assert 1 == 2
E assert 1 == 2
如果要使用自定义测试装饰器 ,请使用标准装饰器语法。
def my_test_decorator(test):
def wrapper():
assert 1 == 2
return wrapper
@my_test_decorator
def test_foo():
assert 1 == 42
输出:
def wrapper():
> assert 1 == 2
E assert 1 == 2
我只需要替换pytest项目的runtest
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.