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()作為上下文管理器。當拋出異常時,可獲取到對應的異常實例,然后斷言它拋出的異常是不是預期的異常。當代碼拋出異常時,如果和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ā)了給定的異常。在沒有異?;蝈e誤異常的情況下,報告器將為您提供有用的輸出。
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基于React-Dropzone實現(xiàn)上傳組件的示例代碼
本文主要介紹了在React-Flask框架上開發(fā)上傳組件的技巧。文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08Python實現(xiàn)Excel表格轉(zhuǎn)置與翻譯工具
本文主要介紹如何使用Python編寫一個GUI程序,能夠讀取Excel文件,將第一個列的數(shù)據(jù)轉(zhuǎn)置,并將英文內(nèi)容翻譯成中文,有需要的小伙伴可以參考一下2024-10-10pyinstaller打包成無控制臺程序時運行出錯(與popen沖突的解決方法)
這篇文章主要介紹了pyinstaller打包成無控制臺程序時運行出錯(與popen沖突的解決方法),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04Python英文文本分詞(無空格)模塊wordninja的使用實例
今天小編就為大家分享一篇關(guān)于Python英文文本分詞(無空格)模塊wordninja的使用實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02