python - 模块范围的夹具被每个测试功能调用
问题描述
pytest 正在为每个预期的测试功能调用模块级夹具,每个模块只应调用一次夹具
#content of test_fin.py
import pytest
import time
import logging
@pytest.fixture
def do_setup_tear(scope="module"):
logging.getLogger().info('doing setup stuff if needed')
yield None
logging.getLogger().info('teardown')
def test_do_this():
time.sleep(5)
assert True
def test_do_that(do_setup_tear):
time.sleep(5)
assert True
def test_do_thing(do_setup_tear):
time.sleep(5)
assert True
实际结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-5.2.2, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\<username>\PycharmProjects\blabla\tests, inifile: pytest.ini
plugins: allure-pytest-2.8.6
collected 3 items
test_fin.py::test_do_this PASSED [ 33%]
test_fin.py::test_do_that
------------------------------- live log setup --------------------------------
2019-10-25 12:12:36 INFO doing setup stuff if needed
PASSED [ 66%]
------------------------------ live log teardown ------------------------------
2019-10-25 12:12:41 INFO teardown
test_fin.py::test_do_thing
------------------------------- live log setup --------------------------------
2019-10-25 12:12:41 INFO doing setup stuff if needed
PASSED [100%]
------------------------------ live log teardown ------------------------------
2019-10-25 12:12:46 INFO teardown
============================= 3 passed in 15.06s ==============================
我在这里错过了什么吗。如果我修改scope="module"
为 `scope="function" 我会得到相同的输出
解决方案
您如何定义夹具范围存在一个小错误。现在,您将作用域作为参数传递给夹具函数。应该用它就@pytest.fixture
行了。
@pytest.fixture(scope="module")
def do_setup_tear():
logging.getLogger().info('doing setup stuff if needed')
yield None
logging.getLogger().info('teardown')
如果我将 scope="module" 修改为 scope="function" 我会得到相同的输出
这是因为现在function
除非用户指定,否则夹具范围是默认值。
推荐阅读
- javascript - 如何让 VS Code Intellisense 识别 JSDoc 注解?
- typescript - 使用打字稿获取羽毛聊天教程的错误消息“错误:必须向'users.get'方法提供一个ID”
- vue.js - Vue-CLI 和 Visual Studio Code 格式冲突
- authentication - 独立 Blazor WebAssembly 身份验证非常慢
- java - FlowLayout 使标签居中?
- apache-spark - 无法使用 spark 将结果写入 kafka 主题
- api - Invidious API 创建令牌
- android - 如何在 Android 10 中使用 XML 样式更改最左侧“主页”图标的颜色
- xamarin - 如何更改 Xamarin Forms 中控件的视觉状态?
- mysql - 我可以使用 VB 6.0 中的 SQL 语句向 MS Access 记录中插入多个值吗?