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

Python 如何在收集测试时替换py.test中的测试函数?,python,pytest,Python,Pytest,我有一个带有测试函数的模块,我想编写conftest.py文件,在收集阶段之后和测试运行之前装饰模块中的所有函数。我不想编辑带有测试功能的模块。 我这样试过: 测试_foo.py conftest.py 当我运行测试时,我得到以下信息: ==================================== FAILURES ===================================== ____________________________________ test_foo _

我有一个带有测试函数的模块,我想编写
conftest.py
文件,在收集阶段之后和测试运行之前装饰模块中的所有函数。我不想编辑带有测试功能的模块。 我这样试过:

测试_foo.py conftest.py 当我运行测试时,我得到以下信息:

==================================== FAILURES =====================================
____________________________________ test_foo _____________________________________

    def test_foo ():
>       assert 1 == 42
E       assert 1 == 42

但是关于
1==2

我预期会出现断言错误。如果您想在测试之前运行某个函数,请定义一个fixture并使用fixture名称作为测试参数

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
    @pytest.fixture(autouse=True)
    def fixture1():
>       assert 1 == 2
E       assert 1 == 2
    def wrapper():
>       assert 1 == 2
E       assert 1 == 2

如果要在每次测试之前运行某个功能,请使用
autouse=True
定义一个fixture。我想这就是你想要的

import pytest


@pytest.fixture(autouse=True)
def fixture1():
    assert 1 == 2


def test_foo():
    assert 1 == 42
输出:

    @pytest.fixture
    def fixture1():
>       assert 1 == 2
E       assert 1 == 2
    @pytest.fixture(autouse=True)
    def fixture1():
>       assert 1 == 2
E       assert 1 == 2
    def wrapper():
>       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
输出:

    @pytest.fixture
    def fixture1():
>       assert 1 == 2
E       assert 1 == 2
    @pytest.fixture(autouse=True)
    def fixture1():
>       assert 1 == 2
E       assert 1 == 2
    def wrapper():
>       assert 1 == 2
E       assert 1 == 2

我只需要替换pytest项的
runtest
方法。

如何做什么?你想实现什么?我想在收集阶段装饰模块中的每个函数,我不想用测试来编辑模块-只有
conftest.py
文件。好的,但目的是什么?我有测试类,其中包含测试和设置方法。我需要在收集阶段刚结束时运行模块中的所有设置方法-制作共享夹具-并存储设置方法的结果,以便根据测试方法进行测试。不,谢谢;请用一个实际显示您试图解决的问题的答案编辑问题,以避免出现错误。谢谢您的回答,但这不是我想要的。在收集阶段,我需要在模块中修饰每个函数。另外,我不想用test编辑模块-只想编辑
confrest.py
文件。对不起,这个问题不太清楚。