pytest中對告警進行斷言採用pytest.warns()方法,其斷言的方法與pytest.raises()類似。pytest.warns()除了能斷言告警外,還能夠捕獲告警信息,並對捕獲的告警信息進行分類處理,可以設定出現特定告警信息時,則用例執行失敗。
Pytest的pytest.warns()用法
pytest.warns()斷言告警信息pytest.warns()捕獲告警信息,並對告警信息進行判斷pytest.warns()記錄告警信息1、pytest.warns()斷言告警信息
pytest.warns()斷言,適用於被測方法會拋出特定告警,當出現這類告警則用例通過,否則用例失敗。
1.1採用pytest.warns()檢查代碼拋出的告警,如果沒有對應的告警拋出,則用例失敗.示例中設定了一個失敗用例和一個成功用例:
# make_warnings.pyimport warningsdeffxn(): warnings.warn("deprecated", DeprecationWarning)defnot_warn():pass對上面的2個方法進行測試:
import syssys.path.append(".")import pytestimport make_warningsclassTestWarns():deftest_depre(self):with pytest.warns(DeprecationWarning): make_warnings.fxn() deftest_not_warn(self):with pytest.warns(DeprecationWarning): make_warnings.not_warn()運行結果:
從運行結果中看出,第2個用例執行失敗,是因為該方法不會拋出告警。從失敗結果中The list of emitted warnings is: []看出,告警信息存儲在list中。
1.2 採用match正則匹配拋出的告警信息,若告警信息和告警類型不同時匹配,則用例執行失敗
import warningsimport pytestdefwarn_message(): warnings.warn("I'm a warning message", UserWarning)deftest_warn_match():with pytest.warns(UserWarning, match=r'^I.*e'): warn_message() # warn_message() # 加上這句,執行用例會看到拋出的告警1.3 將告警信息存入一個變量中,通過讀取這個變量中的信息進行斷言,包括:告警的個數、告警信息參數等。
import warningsimport pytestdefwarn_message(): warnings.warn("user", UserWarning) warnings.warn("runtime", RuntimeWarning)deftest_warn_match():with pytest.warns(UserWarning, match=r'.*t.*') as record: warn_message() assert len(record) == 2assert str(record[0].message) == "user"assert str(record[1].message) == "runtime"運行結果:
從運行結果中,可以看到,返回的list中存儲了2個warnings信息,即record是一個list,可以計算長度,並通過record[i].message獲取告警信息。PS:將示例中的match=r'.*t.*'更改為match=r'.*u.*'即可執行成功。
下面不是pytest.warns()的斷言介紹了
pytest捕獲告警信息
pytest默認捕獲除DeprecationWarning和PendingDeprecationWarning外的所有告警信息,可以在pytest.ini中進行配置,使出現這兩類告警時也會拋出告警信息:# pytest.ini[pytest]filterwarnings = once::DeprecationWarning once::PendingDeprecationWarning如果出現特定告警需要使用例執行失敗,可以採用-W命令:pytest -q test_show_warnings.py -W error::UserWarning可以在pytest.ini中設置過濾或者執行失敗,在這個過濾條件中,除UserWarning外的告警都會識別為錯誤進行處理。# pytest.ini[pytest]filterwarnings = error ignore::UserWarningpytest的標記函數處理告警信息# 忽略function中的告警@pytest.mark.filterwarnings('ignore:function')# 將用例中所有的告警都轉換為錯誤,將裝飾器作用於測試類,則測試類中的所有用例出現告警都會失敗@pytest.mark.filterwarnings('error')不捕獲告警信息,可以在文件中進行配置,或者在命令行傳遞-p no:warnings,那麼當用例存在告警信息時,都不會在結果中輸出告警信息:# pytest.ini[pytest]addopts = -p no:warningspytest記錄告警信息
可以採用recwarn fixture記錄函數的全部告警信息每個告警記錄包含以下屬性:messagecategoryfilenamelinenofileline每個告警記錄具有list的屬性,可調用以下方法:
pop()clear()import warningsdeftest_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
作者: 樂大爺博客聲明:本文已獲作者授權轉載,著作權歸作者所有。