Pytest 学习记录

pytest有哪些优点:

  • 允许直接使用assert进行断言,而不需要使用self.assert*
  • 可以自动寻找单侧文件、类和函数
  • Modular fixtures 可以用于管理小型或参数化的测试信息
  • 与unittest和nose单测框架兼容
  • 丰富的插件支持

1.安装

pip install -U pytest
# 检查
pytest --version

 2.运行

在当前目录下输入  pytest ,自动查找 test_*.py 或 *_test.py 形式的所有文件

-v 用于显示每个测试函数的执行结果

-q 只显示整体测试结果

-s 用于显示测试函数中print()函数输出

# 执行单个文件
pytest xxx.py
# 执行文件夹
pytest testing/
# 按节点ID运行
pytest test_mod.py::test_func
pytest test_mod.py::TestClass:test_method
# 按包运行
pytest --pyargs pkg.testing
# 标记表达式,将运行@pytest.mark.slow装饰器修饰的所有测试
pytest -m slow

运行第一次(或N次)失败后停止

pytest -x
pytest --maxfail=2

 3.断言assert

assert x == y

assert x in y

4.扩展插件

1.测试报告

pip install pytest-cov   # 计算 pytest 覆盖率

pytest --cov-report=html --cov=./test_code_target_dir

  • --cov=[path],measure coverage for filesystem path (multi-allowed),指定被测试对象,用于计算测试覆盖率
  • --cov-report=type,type of report to generate:term,term-missing,annotate,html,xml(multi-allowed),测试报告的类型
  • --cov-config=path,config file for coverage,default:.coveragerc,coverage配置文件
  • --no-cov-on-fail,do not report coverage if test run fails,default: False 如果测试失败,不生成测试报告
  • --cov-fail-under=MIN,Fail if the total coverage is less than MIN  如果测试覆盖率低于MIN,则认为失败

2.测试顺序随机

pip install pytest-randomly

3.出错立即返回

pip install pytest-instafail

原文地址:https://www.cnblogs.com/peng-lan/p/11188602.html