I have a module with test functions and I want to write conftest.py
file to decorate all functions in the module after the collection phase and before test run. And I do not want to edit the module with test functions. I tried it this way:
def test_foo ():
assert 1 == 42
def pytest_generate_tests (metafunc):
def test_bar ():
assert 1 == 2
metafunc.function = test_bar
When I run tests, I get this:
==================================== FAILURES =====================================
____________________________________ test_foo _____________________________________
def test_foo ():
> assert 1 == 42
E assert 1 == 42
But I expected assertion error about 1 == 2
.
If you want to run a certain function before a test , define a fixture and use the fixture name as test parameter.
import pytest
@pytest.fixture
def fixture1():
assert 1 == 2
def test_foo(fixture1):
assert 1 == 42
Output:
@pytest.fixture
def fixture1():
> assert 1 == 2
E assert 1 == 2
If you want to run a certain function before each test , define a fixture with autouse=True
. I think this is what you want.
import pytest
@pytest.fixture(autouse=True)
def fixture1():
assert 1 == 2
def test_foo():
assert 1 == 42
Output:
@pytest.fixture(autouse=True)
def fixture1():
> assert 1 == 2
E assert 1 == 2
If you want a custom test decorator , use standard decorator syntax.
def my_test_decorator(test):
def wrapper():
assert 1 == 2
return wrapper
@my_test_decorator
def test_foo():
assert 1 == 42
Output:
def wrapper():
> assert 1 == 2
E assert 1 == 2
我只需要替换pytest项目的runtest
方法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.