青蛙小白
目录

pytest

第三方测试框架pytest已经成为Python单元测试的事实标准。

  • 使用pytest编写的测试可读性很强,大部分测试的编写都直接使用函数和断言(assert)等python语言原语,就好像没有使用框架一样
  • pytest提供测试辅助工具、支持参数化测试
  • pytest可扩展,带有丰富的插件生态系统

官方文档

用pytest编写的测试是名称以test开头的函数

项目中添加pytest依赖

poetry add --group=tests pytest
# content of test_sample.py
def inc(x):
    return x + 1


def test_answer():
    assert inc(3) == 4

运行测试:

# 或 python -m pytest
pytest

可测试性设计

好的测试不仅可以捕捉错误,还可以改进代码的设计。

评论