简体   繁体   English

如何在收集测试时替换py.test中的测试函数?

[英]How to replace test functions in py.test while collecting tests?

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. 我有一个带有测试功能的模块,我想编写conftest.py文件,以在收集阶段之后和测试运行之前修饰模块中的所有功能。 And I do not want to edit the module with test functions. 而且我不想使用测试功能来编辑模块。 I tried it this way: 我这样尝试过:

test_foo.py test_foo.py

def test_foo ():
    assert 1 == 42

conftest.py conftest.py

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 . 但是我期望断言错误大约为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 . 如果要在每次测试之前运行某个功能,请使用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方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM