pytest運行流程


pytest的整個測試分成如下6個階段:

pytest_configure

  插件和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): 有測試項被關鍵字或者marker過濾掉的時候會被調用

注意: 通過::語法篩選測試用例的步驟是在之前生成測試用例階段完成的,並不是在deselected里面做的

4、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屬性來區分不同階段。

5、pytest_sessionfinish

  所有測試執行完畢之后,返回exit status之前的階段。會調用pytest_terminal_summary向terminal打印一些summary信息,比如pass, fail, error數量之類的總結信息。

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    '''收集測試結果'''
    print(terminalreporter.stats)
    print("total:", terminalreporter._numcollected)
    print('passed:', len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown']))
    print('failed:', len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown']))
    print('error:', len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown']))
    print('skipped:', len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown']))
    # terminalreporter._sessionstarttime 會話開始時間
    duration = time.time() - terminalreporter._sessionstarttime
    print('total times:', duration, 'seconds')

6、pytest_unconfigure

  session結束以后,整個process退出之前的階段。

 

 


免責聲明!

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



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