TOC

pytest 学习

tmuxp 提了一个 Issue, 作者 @tony (Tony 老师?😜) 让我选择是自己写测试,还是他来写。
我表达我对 pytest 不熟之后,他给我一点建议:

所以我先学习学习,然后抽空把 test 自己写了。

pytest 概况

img

基本用法

安装

pip install pytest pytest-html

测试代码

测试文件发现规则:Conventions for Python test discovery

简单来说,

  1. 如果没有指定路径,就从当前路径开始检查
  2. 测试文件:test_*.py, *_test.py
  3. 类名:Test* (没有 __init__ 方法)
  4. 函数名: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 ...

其他

  1. print 的话,会输出在 --- Captured stdout call --- 部分。

    --capture=no
    --capture=sys
    
  2. 标准错误在 --- Captured stderr call --- 部分。

  3. logging 在 --- Captured stdlog call --- 部分。
    1. 默认 warning 级别,可以 --log-level=debug
  4. 日志格式:--log-format="%(asctime)s %(levelname)s [%(name)s:%(funcName)s#%(lineno)s] %(message)s"
  5. 注意,只有用例错误才会输出 stdout, stderr, stdlog
    1. 如果想看详细信息,导出 HTML 报告,用浏览器打开看,效果更好。
  6. 需要跳过的用例:pytest.mark.skip