首页 > 解决方案 > 从 Pytest 夹具中调用自定义函数

问题描述

我想编写一个 Pytest 固定装置,conftest.py它本身调用一个函数,默认情况下,它什么都不做,但可以在测试模块中重新定义。

#conftest.py

def within_foo():
    pass

@pytest.fixture
def foo():
    if some_condition():
        within_foo()
    something_else()


# test_foo.py

def within_foo():
    print('this should be printed when running test_foo')

def test_foo(foo):
    pass

有没有一种干净的方法来实现这一点?

标签: pythonpytestfixtures

解决方案


您可以通过继承来完成此操作。为所有测试创建一个基类,然后您可以决定要覆盖哪些测试within_foo()

class BaseTest:

    @pytest.fixture
    def foo(self):
        self.within_foo()

    def within_foo(self):
        pass

@pytest.mark.testing
class TestSomething(BaseTest):

    def within_foo(self):
        print('this should be printed when running test_foo')

    def test_foo(self, foo):
        pass

@pytest.mark.testing
class TestSomethingElse(BaseTest):

    def test_foo_again(self, foo):
        print('test_foo_again')

输出

========================== 2 passed in 0.08 seconds ===========================
this should be printed when running test_foo
.test_foo

.test_foo_again

推荐阅读