背景
我們有部分正式代碼是採用python編寫,這部分代碼也是需要TDD的,因此,需要找到一個好用的測試架構。 架構選擇
python的測試載入器大全:
https://wiki.python.org/moin/PythonTestingToolsTaxonomy
python主流的測試載入器橫向比較
http://docs.python-guide.org/en/latest/writing/tests/
http://pythontesting.net/test-podcast/
根據下面這篇文章,我們決定使用pytest
http://mathieu.agopian.info/presentations/2015_06_djangocon_europe/?full#cover
pytest的官方資料
http://wiki.zte.com.cn/pages/viewpage.action?pageId=38150854 CI的整合
普通的pytest安裝是沒有包含覆蓋率的
pip install pytest
pytest覆蓋率需要額外安裝
pip install pytest-cov
這時,新增了py.test命令,這是原來pytest命令基礎上封裝的,新增了覆蓋率功能。
例子示範:
py.test test_conf2bin.py --junit-xml=test_conf2bin_report.xml --cov-report=html --cov-config=.coveragerc --cov=./
test_conf2bin.py是目標測試檔案 –junit-xml=test_conf2bin_report.xml是產生junit格式的test_conf2bin_report.xml –cov-report=html 輸出html的報告 –cov-config=.coveragerc 使用.coveragerc設定檔(py.test是基於coverage.py實現的,因此支援coverage.py的設定檔)
–cov=./ 這個是必要的,如果沒有這個,將無法輸出html的報告
.coveragerc這個檔案可以讓py.test實現更多進階的功能,實現舉例如下:
[run]branch = True[report]include = conf2bin.py[html]directory = python_coverage_report
[report]
include = conf2bin.py
由於py.test會計算一個檔案夾裡的所有檔案,如果只需要統計conf2bin.py這個檔案的覆蓋率,則可以這麼寫
[html]
directory = python_coverage_report
指的是html的輸出檔案夾 最後
pytest個人試用,確實很好用,比內建的測試架構強多了