您可以編寫自己的assertWarns函數來封裝catch_warnings上下文。我剛剛實現了它的下面的方式,用一個mixin:
class WarningTestMixin(object):
'A test which checks if the specified warning was raised'
def assertWarns(self, warning, callable, *args, **kwds):
with warnings.catch_warnings(record=True) as warning_list:
warnings.simplefilter('always')
result = callable(*args, **kwds)
self.assertTrue(any(item.category == warning for item in warning_list))
的利用方法:
class SomeTest(WarningTestMixin, TestCase):
'Your testcase'
def test_something(self):
self.assertWarns(
UserWarning,
your_function_which_issues_a_warning,
5, 10, 'john', # args
foo='bar' # kwargs
)
測試將通過如果your_function
發出的警告中的至少一個是類型UserWarning的。
關於解決* ...如果由於一次/默認規則已經發出警告,則不管設置了哪些過濾器,除非警告註冊表與警告相關,否則不會再看到該警告已被清除。*([docs](https://docs.python.org/3/library/warnings.html#testing-warnings))請參閱[本文](https://blog.ionelmc.ro/2013/06/26/testing-python-warnings /)關於模塊級別__warningregistry__(註冊表文件提到)。 – saaj 2016-09-16 15:12:59