pytest 是一个功能齐全的 Python 测试工具,可以帮助编写更好的程序,不仅可以编写小测试,还可以扩展到复杂的功能测试。
特性:
有关失败的断言语句的详细信息(无需记住 self.assert* names)
自动发现测试模块和功能
模块化式具,用于管理小型或参数化的长期测试资源
可以开箱即用运行单元测试、Nose 测试套件
Python 3.5+ 与 PyPy3;
丰富的插件架构,拥有 850 多个外部插件和繁荣的社区
简单 demo:
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
运行该测试:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_sample.py F [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________
def test_answer():
> assert inc(3) == 5
E assert 4 == 5
E + where 4 = inc(3)
test_sample.py:6: AssertionError
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 4 == 5
============================ 1 failed in 0.12s =============================