2017-10-21 214 views
1

早些時候,我在我的項目中使用python unittest,並且它來到了unittest.TextTestRunnerunittest.defaultTestLoader.loadTestsFromTestCase。我使用它們的原因如下:閱讀py.test的輸出爲對象

  1. 使用調用unittests的run方法的包裝函數來控制unittest的執行。我不想要命令行方法。

  2. 從結果對象中讀取unittest的輸出並將結果上傳到一個bug跟蹤系統,該系統允許我們生成一些關於代碼穩定性的複雜報告。

最近有決定改用py.test的決定,我該怎麼辦上述使用py.test?我不想解析任何CLI/HTML來從py.test獲取輸出。我也不想在我的單元測試文件上寫太多的代碼來做到這一點。

有人可以幫助我嗎?

回答

2

可以使用pytest的鉤子攔截測試結果報告:

conftest.py

import pytest 

@pytest.hookimpl(hookwrapper=True) 
def pytest_runtest_logreport(report): 
    yield 

    # Define when you want to report: 
    # when=setup/call/teardown, 
    # fields: .failed/.passed/.skipped 
    if report.when == 'call' and report.failed: 

     # Add to the database or an issue tracker or wherever you want. 
     print(report.longreprtext) 
     print(report.sections) 
     print(report.capstdout) 
     print(report.capstderr) 

同樣,你可以攔截這些鉤子一個在需要的階段注入你的代碼(在某些情況下,與嘗試,唯獨身邊yield):

  • pytest_runtest_protocol(item, nextitem)
  • pytest_runtest_setup(item)
  • pytest_runtest_call(item)
  • pytest_runtest_teardown(item, nextitem)
  • pytest_runtest_makereport(item, call)
  • pytest_runtest_logreport(report)

瞭解更多:Writing pytest plugins

所有這一切都可以輕鬆完成要麼作爲一個簡單的安裝庫做了一個小小的插件,或者作爲一個僞插件conftest.py,它只是l在其中一個目錄中進行測試。