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