views:

46

answers:

2

Hi, I have a following function in Python and I want to test with unittest that if the function gets 0 as argument, it throws a warning. I already tried assertRaises, but since I don't raise the warning, that doesn't work.

   def isZero( i):
       if i != 0:
         print "OK"
       else:
         warning = Warning( "the input is 0!") 
         print warning
       return i

Thank you, Tomas

+3  A: 

You can use the catch_warnings context manager. Essentially this allows you to mock the warnings handler, so that you can verify details of the warning. See the official docs for a fuller explanation and sample test code.

ire_and_curses
+1. Nifty and useful.
Manoj Govindan
+1  A: 

@ire_and_curses' answer is quite useful and, I think, canonical. Here is another way to do the same thing. This one requires Michael Foord's excellent Mock library.

import unittest, warnings
from mock import patch_object

def isZero( i):
   if i != 0:
     print "OK"
   else:
     warnings.warn( "the input is 0!")
   return i

class Foo(unittest.TestCase):
    @patch_object(warnings, 'warn')
    def test_is_zero_raises_warning(self, mock_warn):
        isZero(0)
        self.assertTrue(mock_warn.called)

if __name__ == '__main__':
    unittest.main()

The nifty patch_object lets you mock out the warn method.

Manoj Govindan