- 2022/01/10, pytest 学习
- 2022/02/28, pytest 代码学习
- 2022/05/06, 使用 Jenkins + pytest 执行 Python 项目的自动化测试
- 2022/05/07, pytest 配置
- 2022/07/24, Pytest Mock
给 tmuxp 提了一个 Issue, 作者 @tony (Tony 老师?😜) 让我选择是自己写测试,还是他来写。
我表达我对 pytest 不熟之后,他给我一点建议:
- https://tmuxp.git-pull.com/developing.html should let you set it up.
- pytest documentation
所以我先学习学习,然后抽空把 test 自己写了。
pytest 概况
- 文档:https://docs.pytest.org/en/stable/
中文文档:https://www.osgeo.cn/pytest/(感觉机翻痕迹太严重,还是直接看英文文档吧)
基本用法
安装
pip install pytest pytest-html
测试代码
测试文件发现规则:Conventions for Python test discovery
简单来说,
- 如果没有指定路径,就从当前路径开始检查
- 测试文件:
test_*.py
,*_test.py
- 类名:
Test*
(没有__init__
方法) - 函数名:
test_*
(不一定需要类,可以直接是外层函数)
推荐结构:
tests/
test_app.py
test_view.py
...
测试
pytest # 测试全部
pytest test.py # 指定测试文件
pytest test.py::TestClassA # 指定测试类
pytest test.py::TestClassA::test_method_a # 指定测试方法
生成报告 (HTML)
pytest --html=report.html
实验
mkdir -p /tmp/a/tests/
touch /tmp/a/__init__.py
touch /tmp/a/tests/test_a.py
cat > /tmp/a/tests/test_a.py <<EOF
def inc(x):
return x + 1
def test_inc01():
assert inc(3) == 4
def test_inc02():
assert inc(3) == 5
EOF
cd /tmp/a
cat tests/test_a.py
pytest
pytest tests/test_a.py
pytest tests/test_a.py::test_inc01
pytest tests/test_a.py::test_inc02
# 加入 logging
pytest --log-cli-level=INFO ...
其他
-
print 的话,会输出在
--- Captured stdout call ---
部分。--capture=no --capture=sys
-
标准错误在
--- Captured stderr call ---
部分。 - logging 在
--- Captured stdlog call ---
部分。- 默认 warning 级别,可以
--log-level=debug
- 默认 warning 级别,可以
- 日志格式:
--log-format="%(asctime)s %(levelname)s [%(name)s:%(funcName)s#%(lineno)s] %(message)s"
- 注意,只有用例错误才会输出 stdout, stderr, stdlog
- 如果想看详细信息,导出 HTML 报告,用浏览器打开看,效果更好。
- 需要跳过的用例:
pytest.mark.skip