本文介绍pytest.main运行测试用例的方法
pytest.main():main中传入不同的指令用以执行指定测试用例
-s: 显示程序中的print/logging输出
-v: 丰富信息模式, 输出更详细的用例执行信息
-q: 安静模式, 不输出环境信息
-k:关键字匹配,用and区分:匹配范围(文件名、类名、函数名)
示例
test_module1.py
def test_m1_1():print('这是 subpath1/test_module1.py::test_m1_1')assert 1==1def test_m1_2():print('这是 subpath1/test_module1.py::test_m1_2')assert 2==2def test_spec_1():print ('这是 subpath1/test_module1.py::test_spec_1')assert 2 == 2
test_module2.py
def test_m2_01():print('这是 subpath1/test_module1.py::test_m1_1')assert 1==1class TestM2():def test_m2_02(self):print ('这是 subpath2/test_module2.py::TestM2::test_m2_02')assert 1==1def test_pp(self):print ('这是 subpath2/test_module2.py::TestM2::test_pp')assert 1 == 1
maintest.py
import pytestif __name__ == '__main__':# 运行当前目录下所有(test_*.py 和 *_test.py)pytest.main()
运行结果:
============================= test session starts =============================platform win32 -- Python 3.6.6rc1, pytest-5.4.1, py-1.8.1, pluggy-0.13.1rootdir: E:\study\python\study\BasicKnowledgePoints\s5_frame\f001_pytest_用例运行collected 6 itemssubpath1\test_module1.py ...[ 50%]subpath2\test_module2.py ...[100%]============================== 6 passed in 0.15s ==============================
1、运行指定路径下的用例
pytest.main(['./'])# 运行./目录下所有(test_*.py 和 *_test.py)
pytest.main (['./subpath1']) # 运行./subpath1 目录下用例
pytest.main (['./subpath1/test_module1.py']) # 运行指定模块
pytest.main (['./subpath1/test_module1.py::test_m1_1']) # 运行模块中的指定用例
pytest.main (['./subpath2/test_module2.py::TestM2::test_m2_02']) # 运行类中的指定用例
pytest.main (['-k','pp']) # 匹配包含pp的用例(匹配目录名、模块名、类名、用例名)
pytest.main(['-k','spec','./subpath1/test_module1.py'])# 匹配test_module1.py模块下包含spec的用例
pytest.main(['-k','pp','./subpath2/test_module2.py::TestM2']) # 匹配TestM2类中包含pp的用例
2、运行参数
pytest.main(['-s','./subpath1/test_module1.py']) # -s: 显示程序中的print/logging输出
运行结果:
subpath1\test_module1.py 这是 subpath1/test_module1.py::test_m1_1.这是 subpath1/test_module1.py::test_m1_2.这是 subpath1/test_module1.py::test_spec_1.
pytest.main(['-v','./subpath1/test_module1.py']) # -v: 丰富信息模式, 输出更详细的用例执行信息
运行结果:
subpath1/test_module1.py::test_m1_1 PASSED [ 33%]subpath1/test_module1.py::test_m1_2 PASSED [ 66%]subpath1/test_module1.py::test_spec_1 PASSED [100%]============================== 3 passed in 0.06s ==============================
pytest.main(['-q','./subpath1/test_module1.py']) # -q: 安静模式, 不输出环境信息
运行结果:
...[100%]3 passed in 0.06s
pytest.main(['-v','-s','./subpath1/test_module1.py']) # 多个参数组合
运行结果:
subpath1/test_module1.py::test_m1_1 这是 subpath1/test_module1.py::test_m1_1PASSEDsubpath1/test_module1.py::test_m1_2 这是 subpath1/test_module1.py::test_m1_2PASSEDsubpath1/test_module1.py::test_spec_1 这是 subpath1/test_module1.py::test_spec_1PASSED============================== 3 passed in 0.10s ==============================