Python单元测试框架:Pytest简介

Pytest简介

  • 入门简单,文档丰富
  • 支持单元测试、功能测试
  • 支持参数化
  • 重复执行,部分执行,测试跳过
  • 兼容其他测试框架(nose,unittest等)
  • 支持生成html报告
  • 可集成CI环境(Jenkins 等)

2、Pytest安装

    import pytest
    class Test_class:
        def test_001(self):
            print('用例001')
            assert 8 == 8
        def test_002(self):
            print('用例002')
            assert 6 == 6
        def test_003(self):
            print('用例003')
            assert 3 == 2
    if __name__ == "__main__":
    # 里面参数需要传list,多个参数放list就不会有警告了
# pytest.main('-q test_class.py')
        pytest.main(['-q', 'test_class.py'])

3、创建一个简单的test案例

    import pytest
    class Test_class:
        def test_001(self):
            print('用例001')
            assert 8 == 8
        def test_002(self):
            print('用例002')
            assert 6 == 6
        def test_003(self):
            print('用例003')
            assert 3 == 2
    if __name__ == "__main__":
    # 里面参数需要传list,多个参数放list就不会有警告了
# pytest.main('-q test_class.py')
        pytest.main(['-q', 'test_class.py'])

执行结果

pytest 中用例的检查点 直接用 Python 的 assert 断言。

assert 后面的表达式结果 为 True ,就是检查点通过,结果为False ,就是检查点不通过。

 

执行测试的时候,我们只需要在测试文件test_class所在的目录下,运行py.test即可。pytest会在当前的目录下,寻找以test开头的文件(即测试文件),找到测试文件之后,进入到测试文件中寻找test_开头的测试函数并执行。

4、Pycharm设置Pytest

#file->Setting->Tools->Python Integrated Tools->项目名称->Default test runner->选择py.test
#右键选择pytest运行或者直接运行.py文件

执行结果

 

 

由上可见:Pytest是可以兼容UnitTest脚本的,之前写的UnitTest用例也能用Pytest框架去运行。

5、Pytest自动生成报告

    # 需预先装上pytest-html
    >>>pip install pytest_html

    # 生成html格式的报告
    >>>pytest -v test_1.py --html=Path

    # 生成xml格式的报告
    >>>pytest -v test_1.py --junitxml=Path

    # 生成txt格式的报告
    >>>pytest -v test_1.py --resultlog=Path

注意:检查运行指令时,路径(根目录)是否正确

参考地址:

https://docs.pytest.org/en/latest/warnings.html

 

 

    生成报告    
    .test_class.py::Test_class::test_001
    .test_class.py::Test_class::test_002
    F
    test_class.py::Test_class::test_003
    self = < test_class.Test_class object at 0x000001582B868978 >
    def test_003(self):
        print('用例003')
    > assert 3 == 2
    E
    assert 3 == 2
    E + 3
    E - 2
    test_class.py: 24: AssertionError

PS:如有需要Python学习资料的小伙伴可以加下方的群去找免费管理员领取

 

可以免费领取源码项目实战视频PDF文件

 

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

作者:顾小鱼

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值