Pytest 入门一 编写第一个测试脚本和测试类

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值