Pytest斷言的具體使用
Pytest使用的斷言是使用python內(nèi)置的斷言assert。Python assert(斷言)用于判斷一個表達式,在表達式條件為 false 的時候觸發(fā)異常。即pytest測試結(jié)果為False的斷言為斷言失敗即測試用例執(zhí)行失敗,反之為斷言成功即測試用例執(zhí)行成功。
斷言使用場景:
- 為測試結(jié)果作斷言
- 為斷言不通過的結(jié)果添加說明信息
- 為預期異常作斷言
- 為失敗斷言作自定義說明信息
assert斷言方法
assert關(guān)鍵字后面接表達式,常用的assert斷言方法如下:
- 判斷xx為真:assert xx
- 判斷xx不為真:assert not xx
- 判斷b包含a:assert a in b
- 判斷b不包含a:assert a not in b
- 判斷a等于b:assert a == b
- 判斷a不等于b:assert a != b
示例:
# 為測試結(jié)果作斷言 ? import pytest from func import * ? class TestFunc: ?def test_add_by_class(self): ? assert add(2,3) == 5
# 為斷言不通過的結(jié)果添加說明信息 ? def test_login(): ? ? # 使用python內(nèi)置的斷言 ?? ?# "1是不等于2的"是斷言失敗后,拋出異常輸出的自定義提示信息 ? ? assert 1 == 2, "1是不等于2的" ? ?? test_login() ? # 運行結(jié)果: AssertionError: 1是不等于2的
異常斷言Excepiton
異常斷言即為斷言拋出的異常是預期的異常,執(zhí)行的測試用例是成功的。
使用pytest.raises()作為上下文管理器。當拋出異常時,可獲取到對應(yīng)的異常實例,然后斷言它拋出的異常是不是預期的異常。當代碼拋出異常時,如果和raises指定的異常類相匹配,則斷言不會失敗。
官方文檔:How to write and report assertions in tests — pytest documentation
with pytest.raises()執(zhí)行結(jié)束后會生成一個ExceptionInfo的實例對象,該對象包含type , value, traceback屬性。
# 變量存儲該異常的所有信息
with pytest.raises(TypeError) as 變量:
# 獲取變量的所有屬性,即type、value、traceback
print(變量.__dict__)
注意:斷言type的時候,異常類型是不需要加引號的。斷言value值的時候需轉(zhuǎn)換str類型,value屬性可作異常的說明信息。
示例如下:
import pytest
def test_zero_division_long():
with pytest.raises(ZeroDivisionError) as excinfo:
1 / 0
# 斷言異常類型 type
assert excinfo.type == ZeroDivisionError
# 斷言異常 value 值
assert "division by zero" in str(excinfo.value)
with pytest.raise(ZeroDivisionError)用于對于故意測試異常代碼的情況(已知異常),斷言通過用例執(zhí)行成功顯示passed,不通過會顯示failed。
示例如下:
# 為預期異常作斷言完整示例,執(zhí)行用例為True
# ./func.py
def add(a,b):
if isinstance(a,int) and isinstance(b,int):
return a+b
else:
raise TypeError('數(shù)據(jù)類型錯誤')
# ./test_case/test_func.py
import pytest
from func import *
class TestFunc:
# 正常測試用例
def test_add_by_class(self):
assert add(2,3) == 5
# 異常測試用例,期望結(jié)果為拋出TypeError異常
def test_add_by_func_aaa(self,*args, **kwargs):
with pytest.raises(TypeError) as E:
add('3',4)
print(E.type)
print(E.value)
print(E.traceback)
# ./run_test.py
import pytest
if __name__ == '__main__':
pytest.main(['-v'])# 木有拋出預期異常的示例,執(zhí)行用例為False
# ./func.py
def add(a,b):
# 指定異常,從此處直接拋出異常
raise NameError("名稱錯誤")
if isinstance(a,int) and isinstance(b,int):
return a+b
else:
raise TypeError('數(shù)據(jù)類型錯誤')
# ./test_case/test_func.py
import pytest
from func import *
class TestFunc:
# 異常測試用例,期望結(jié)果為爆出TypeError異常
def test_add_by_func_aaa(self,*args, **kwargs):
with pytest.raises(TypeError):
add('3',4)
# ./run_test.py
import pytest
if __name__ == '__main__':
pytest.main(['-v'])可將match關(guān)鍵字參數(shù)傳遞給上下文管理器pytest.raises(),來測試正則表達式與異常的信息表達形式是否匹配。match方法相當于re.search功能。
注意:這種方法只能斷言value,不能斷言type。
示例如下:
import pytest
def test_zero_division_long():
with pytest.raises(ZeroDivisionError, match=".*zero.*") as excinfo:
1 / 0
# match方法相當于re.search功能,即match="zero"也是允許的
def test_zero_division_long():
with pytest.raises(ZeroDivisionError, match="zero") as excinfo:
1 / 0
pytest. raised()函數(shù)還有另一種形式,在這里傳遞一個函數(shù),該函數(shù)將使用給定的*args和**kwargs執(zhí)行,并斷言引發(fā)了給定的異常。在沒有異常或錯誤異常的情況下,報告器將為您提供有用的輸出。
pytest.raises(ExpectedException, func, *args, **kwargs)
斷言某個測試用例中可能出現(xiàn)多個不同的預期異常的解決辦法:
在with pytest.raises()中傳入異常類型的參數(shù),從傳入一個異常類型,改變?yōu)閭魅胍粋€異常類型組成的元組。同樣只是傳入一個參數(shù)。
示例如下:
# ./func.py
def add(a,b):
raise NameError('名字錯了')
if isinstance(a,int) and isinstance(b,int):
return a+b
else:
raise TypeError('數(shù)據(jù)類型錯誤')
# ./test_case/test_func.py
import pytest
from func import *
class TestFunc:
# 異常測試用例,期望結(jié)果為爆出TypeError異常
def test_add_by_func_aaa(self,*args, **kwargs):
# 將預期中多個錯誤信息組成一個元組
with pytest.raises((TypeError,NameError),match=r'.*錯.*$') as E:
add('3',4)
# ./run_test.py
import pytest
if __name__ == '__main__':
pytest.main(['-v'])檢查斷言裝飾器
檢查異常裝飾器@pytest.mark.xfail():用于對于檢查未修復的錯誤,即可能發(fā)生的異常。斷言通過用例執(zhí)行成功會顯示xfailed,不通過顯示failed。
作用:檢查是否有異常,不確定是否有異常。
示例如下:
# 單個異常時斷言裝飾器使用
@pytest.mark.xfail(raises=ZeroDivisionError)
def test_f():
1 / 0
# 多個異常時斷言裝飾器使用
@pytest.mark.xfail(raises=(TypeError, NameError))
def test_add_by_func_aaa2():
add("3", 4)
到此這篇關(guān)于Pytest斷言的具體使用的文章就介紹到這了,更多相關(guān)Pytest斷言內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何在Python中利用matplotlib.pyplot畫出函數(shù)圖詳解
通過圖像可以直觀地學習函數(shù)變化、分布等規(guī)律,在學習函數(shù)、概率分布等方面效果顯著,下面這篇文章主要給大家介紹了關(guān)于如何在Python中利用matplotlib.pyplot畫出函數(shù)圖的相關(guān)資料,需要的朋友可以參考下2022-08-08
Python GUI編程之tkinter模塊Toplevel控件實現(xiàn)搭建父子窗口
這篇文章主要介紹了Python使用tkinter模塊Toplevel控件搭建父子窗口的實現(xiàn)方法,Tkinter是Python的標準GUI庫,Python使用Tkinter可以快速的創(chuàng)建GUI應(yīng)用程序,用到相關(guān)控件的同學可以參考下2023-12-12
PyTorch詳解經(jīng)典網(wǎng)絡(luò)ResNet實現(xiàn)流程
ResNet全稱residual neural network,主要是解決過深的網(wǎng)絡(luò)帶來的梯度彌散,梯度爆炸,網(wǎng)絡(luò)退化(即網(wǎng)絡(luò)層數(shù)越深時,在數(shù)據(jù)集上表現(xiàn)的性能卻越差)的問題2022-05-05

