pytest插件探索——hook workflow

5次阅读

共计 2513 个字符,预计需要花费 7 分钟才能阅读完成。

pytest 插件开发需要熟悉一些常用的 hook 函数,官方对于这些 hook 有一份简略的文档(目前除了小部分 hook 目前缺乏文档外,见这个 issue),但是各个 hook 的调用逻辑没有一个直观的 flowchart(这个也有人提了 issue)
根据 pytest core developer-Bruno Oliveira 的提示,通过使用向 pytest 传递 –debug 选项然后运行测试,我们就可以在当前目录得到一个类似如下内容的 pytestdebug.log:
versions pytest-4.3.0, py-1.8.0, python-3.6.4.final.0cwd=E:Devdebug_pytestargs=[‘tests\test_setup.py’, ‘–debug’]pytest_cmdline_main [hook]​ config: <_pytest.config.Config object at 0x000002119BA91080> pytest_plugin_registered [hook]​ plugin: <Session debug_pytest>​ manager: <_pytest.config.PytestPluginManager object at 0x000002119B22BD30> finish pytest_plugin_registered –> [][hook] pytest_configure [hook]​ config: <_pytest.config.Config object at 0x000002119BA91080>​ pytest_plugin_registered [hook]

经过多次反复测试分析 debug 文件,整理出了一个 xmind 的思维导图:
链接: https://pan.baidu.com/s/1owWI… 提取码: 69ks
另附 pytest 的个人总结 xmind 图:
链接: https://pan.baidu.com/s/18l6J… 提取码: uwnd
结合导图再梳理一下(建议配合网盘里的 xmind 图看),大体整个测试分成如下 6 个阶段:

pytest_configure
插件和 conftest.py 文件配置初始化等,创建 session。

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

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): 有测试项被关键字或者 marker 过滤掉的时候会被调用注意:通过:: 语法筛选测试用例的步骤是在之前生成测试用例阶段完成的,并不是在 deselected 里面做的

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

pytest_runtest_logstart(nodeid, location):开始执行一个新测试项的时候调用. 注:官方文档的意思表述的有点模糊,并不是 setup/call/teardown 阶段分别调用一次,就是函数命令一直的意思测试开始前打印一次

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 对象, 这里的 call object 我们一般不太接触,_pytest/runner.py 里面有具体的用法可以参考。

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

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

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

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

正文完
 0