2010-08-27 5 views

Respuesta

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 

En lugar de simplemente comprobar la longitud, se puede comprobar en profundidad, por supuesto:

assert str(w.args[0]) == "deprecated"

en Python 2.7 o posterior, puede hacer esto con el último cheque como:

assert str(w[0].message[0]) == "deprecated"

+0

no debería ser la prueba 'len (w)> 0', sólo queremos comprobar si los' advertencias. La lista WarningMessage' está vacía. O, siguiendo [PEP8] (https://www.python.org/dev/peps/pep-0008/#programming-recommendations) simplemente prueba si las secuencias vacías son falsas –

1

Hay (al menos) dos maneras de hacer esto. Puede ver la advertencia en list de warnings.WarningMessage s en prueba o usar mock a patch importado warnings en su módulo.

Creo que la versión patch es más general.

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) 
Cuestiones relacionadas