pytest文檔57-計算單元測試代碼覆蓋率(pytest-cov)


前言

我們在做測試的時候,經常遇到領導的靈魂拷問:你的測試用例覆蓋率是多少,達到100%了么?你如何保證你的測試質量?
測試用例的覆蓋率如何統計呢,如何知道開發的代碼,我們都測到了,不會存在漏測的情況。

pytest-cov

先命令行安裝 pytest-cov 2.10.1版本

pip install pytest-cov==2.10.1

環境要求:
1.python3.6.6 版本
備注:其它版本沒試過

python3.6.0會遇到以下問題

INTERNALERROR>raise CoverageException("Couldn't use data file {!r}:{}".format(self.filename, msg))
INTERNALERROR> coverage.misc.CoverageException: Couldn't use data file'C:\\Users\\Desktop\\Pytest\\.coverage': 
Safety level may not be changed inside a transaction

解決辦法:安裝3.6.1以上版本

實現功能

在做單元測試時,代碼覆蓋率常常被拿來作為衡量測試好壞的指標,甚至,用代碼覆蓋率來考核測試任務完成情況,
比如,代碼覆蓋率必須達到80%或 90%。於是乎,測試人員費盡心思設計案例覆蓋代碼。
單元測試的方法有:語句覆蓋/判定覆蓋/條件覆蓋/路徑覆蓋

先看一個簡單的案例,前端實現一個功能,根據接口返回的不同code值,判斷支付的結果,給用戶返回提示友好的信息

前端實現功能:根據接口返回的不同code值,判斷支付的結果,給用戶返回提示友好的信息
接口返回格式:
{
    "code": 0,
    "msg": "success!",
    "data": []
}

錯誤碼參照
0 - 成功
30000 - 參數錯誤
30001 - 余額不足
30002 - 達到當天最大額度
201102 - 銀行卡被凍結

實現代碼


'''
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
接口返回格式
{
    "code": 0,
    "msg": "success!",
    "data": []
}

錯誤碼參照
0 - 成功
30000 - 參數錯誤
30001 - 余額不足
30002 - 達到當天最大額度
201102 - 銀行卡被凍結
'''
# pay.py
def pay_status(result):
    '''根據接口返回code狀態,給用戶提示對應的結果'''
    if result.get("code") == 0:
        return "支付成功"
    elif result.get("code") == 30000:
        return "支付失敗: %s" % result.get("msg")
    elif result.get("code") == 30001:
        return "支付失敗: %s" % result.get("msg")
    elif result.get("code") == 30002:
        return "支付失敗: %s" % result.get("msg")
    elif result.get("code") == 201102:
        return "支付失敗: %s" % result.get("msg")
    else:
        return "支付失敗: 系統異常,未知錯誤"

整個項目目錄結構如下

  • src 是項目的源碼
  • tests 是我們寫的單元測試用例
  • src和tests放同一個項目的根目錄下

用例設計

在tests/test_pay.py下寫測試用例,先只寫一個支付成功的案例

from src.pay import pay_status
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/


def test_pay_success():
    result = {
            "code": 0,
            "msg": "success!",
            "data": []
        }
    assert pay_status(result) == "支付成功"

運行用例

運行用例的時候加上 --cov 參數

pytest --cov

運行結果

>pytest --cov
================================================= test session starts =================================================
platform win32 -- Python 3.6.6, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\soft\pytest-demo-cov
plugins: change-report-1.0, cov-2.10.1, html-1.19.0, metadata-1.8.0
collected 1 item

tests\test_pay.py .                                                                                              [100%]

----------- coverage: platform win32, python 3.6.6-final-0 -----------
Name                Stmts   Miss  Cover
---------------------------------------
src\__init__.py         0      0   100%
src\pay.py             13      9    31%
tests\__init__.py       0      0   100%
tests\test_pay.py       4      0   100%
---------------------------------------
TOTAL                  17      9    47%


================================================== 1 passed in 0.10s ==================================================

從報告可以看出src\pay.py 的代碼測試覆蓋率是31%,其它文件都是100%覆蓋,這就說明我們單元測試代碼測試覆蓋率是31%
還有一個指標是測試用例的執行率,測試用例在test_pay.py文件,執行率是100%,說明用例全部執行了。

coverage生成html報告

coverage 相關參數查看,使用pytest -h

> pytest -h
coverage reporting with distributed testing support:
  --cov=[SOURCE]        Path or package name to measure during execution (multi-allowed). Use --cov= to not do any
                        source filtering and record everything.
  --cov-report=TYPE     Type of report to generate: term, term-missing, annotate, html, xml (multi-allowed). term, term-
                        missing may be followed by ":skip-covered". annotate, html and xml may be followed by ":DEST"
                        where DEST specifies the output location. Use --cov-report= to not generate any output.
  --cov-config=PATH     Config file for coverage. Default: .coveragerc
  --no-cov-on-fail      Do not report coverage if test run fails. Default: False
  --no-cov              Disable coverage report completely (useful for debuggers). Default: False
  --cov-fail-under=MIN  Fail if the total coverage is less than MIN.
  --cov-append          Do not delete coverage but append to current. Default: False
  --cov-branch          Enable branch coverage.
  --cov-context=CONTEXT
                        Dynamic contexts to use. "test" for now.

生成html的報告

pytest --cov --cov-report=html

執行完成,在項目根目錄會生成 htmlcov 目錄

運行 index.html 文件查看代碼覆蓋率

點開src\pay.py

想覆蓋率達到100%,那得再繼續寫用例,讓每個if分支情況都覆蓋到

指定被測代碼

如果我們想指定執行項目里面的某個模塊,可以通過--cov=模塊 來運行

pytest --cov=src

>pytest --cov=src
================================================= test session starts =================================================
platform win32 -- Python 3.6.6, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\soft\pytest-demo-cov
plugins: change-report-1.0, cov-2.10.1, html-1.19.0, metadata-1.8.0
collected 1 item

tests\test_pay.py .                                                                                              [100%]

----------- coverage: platform win32, python 3.6.6-final-0 -----------
Name              Stmts   Miss  Cover
-------------------------------------
src\__init__.py       0      0   100%
src\pay.py           13      9    31%
-------------------------------------
TOTAL                13      9    31%


================================================== 1 passed in 0.07s ==================================================

也可以指定具體的py模塊名稱

pytest --cov=src.pay

但不能寫成pytest --cov=src/pay.py


免責聲明!

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



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