Monday, September 15, 2008

assertNone/assertNotNone

Why Python unittest module lacks assertNone/assertNotNone? I think this lack would cause problems as API misuse. For example:

obj = factory.make_object()
self.assert_(obj) # must not be None (?)

I intended to say "factory.make_object must not return None", but It can fail even False and such an empty object (0, "", [], ...).

I should have written like:

obj = factory.make_object()
self.assert_(obj is not None) # must not be None!

Repeating that code, however, is so boring, a lot of the visual noise, and error-prone. Writing assertNone/assertNotNone:

class TestCase(unittest.TestCase):
    """Custom TestCase class"""

    def failUnlessNone(self, expr, msg=None):
        """Fail the test unless the expression is None."""
        if expr is not None: raise self.failureException, msg

    def failIfNone(self, expr, msg=None):
        """Fail the test if the expression is None."""
        if expr is None: raise self.failureException, msg

    # Synonyms for assertion methods
    assertNone = failUnlessNone
    assertNotNone = failIfNone

0 comments: