pytest 3.1
版本新增特性
1. 告警信息的默认捕获行为
pytest
可以自动捕获测试中产生的告警信息,并在执行结束后进行展示;
下面这个例子,我们在测试中人为的产生一条告警:
# src/chapter-8/test_show_warning.py
import warnings
def api_v1():
warnings.warn(UserWarning('请使用新版本的API。'))
return 1
def test_one():
assert api_v1() == 1
我们也可以通过-W arg
命令行选项来自定义告警的捕获行为:
arg
参数的格式为:action:message:category:module:lineno
;
action
只能在"error", "ignore", "always(all)", "default", "module", "once"
中取值,默认取值为default
;category
必须是Warning
的子类,默认取值为Warning
类,表示所有的告警;module
必须为字符串,表示特定模块产生的告警信息;
下面是一些常见的使用场景:
-
忽略某一种类型的告警信息;例如,忽略
UserWarning
类型的告警(-W ignore::UserWarning
):λ pipenv run pytest -W ignore::UserWarning src/chapter-8/test_show_warnings.py ============================ test session starts ============================= platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0 rootdir: D:\Personal Files\Projects\pytest-chinese-doc collected 1 item src\chapter-8\test_show_warnings.py . [100%] ============================= 1 passed in 0.02s ==============================
-
将某一种类型的告警转换为异常来处理;例如,将
UserWarning
告警转换为异常处理(-W error::UserWarning
):λ pipenv run pytest -W error::UserWarning src/chapter-8/test_show_warnings.py ============================ test session starts ============================= platform win32 -- Python 3.7.3, pytest-5.1.3, py-1.8.0, pluggy-0.13.0 rootdir: D:\Personal Files\Projects\pytest-chinese-doc collected 1 item src\chapter-8\test_show_warnings.py F [100%] ================================== FAILURES ================================== __________________________________ test_one __________________________________ def test_one(): > assert api_v1() == 1 src\chapter-8\test_show_warnings.py:31: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def api_v1(): > warnings.warn(UserWarning('请使用新版本的API。')) E UserWarning: 请使用新版本的API。 src\chapter-8\test_show_warnings.py:26: UserWarning ============================= 1 failed in 0.05s ============================