通過代碼實例解析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退出之前的階段。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM