Pythons: Python 3.6, 3.7, 3.8, 3.9, PyPy3
Platforms: Linux and Windows
PyPI package name: pytest
Documentation as PDF: download latest
pytest 是一个框架,它使构建简单且可扩展的测试变得容易。测试具有表现力和可读性——不需要样板代码。在几分钟内开始对您的应用程序或库进行小型单元测试或复杂的功能测试。
安装pytest
在命令行中运行以下命令:
pip install -U pytest
检查您是否安装了正确的版本:
$ pytest --version
pytest 6.2.4
创建您的第一个测试
只用四行代码创建一个简单的测试函数:
# content of test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
这样就可以了。您现在可以执行测试方法:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-6.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 func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:6: AssertionError
========================