首页 > 解决方案 > 更改在 pytest 中调用固定装置的方式

问题描述

我在 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 中还有许多其他修复程序,其范围为session,module

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

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的夹具在我的测试用例中的夹具之前运行

如何更改夹具执行方式的顺序

标签: pythonpytestfixtures

解决方案


这是在打印“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

推荐阅读