Friday, June 8, 2007

Warnings unit test helper

Trial's TestCase offers a new helper method in Twisted trunk@HEAD, assertWarns. This makes it trivial to test that a particular function call emits a warning which satisfies some condition. For example, this is useful for verifying that an API which is supposed to be deprecated is actually deprecated:


from twisted.trial.unittest import TestCase

def someFunction(input):
"""
Map inputs to outputs.
"""


class FunctionTests(TestCase):
"""
Tests for L{someFunction}.
"""

def test_deprecation(self):
"""
Calling L{someFunction} should emit a L{DeprecationWarning}.
"""
self.assertWarns(
DeprecationWarning,
("someFunction is deprecated, use anotherFunction instead",),
__file__,
someFunction, 3)


Before adding the warning, this fails:


$ trial assertwarns.py
Running 1 tests.
assertwarns
FunctionTests
test_deprecation ... [FAIL]

===============================================================================
[FAIL]: assertwarns.FunctionTests.test_deprecation

Traceback (most recent call last):
File "/home/exarkun/assertwarns.py", line 22, in test_deprecation
someFunction, 3)
File "/home/exarkun/Projects/Twisted/trunk/twisted/trial/unittest.py", line 346, in failUnlessWarns
self.assertEqual(len(warningsShown), 1, pformat(warningsShown))
twisted.trial.unittest.FailTest: []
-------------------------------------------------------------------------------
Ran 1 tests in 0.009s

FAILED (failures=1)


After changing the definition of someFunction to this:


import warnings

def someFunction(input):
"""
Map inputs to outputs.
"""
warnings.warn(
"someFunction is deprecated, use anotherFunction instead",
category=DeprecationWarning)


the tests pass:


$ trial assertwarns.py
Running 1 tests.
assertwarns
FunctionTests
test_deprecation ... [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.003s

PASSED (successes=1)

No comments:

Post a Comment