2010-08-27 22 views

回答

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"

+0

不應在試驗中'LEN(W)> 0',我們只是想檢查是否'警告。 WarningMessage'列表爲空。或者,按照[PEP8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations)測試空序列是否爲假 – 2015-08-19 07:22:59

1

有(至少)這樣做有兩種方式。您可以在listwarnings.WarningMessage s中測試或在您的模塊中使用mockpatch導入的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)