我正在使用nose編寫單元測試,我想檢查一個函數是否發出警告(函數使用warnings.warn
)。這是否可以輕鬆完成?檢查一個函數引發鼻測試的警告
7
A
回答
9
def your_code():
# ...
warnings.warn("deprecated", DeprecationWarning)
# ...
def your_test():
with warnings.catch_warnings(record=True) as w:
your_code()
assert len(w) > 1
而不是僅僅檢查lenght,你可以深入的檢查,當然:
assert str(w.args[0]) == "deprecated"
在Python 2.7版或更高版本,可以與上次檢查爲做到這一點:
assert str(w[0].message[0]) == "deprecated"
1
有(至少)這樣做有兩種方式。您可以在list
的warnings.WarningMessage
s中測試或在您的模塊中使用mock
到patch
導入的warnings
。
我認爲patch
版本更一般。
raise_warning.py:
import warnings
def should_warn():
warnings.warn('message', RuntimeWarning)
print('didn\'t I warn you?')
raise_warning_tests.py:
import unittest
from mock import patch
import raise_warning
class TestWarnings(unittest.TestCase):
@patch('raise_warning.warnings.warn')
def test_patched(self, mock_warnings):
"""test with patched warnings"""
raise_warning.should_warn()
self.assertTrue(mock_warnings.called)
def test_that_catches_warning(self):
"""test by catching warning"""
with raise_warning.warnings.catch_warnings(True) as wrn:
raise_warning.should_warn()
# per-PEP8 check for empty sequences by their Truthiness
self.assertTrue(wrn)
相關問題
- 1. 警告測試
- 2. 引發異常的測試函數
- 3. 測試引發故障的函數
- 4. 的Android測試「ro.build.date.utc」警告
- 5. JUnit測試中的警告
- 6. 鼻子測試單次設置函數調用一次
- 7. Java 1.7 varargs函數報告爲未檢查警告
- 8. 腳本引發的警告
- 9. 測試函數的存在(一個動態引用函數)
- 10. QUnit/Sinon:測試一個函數,檢查cookie是否啓用
- 11. 檢測Chrome插件警告
- 12. Apache Camel JUnit測試警告
- 13. 取消測試(帶警告)
- 14. Vuelidate警告噶/柴測試
- 15. (Rails 5)爲什麼這個集成測試關鍵字參數引發了一個棄用警告?
- 16. 陣營警告:「無法道具類型:檢查是不是一個函數」
- 17. Cassandra引發SSLFactory.java警告
- 18. 警告:函數「殺」
- 19. Django鼻子如何寫這個測試?
- 20. Python鼻子測試示例
- 21. 檢查一個文件的整數,然後輸出一個警告C#
- 22. 鼻子測試類與發電機的多個測試,但只有一個類的實例
- 23. 如何在python中引發警告時在函數中查看變量?
- 24. 對R包中不推薦使用的函數進行單元測試在檢查過程中導致警告
- 25. 如何檢查Arima()函數是否生成警告消息?
- 26. 的iOS警告:函數「pathInDocumentDirectory」
- 27. Ç - 警告:函數「printf的」
- 28. Objective - C的連接測試警告
- 29. 測試執行期間的Vue警告
- 30. 單元測試提供了一個shell腳本調用警告
不應在試驗中'LEN(W)> 0',我們只是想檢查是否'警告。 WarningMessage'列表爲空。或者,按照[PEP8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations)測試空序列是否爲假 – 2015-08-19 07:22:59