更改在pytest中调用固定装置的方式

问题描述 投票:2回答:3

我在conftest.py中遇到问题

@pytest.fixture(scope="function", autouse=True)
@pytest.mark.usefixtures
def pause_on_assert():
    yield
    if hasattr(sys, 'last_value') and isinstance(sys.last_value, AssertionError):
        tkinter.messagebox.showinfo(sys.last_value)

类似地,conftest.py中还有许多其他固定方式,范围为sessionmodule

我的测试用例看起来像这样

test.py

@pytest.fixture(scope="function", autouse=True)
def _wrapper:
    print("pre condition")
    yield
    print("post condition")

def test_abc():
    assert 1==0

问题是我想让conftest.py中的设备在测试用例中的设备yield之前运行

如何更改夹具的执行顺序

python pytest fixtures
3个回答
0
投票

由于您的_wrapper是功能范围的自动使用灯具:它将在相同作用域中的其他灯具之前实例化。因此,修复方法是定义不带_wrapperautouse=True并尝试隐式调用该装饰器,例如:

def test_abc(_wrapper):
    assert 1==0

Autouse source

[更新]如果您无权更改测试套件,建议您擦除所有本地特定的_wrapper并重构conftest指定的夹具以调用_wrapper,因为夹具功能可以使用其他夹具他们自己。您的conftest.py将如下所示:

# conftest.py
@pytest.fixture(scope="function", autouse=True)
def _wrapper(pause_on_assert):
    print("pre condition")
    yield
    print("post condition")

@pytest.fixture()
def pause_on_assert():
    yield
    if hasattr(sys, 'last_value') and isinstance(sys.last_value, AssertionError):
        tkinter.messagebox.showinfo(sys.last_value)

Modularity source


0
投票

这里是在打印“ B”的测试函数之前运行打印“ A”的conftest.py函数的示例。

cd到父目录,在此示例中为py_tests并运行。

pytest -s -v

输出为:

A
setting up
B
PASSED

具有目录结构:

py_tests
 -conftest.py
 -tests
  --tests.py

文件:

conftest.py

import pytest

@pytest.fixture(scope="function")
def print_one():
    print("\n")
    print("A")

test.py

import pytest

class Testonething:

    @pytest.fixture(scope="function", autouse=True)
    def setup(self, print_one):
        print("setting up")


    def test_one_thing(self):
        print("B")
        assert True

0
投票

[如果您想确保一段代码在测试功能之后运行,但在所有固定装置拆除之前,我建议改用pytest_runtest_teardown钩子。将pytest_runtest_teardown中的pause_on_assert灯具替换为:

conftest.py
© www.soinside.com 2019 - 2024. All rights reserved.