[接口測試_B] 04 Pytest斷言處理_告警斷言

pytest中對告警進行斷言采用pytest.warns()方法,其斷言的方法與pytest.raises()類似。pytest.warns()除了能斷言告警外,還能夠捕獲告警信息,并對捕獲的告警信息進行分類處理,可以設定出現(xiàn)特定告警信息時,則用例執(zhí)行失敗。

Pytest的pytest.warns()用法

  • pytest.warns()斷言告警信息
  • pytest.warns()捕獲告警信息,并對告警信息進行判斷
  • pytest.warns()記錄告警信息

1、pytest.warns()斷言告警信息

pytest.warns()斷言,適用于被測方法會拋出特定告警,當出現(xiàn)這類告警則用例通過,否則用例失敗。

1.1采用pytest.warns()檢查代碼拋出的告警,如果沒有對應的告警拋出,則用例失敗.示例中設定了一個失敗用例和一個成功用例:
# make_warnings.py
import warnings
def fxn():
    warnings.warn("deprecated", DeprecationWarning)
def not_warn():
    pass

對上面的2個方法進行測試:

import sys
sys.path.append(".")
import pytest
import make_warnings

class TestWarns():
    def test_depre(self):
        with pytest.warns(DeprecationWarning):
            make_warnings.fxn()

    def test_not_warn(self):
        with pytest.warns(DeprecationWarning):
            make_warnings.not_warn()

運行結果:

PS E:\python_interface_test\requests_practice> pytest -q .\test_warns.py
.F                                                                       [100%]
================================== FAILURES ===================================
___________________________ TestWarns.test_not_warn ___________________________

self = <requests_practice.test_warns.TestWarns object at 0x000001D3915AF2E8>

    def test_not_warn(self):
        with pytest.warns(DeprecationWarning):
>           make_warnings.not_warn()
E           Failed: DID NOT WARN. No warnings of type (<class 'DeprecationWarning'>,) was emitted. The list of emitted warnings is: [].

test_warns.py:14: Failed
1 failed, 1 passed in 0.06 seconds

從運行結果中看出,第2個用例執(zhí)行失敗,是因為該方法不會拋出告警。從失敗結果中The list of emitted warnings is: []看出,告警信息存儲在list中。

1.2 采用match正則匹配拋出的告警信息,若告警信息和告警類型不同時匹配,則用例執(zhí)行失敗
import warnings
import pytest

def warn_message():
    warnings.warn("I'm a warning message", UserWarning)

def test_warn_match():
    with pytest.warns(UserWarning, match=r'^I.*e'):
        warn_message()
    # warn_message() # 加上這句,執(zhí)行用例會看到拋出的告警
1.3 將告警信息存入一個變量中,通過讀取這個變量中的信息進行斷言,包括:告警的個數(shù)、告警信息參數(shù)等。
import warnings
import pytest

def warn_message():
    warnings.warn("user", UserWarning)
    warnings.warn("runtime", RuntimeWarning)

def test_warn_match():
    with pytest.warns(UserWarning, match=r'.*t.*') as record:
        warn_message()
    assert len(record) == 2
    assert str(record[0].message) == "user"
    assert str(record[1].message) == "runtime"

運行結果:

PS E:\python_interface_test\requests_practice> pytest -q .\test_warns.py
F                                                                        [100%]
================================== FAILURES ===================================
_______________________________ test_warn_match _______________________________

    def test_warn_match():
        with pytest.warns(UserWarning, match=r'.*t.*') as record:
>           warn_message()

test_warns.py:13:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
....
E Failed: DID NOT WARN. No warnings of type (<class 'UserWarning'>,) matching ('.*t.*') was emitted. 
The list of emitted warnings is: [UserWarning('user',), RuntimeWarning('runtime',)].
...
1 failed in 0.07 seconds

從運行結果中,可以看到,返回的list中存儲了2個warnings信息,即record是一個list,可以計算長度,并通過record[i].message獲取告警信息。
PS:將示例中的match=r'.*t.*'更改為match=r'.*u.*'即可執(zhí)行成功。


下面不是pytest.warns()的斷言介紹了



pytest捕獲告警信息

  • pytest默認捕獲除DeprecationWarning和PendingDeprecationWarning外的所有告警信息,可以在pytest.ini中進行配置,使出現(xiàn)這兩類告警時也會拋出告警信息:
# pytest.ini
[pytest]
filterwarnings =
    once::DeprecationWarning
    once::PendingDeprecationWarning
  • 如果出現(xiàn)特定告警需要使用例執(zhí)行失敗,可以采用-W命令:pytest -q test_show_warnings.py -W error::UserWarning
  • 可以在pytest.ini中設置過濾或者執(zhí)行失敗,在這個過濾條件中,除UserWarning外的告警都會識別為錯誤進行處理。
# pytest.ini
[pytest]
filterwarnings =
    error
    ignore::UserWarning
  • pytest的標記函數(shù)處理告警信息
# 忽略function中的告警
@pytest.mark.filterwarnings('ignore:function')

# 將用例中所有的告警都轉(zhuǎn)換為錯誤,將裝飾器作用于測試類,則測試類中的所有用例出現(xiàn)告警都會失敗
@pytest.mark.filterwarnings('error')
  • 不捕獲告警信息,可以在文件中進行配置,或者在命令行傳遞-p no:warnings,那么當用例存在告警信息時,都不會在結果中輸出告警信息:
# pytest.ini
[pytest]
addopts = -p no:warnings

pytest記錄告警信息

  • 可以采用recwarn fixture記錄函數(shù)的全部告警信息
    每個告警記錄包含以下屬性:
  • message
  • category
  • filename
  • lineno
  • file
  • line

每個告警記錄具有l(wèi)ist的屬性,可調(diào)用以下方法:

  • pop()
  • clear()
import warnings
def test_hello(recwarn):
    warnings.warn("hello", UserWarning)
    assert len(recwarn) == 1
    w = recwarn.pop(UserWarning)
    assert issubclass(w.category, UserWarning)
    assert str(w.message) == "hello"
    assert w.filename
    assert w.lineno
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

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