• Python单元测试




    1、Pytest模块


    Python接口测试的主要模块有:Unittest和Pytest

    Unittest是Python自带的单元测试框架,Pytest是一个第三方单元测试框架,具有丰富的插件生态,兼容Unittest测试集,社区繁荣

    Pytest特性有:

    • Pytest可以和Selenium、Requests、Appium结合实现Web自动化、接口自动化、App自动化

    • Pytest可以实现测试用例的跳过以及reruns失败用例重试

    • Pytest可以和Allure生成非常美观的测试报告

    • Pytest可以和Jenkins持续集成

    例如:

    """
    pytest-html            生成html格式的自动化测试报告
    pytest-xdist           测试用例分布式执行,多CPU分发
    pytest-ordering        用于改变测试用例的执行顺序
    pytest-rerunfailures   用例失败后重跑
    allure-pytest          用于生成美观的测试报告
    pytest-selenium        集成Selenium
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    安装:

    pip install pytest
    
    • 1

    Pytest框架的用例执行入口:

    pytest.main(args参数列表)
    
    • 1

    2、Pytest测试用例的运行参数

    '''
    -s: 显示程序中的print/logging输出
    -v: 丰富信息模式,输出更详细的用例执行信息
    -vs: 该两个参数可一起使用
    -q: 安静模式,不输出环境信息
    -x: 出现一条测试用例失败就退出测试
    -n=num: 多线程或分布式运行测试用例(需要先安装pytest-xdist)
    --html=./report.html: 生成xml/html格式测试报告(需要先安装pytest-html)
    --reruns num:重试运行测试用例(需要先安装pytest-rerunfailures)
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、Pytest测试用例的运行方式


    1) 主函数模式

    '''
    pytest.main()              运行当前目录下所有以test开头或结尾的文件
    pytest.main(['test.py'])   运行指定模块
    pytest.main(['./test'])    运行指定目录
    通过nodeid指定用例运行:nodeid有模块名、分隔符、类名、方法名、函数名组成
    pytest.main(["test.py::Test_Class"])                 指定类名
    pytest.main(["test.py::Test_Class::test_method"])    指定方法
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2) 终端命令行模式

    '''
    pytest                     运行所有,当传入参数-s、-v、-x时,相当于命令行输入pytest -s -v -x
    pytest test.py             运行指定模块
    pytest ./test              运行指定目录
    pytest test.py::Test_Class::test_method       指定方法
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3) 通过pytest.ini配置文件运行

    位置:一般放在项目的根目录

    编码:必须是ANSI,可以使用Notepad++修改编码格式

    作用:改变Pytest默认的行为

    运行规则:不管是主函数的模式运行,还是命令行模式运行,都会去读取这个配置文件

    例如:

    '''
    [pytest]
    # 命令行参数,多个参数使用空格分隔
    addopts = -vs
    # 测试用例文件夹(目录)
    testpaths = ../pytestproject
    # 测试搜索的模块文件名称
    python_files = test*.py
    # 测试搜索的测试类名
    python_classes = Test*
    # 测试搜索的测试函数名
    python_functions = test*
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    4、Pytest测试用例的执行顺序


    Pytest:默认从上到下执行

    改变默认执行顺序:使用mark标记

    @pytest.mark.run
    • 相关阅读:
      电脑重装系统之后设置
      弘辽科技:超级推荐爆款拉新怎么设置?爆款拉新怎么玩?
      Python数据分析将数组的多行元素首尾相连为一行numpy.ravel()
      如何快速搭建Spring Boot接口调试环境并实现公网访问
      什么是aop?
      IO多路转接 ——— select、poll、epoll
      低垂的果子未必好摘
      JS进阶-编程思想
      cuda 换源 ubuntu 就他了 速度很快
      机器视觉系列5:C++部署pytorch模型onnxruntime
    • 原文地址:https://blog.csdn.net/weixin_55629186/article/details/133150530