日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Pytest斷言的具體使用_python

作者:cherish1112365 ? 更新時間: 2023-04-10 編程語言

Pytest使用的斷言是使用python內(nèi)置的斷言assert。Python assert(斷言)用于判斷一個表達式,在表達式條件為 false 的時候觸發(fā)異常。即pytest測試結果為False的斷言為斷言失敗即測試用例執(zhí)行失敗,反之為斷言成功即測試用例執(zhí)行成功。

斷言使用場景:

  • 為測試結果作斷言
  • 為斷言不通過的結果添加說明信息
  • 為預期異常作斷言
  • 為失敗斷言作自定義說明信息

assert斷言方法

assert關鍵字后面接表達式,常用的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

示例:

# 為測試結果作斷言
?
import pytest
from func import *
?
class TestFunc:
?def test_add_by_class(self):
? assert add(2,3) == 5
# 為斷言不通過的結果添加說明信息
?
def test_login():
? ? # 使用python內(nèi)置的斷言
?? ?# "1是不等于2的"是斷言失敗后,拋出異常輸出的自定義提示信息
? ? assert 1 == 2, "1是不等于2的"
? ??
test_login()
?
# 運行結果:
AssertionError: 1是不等于2的

異常斷言Excepiton

異常斷言即為斷言拋出的異常是預期的異常,執(zhí)行的測試用例是成功的。

使用pytest.raises()作為上下文管理器。當拋出異常時,可獲取到對應的異常實例,然后斷言它拋出的異常是不是預期的異常。當代碼拋出異常時,如果和raises指定的異常類相匹配,則斷言不會失敗。

官方文檔:How to write and report assertions in tests — pytest documentation

?with pytest.raises()執(zhí)行結束后會生成一個ExceptionInfo的實例對象,該對象包含type , value, traceback屬性。

# 變量存儲該異常的所有信息
with pytest.raises(TypeError) as 變量: 
    # 獲取變量的所有屬性,即type、value、traceback
    print(變量.__dict__)

注意:斷言type的時候,異常類型是不需要加引號的。斷言value值的時候需轉換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
 
 # 異常測試用例,期望結果為拋出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:
    # 異常測試用例,期望結果為爆出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關鍵字參數(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:
    # 異常測試用例,期望結果為爆出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)

原文鏈接:https://blog.csdn.net/cherish1112365/article/details/128028225

欄目分類
最近更新