• 45-pytest-pytest.main()使用



    前言

    • 前面一直使用命令行运行pytest用例,本篇来学下使用pytest.main()来运行测试用例

    pytest.main()

    • args 传一个list对象,list 里面是多个命令行的参数
    • plugins 传一个list对象,list 里面是初始化的时候需注册的插件
    • 不带参数运行
    import pytest
    
    # 等同于命令行执行 pytest
    # 默认运行的是当前目录及子目录的所有文件夹的测试用例
    pytest.main()
    
    • 1
    • 2
    • 3
    • 4
    • 5

    参数运行

    -s: 显示程序中的 print/logging 输出
    -v: 丰富信息模式, 输出更详细的用例执行信息
    -k: 运行包含某个字符串的测试用例。如:pytest -k add XX.py 表示运行 XX.py 中包含 add 的测试用例。
    -q: 简单输出模式, 不输出环境信息
    -x: 出现一条测试用例失败就退出测试。在调试阶段非常有用,当测试用例失败时,应该先调试通过,而不是继续执行测试用例。

    • 在命令行运行带上 -s 参数
     pytest -s -x
    
    • 1
    • pytest.main() 里面等价于
    import pytest
    
    # 带上-s参数
    pytest.main(["-s","-x"])
    
    • 1
    • 2
    • 3
    • 4

    指定测试用例

    • 指定运行 study 文件夹下的全部用例
    pytest study
    
    • 1
    • pytest.main() 里面等价于
    import pytest
    
    # 运行指定文件夹目录
    pytest.main(["study "])
    
    • 1
    • 2
    • 3
    • 4
    • 运行指定的 study/test_77.py 下的全部用例
    pytest study/test_77.py
    
    • 1
    • pytest.main() 里面等价于
    import pytest
    
    # 运行指定py文件
    pytest.main(["study/tset_77.py"])
    
    • 1
    • 2
    • 3
    • 4
    • 运行指定的 study/test_77.py 下的某个用例
    pytest study/test_77.py::tset_01
    
    • 1
    • pytest.main() 里面等价于
    import pytest
    
    # 运行指定py文件下测试用例
    pytest.main(["study/tset_77.py::test_01"])
    
    • 1
    • 2
    • 3
    • 4

    指定plugins参数

    # -*- coding: utf-8 -*-
    # @Time    : 2022/10/22
    # @Author  : 大海
    
    import pytest
    
    
    def test_01():
        """测试用例1"""
        name = '小白'
        age = 28
        city = 'Beijing'
    
        assert name == '小白'
        assert age == 28
        assert city == 'Beijing'
    
    # 自定义插件
    class MyPlugin(object):
        def pytest_sessionstart(self):
            print("*** test run start blog地址 https://blog.csdn.net/IT_heima")
    
    
    if __name__ == '__main__':
    	# 通过 plugins 参数指定加载
        pytest.main(['-s', '-v', 'test_77.py'], plugins=[MyPlugin()])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
  • 相关阅读:
    MySQL表的约束
    2024-Pop!_OS新版本,新桌面环境的消息
    sql:group by和聚合函数的使用
    vlan实验
    flutter card 使用示例
    网口工业相机之丢包问题排查
    【Java基础】方法
    【教师节特辑】做个教师节快乐照片墙吧
    C#设计原则
    视频怎么打上自己的水印
  • 原文地址:https://blog.csdn.net/IT_heima/article/details/127459595