[英]Call custom function from within Pytest fixture
I would like to write a Pytest fixture in conftest.py
that, within itself, calls a function that, by default, does nothing but can be redefined in test modules.我想在
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
Is there a clean way to implement this?有没有一种干净的方法来实现这一点?
You can accomplish this with inheritance.您可以通过继承来实现这一点。 Create a base class for all tests, than you can decide in which tests you want to override
within_foo()
为所有测试创建一个基类,然后您可以决定要在哪些测试中覆盖
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')
Outout输出
========================== 2 passed in 0.08 seconds ===========================
this should be printed when running test_foo
.test_foo
.test_foo_again
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.