我想在 conftest.py
中编写一个 Pytest 固定装置,该装置在其内部调用一个函数,该函数默认情况下不执行任何操作,但可以在测试模块中重新定义。
#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
有没有一种干净的方法来实现这个?
最佳答案
您可以通过继承来实现这一点。为所有测试创建一个基类,然后您可以决定要在哪些测试中覆盖 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
关于python - 从 Pytest fixture 中调用自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59983900/