解決 Python 使用 Coverage.py 產生程式碼測試覆蓋率報告 (coverage report) 遇到的問題
[問題1] coverage: command not found
問題狀況:
[問題2] No data to report
問題狀況:
問題狀況:
[問題4] Module xxx was never imported. (module-not-imported)
問題狀況:
專案的檔案目錄結構,部分參考 Python 單元測試(Unit Testing) – 在電梯裡遇見雙胞胎
參考資料
[問題1] coverage: command not found
問題狀況:
$ coverage report -m解決方式: 安裝 coverage
/bin/bash: line 73: coverage: command not found
$ php install coverage安裝完可以輸入以下指令,確認已經完成安裝
$ coverage --version
Coverage.py, version 4.5.1 with C extension
Documentation at https://coverage.readthedocs.io
[問題2] No data to report
問題狀況:
# 目錄結構: test/test.test_calc.py解決方式: 原本 python -m 改成 coverage run -m
$ python -m unittest test.test_calc
$ coverage report -m
Name Stmts Miss Cover Missing
-------------------------------------
No data to report.
$ coverage run -m unittest test.test_calc[問題3] 執行測試的是 test_calc ,卻出現其他 python 程式的覆蓋率結果
問題狀況:
$ coverage report -m解決方式: 使用 --include 變數,指定要測試的檔案名稱
Name Stmts Miss Cover Missing
-----------------------------------------------------------------------------------------------------------
mylib/__init__.py 2 0 100%
mylib/calc.py 5 0 100%
mylib/another.py 9 5 44% 8-15
test/__init__.py 2 0 100%
test/test_calc.py 16 1 94% 24
test/test_another.py 13 6 54% 7, 10, 13-15, 18
$ coverage run --include ./mylib/calc.py -m unittest test.test_calc
[問題4] Module xxx was never imported. (module-not-imported)
問題狀況:
$ coverage run -a --source mylib/calc.py test/test_calc.py解決方式: --source 變數是指定要使用的資料夾、要指定檔案需要改成使用 --include 變數
Traceback (most recent call last):
File "test/test_calc.py", line 2, in
from mylib.calc import Calculator
ModuleNotFoundError: No module named 'mylib'
Coverage.py warning: Module mylib/calc.py was never imported. (module-not-imported)
$ coverage run --include ./mylib/calc.py -m unittest test.test_calc
專案的檔案目錄結構,部分參考 Python 單元測試(Unit Testing) – 在電梯裡遇見雙胞胎
- mylib/calc.py
- mylib/another.py
- test/test_calc.py
- test/test_another.py
參考資料
- Specifying source files — Coverage.py 4.5.1 documentation
- 5. Increase Test Coverage — Python Developer's Guide
- ned / coveragepy / issues / #567 - "--source Coverage.py warning: Module xxx.py was never imported" using "-m unittest discover -v tests" on CircleCI Fails — Bitbucket
作者已經移除這則留言。
回覆刪除nice blog.
回覆刪除