从 Pytest 夹具中调用自定义函数
Call custom function from within Pytest fixture
我想在 conftest.py
中编写一个 Pytest fixture,它在自身内部调用一个函数,默认情况下,该函数不执行任何操作,但可以在测试模块中重新定义。
#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
有没有一种干净的方法来实现这个?
您可以通过继承来实现这一点。为所有测试创建一个基础 class,然后您可以决定要覆盖哪些测试 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
我想在 conftest.py
中编写一个 Pytest fixture,它在自身内部调用一个函数,默认情况下,该函数不执行任何操作,但可以在测试模块中重新定义。
#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
有没有一种干净的方法来实现这个?
您可以通过继承来实现这一点。为所有测试创建一个基础 class,然后您可以决定要覆盖哪些测试 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