真實項目中如何使用pytest進行單元測試(結(jié)合PyCharm)

真實項目中如何使用pytest進行單元測試(結(jié)合PyCharm)

目的

網(wǎng)上很多介紹pytest的文章,但是很少結(jié)合實際開發(fā),多為簡單demo。以下介紹結(jié)合實際項目如何使用。

主要內(nèi)容

  • 創(chuàng)建普通項目
  • 添加pytest依賴
  • 創(chuàng)建測試目錄
  • 執(zhí)行測試
  • 結(jié)合PyCharm
  • 參考文獻

創(chuàng)建普通項目

創(chuàng)建一個項目根目錄"pytest-demo"

添加項目文件,目錄結(jié)構(gòu)如下


pytest-demo

  • demo
    • __init__.py
      • utils
        • __init__.py
        • math_helper.py

math_helper.py如下

class MathHelper(object):
    def addition(self, first, second):
        """
        加法
        :param first: 第一個參數(shù)
        :param second: 第二個參數(shù)
        :return: 相加后的結(jié)果
        """
        # 先判斷傳入類型
        if not isinstance(first, (int, float)):
            raise ValueError("first參數(shù)必須為數(shù)值")
        if not isinstance(second, (int, float)):
            raise ValueError("second參數(shù)必須為數(shù)值")
        # 返回結(jié)果
        return first + second

添加pytest依賴

$ pip install pytest

添加單元測試目錄

在根目錄下創(chuàng)建單元測試目錄"tests"(注意要創(chuàng)建成package,方便全量測試)

對應(yīng)添加測試類,測試類文件名必須為test_*.py 或 *_test.py,命名規(guī)則可查看pytest官方文檔

最終目錄結(jié)構(gòu)如下


pytest-demo

  • demo
    • __init__.py
      • utils
        • __init__.py
        • math_helper.py
  • tests
    • demo
      • __init__.py
        • utils
          • __init__.py
          • test_math_helper.py

test_math_helper.py如下

import pytest
from demo.utils.math_helper import MathHelper


def test_addition():
    # 初始化
    helper = MathHelper()
    # 輸入錯誤類型,預(yù)期接收ValueError的報錯
    with pytest.raises(ValueError):
        helper.addition("1", 2)
    with pytest.raises(ValueError):
        helper.addition(1, "2")
    # 正確調(diào)用
    result = helper.addition(1, 2)
    # 使用assert判斷結(jié)果
    assert result == 3

執(zhí)行測試用例

$ pytest

即可執(zhí)行所有測試,并給出結(jié)果

結(jié)合PyCharm

  • 設(shè)置PyCharm默認(rèn)測試類型
  1. 打開 File > Settings > Tools > Python Integrated Tools > Testing > Default test runner
  2. 修改下拉框,改為"pytest"
  3. 右鍵單元測試文件,點擊"run",即可執(zhí)行測試,在下方的"Run"窗口也有相應(yīng)的測試結(jié)果
  • 設(shè)置執(zhí)行所有測試
  1. 右鍵"tests"文件夾,選擇"Run"
  2. 接下來就直接跑目錄下所有的測試用例了,在下方的"Run"窗口可以看到測試信息
  3. 如果報錯找不到模塊時,需要打開右上角的編輯啟動項,先刪除舊信息,否則會有緩存

參考文獻

pytest官方文檔

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容