pytest-类中测试方法、多文件批量执行

张开发
2026/4/12 1:01:35 15 分钟阅读

分享文章

pytest-类中测试方法、多文件批量执行
pytest-类中测试方法、多文件批量执行,完整、可直接复制运行的写法覆盖测试类 类中方法执行多文件批量执行按标记pytest.mark执行常用组合用法1. 测试类 类中方法在 main 中执行完整代码python运行import pytest # 测试类必须 Test 开头 class TestDemo: def test_case1(self): assert 1 1 2 def test_case2(self): assert pytest in hello pytest # 独立函数 def test_func1(): assert True if __name__ __main__: # 1. 执行当前文件所有用例类函数 pytest.main([__file__, -v, -s]) # 2. 只执行某个类 # pytest.main([__file__ ::TestDemo, -v]) # 3. 只执行某个类里的某个方法 # pytest.main([__file__ ::TestDemo::test_case1, -v])执行路径规则plaintext文件.py::类名::方法名2. 多文件批量执行假设项目结构plaintexttests/ ├── test_login.py ├── test_order.py └── test_pay.py main.py在 main.py 中批量执行python运行import pytest if __name__ __main__: # 1. 执行 tests 目录下所有测试 pytest.main([./tests, -v, -s]) # 2. 执行指定多个文件 # pytest.main([./tests/test_login.py, ./tests/test_order.py, -v]) # 3. 只执行某个文件中的某个用例 # pytest.main([./tests/test_login.py::TestLogin::test_login_success, -v])3. 按标记 pytest.mark 执行常用给用例打标记例如smoke、api、ui。示例代码python运行import pytest pytest.mark.smoke def test_smoke1(): assert True pytest.mark.smoke def test_smoke2(): assert True pytest.mark.api def test_api1(): assert True if __name__ __main__: # 只执行标记为 smoke 的用例 pytest.main([__file__, -m, smoke, -v]) # 执行 smoke 或 api # pytest.main([__file__, -m, smoke or api, -v]) # 执行非 api # pytest.main([__file__, -m, not api, -v])4. 最常用完整 main 模板直接拿去用python运行import pytest if __name__ __main__: pytest.main([ ./tests, # 测试目录 -v, # 详细 -s, # 显示 print -x, # 失败即停止 --htmlreport.html, # 报告 --alluredir./allure-results ])5. 常用执行语法汇总表格场景写法当前文件所有用例pytest.main([__file__])某个测试类文件::TestClass类中某个方法文件::TestClass::test_func某个函数文件::test_func执行目录[./tests]按标记执行-m smoke

更多文章