[Python] 在 pytest 中測試某個函式是否有丟出 exception

[Python] 在 pytest 中測試某個函式是否有丟出 exception

在用 pytest 寫單元測試 (unit-testing) 時,

偶爾會需要測試某個函式會丟出例外 (exception) 的情況~

這個在 pytest 本身已經有支援了,例如:

 

def test_get_file_sha1():
    with pytest.raises(TypeError):
        Checksum._get_file_sha1(None)

 

上面的測試程式預期 _get_file_sha1(None) 會丟出一個 TypeError 的 exception,

因此可以用 pytest.raises(TypeError) 來確認,

假設沒接到這預期的例外的話,這個 test case 就失敗了~

 

參考資料:pytest: Assertions about expected exceptions

 

(本頁面已被瀏覽過 842 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料