通过代码实例解析pytest运行流程

pytest的整个测试分成如下六个阶段:

1、 pytest_configure 

pytest插件和conftest.py文件配置初始化等,创建测试session会话

2、 pytest_sessionstart 

创建session完以后,执行collection收集测试用例之前的阶段。会调用 pytest_report_header 向terminal终端打印一些环境信息,比如插件版本,python版本,操作平台这些等。

3、 pytest_collection 

测试用例收集以及生成测试输入的过程,这里还可能包括根据关键字keywords和标签名marker筛选测试用例的过程。

这个过程会涉及多次generate item的调用;主要关注如下调用:

① pytest_generate_tests(metafunc) :生成测试项;

② pytest_make_parametrize_id(config, val, argname) :根据 @pytest.mark.parametrize 参数化生成对应测试项;

③ pytest_collection_modifyitems(session, config, items) :所有测试项收集完毕以后调用,一般用来进行测试用例的重新排序二次过滤

④ pytest_deselected(items) :有部分测试项被关键字keywords或者标签名marker过滤掉的时候调用。

【注意】通过 :: 语法筛选测试用例的步骤是在之前生成测试用例阶段完成的,并不是在deselected里面操作。

4、 pytest_runtestloop 

执行筛选过的测试用例, 在 pytest_runtest_protocol 里面完成包括 setup , call ,  teardown 和 log 打印的过程。主要关注如下调用:

pytest_runtest_logstart(nodeid, location) :开始执行一个新测试项的时候调用。

pytest_runtest_logfinish(nodeid, location) :结束执行一个测试项的时候调用。

pytest_runtest_setup(item) : 在 pytest_runtest_call 执行之前调用。

pytest_runtest_call(item) :执行实际的测试过程。

pytest_runtest_teardow(item, nextitem) : 在pytest_runtest_call执行之后调用。

pytest_fixture_setup(fixturedef, request) :执行fixture函数的setup过程(是否执行取决于fixture是否需要创建)。

pytest_fixture_post_finalizer(fixturedef, request) :执行fixture函数的teardown过程(如果有)。

pytest_runtest_makereport(item, call) :返回给定item测试用例对象和call测试用例的测试步骤对应的 _pytest.runner.TestReport(测试报告对象)对象。【参考博客:pytest获取测试用例执行结果(钩子函数:pytest_runtest_makereport)

pytest_runtest_logreport(report) :在测试的setup/call/teardown阶段report更新之后分别被调用到,可以用when属性来区分测试用例执行的不同阶段。

pytest_report_teststatus(report, config) :返回测试用例的各个测试阶段的result, 可以用when属性来区分不同阶段。

5、 pytest_sessionfinish 

所有测试执行完毕之后,返回 exit status 之前的阶段。会调用 pytest_terminal_summary 向terminal终端打印一些summary信息,比如测试用例的pass,fail,error数量之类的总结信息。

参考博客:【pytest的Hook函数(钩子函数)详解 || pytest统计测试结果(钩子函数:pytest_terminal_summary)

6、 pytest_unconfigure 

session结束以后,整个process退出之前的阶段。

 

posted @ 2022-01-10 17:14  习久性成  阅读(2117)  评论(2编辑  收藏  举报