Pytest是一个创建简单且可扩展测试的一个测试框架,其测试表述性强可读性好,且很高效,可以在很短的时间内对你的库和应用构建简单的单元测试和复杂的功能测试。
启动虚拟环境并使用‘pip install pytest’来安装pytest, 使用‘pytest --version’来验证安装成功。过程如下:
[wlin@wlin pytest]$ virtualenv test_pytest
Using base prefix '/usr/local'
New python executable in /home/wlin/pytest/test_pytest/bin/python3.5
Also creating executable in /home/wlin/pytest/test_pytest/bin/python
Installing setuptools, pip, wheel...
done.
[wlin@wlin pytest]$ source test_pytest/bin/activate
(test_pytest) [wlin@wlin pytest]$ pip install pytest
Installing collected packages: six, pyparsing, packaging, py, attrs, iniconfig, pathlib2, toml, zipp, importlib-metadata, pluggy, pytest
Successfully installed attrs-20.2.0 importlib-metadata-2.0.0 iniconfig-1.0.1 packaging-20.4 pathlib2-2.3.5 pluggy-0.13.1 py-1.9.0 pyparsing-2.4.7 pytest-6.1.0 six-1.15.0 toml-0.10.1 zipp-1.2.0
(test_pytest) [wlin@wlin pytest]$ pytest --version
pytest 6.1.0
构建第一个测试脚本
在当前目录下创建test_sample.py并直接执行pytest,过程如下:
(test_pytest) [wlin@wlin pytest]$ vi test_sample.py
(test_pytest) [wlin@wlin pytest]$ cat test_sample.py
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
(test_pytest) [wlin@wlin pytest]$ pytest
=============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.5.2, pytest-6.1.0, py-1.9.0, pluggy-0.13.1
rootdir: /home/wlin/pytest
collected 1 item
test_sample.p

Pytest是一个强大的测试框架,易于创建和扩展测试。本文介绍了如何开始使用Pytest,包括安装、构建第一个测试脚本和测试类。测试脚本的创建涉及pytest对test_开头的函数和文件的自动发现,而测试类允许更好地组织和隔离测试用例。使用assert进行断言检查,pytest.raises用于捕获异常,确保测试的正确性。
最低0.47元/天 解锁文章
4339

被折叠的 条评论
为什么被折叠?



