python - 从 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
有没有一种干净的方法来实现这一点?
解决方案
您可以通过继承来完成此操作。为所有测试创建一个基类,然后您可以决定要覆盖哪些测试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
推荐阅读
- c++ - 带有 flto 的 RHEL 8 上的 C++ 字符串段错误(但不是 RHEL 7)
- javascript - 如何在 React 中每秒增加一个状态变量
- react-native - 使用 react native Flatlist 显示来自文件名数组的图像
- python - 我正在安装用语 ctcdecode 并收到此错误
- sql-server - 修改大型数据库的策略
- typescript - 如何解决最大内存超出错误
- python - setup.cfg 元数据中的“版本”条目被忽略
- python - 通过 python 脚本运行 Heroku CLI 命令
- flutter - 类型'String'不是嵌套JSON中'index'类型'int'的子类型
- java - 当我将 LocalDate 格式化为 dd.MMM.YYYY 我得到 01.Jan..2000 有两个点