I See Dead Code

… as sounding brass, or a tinkling cymbal.

I See Dead Code header image 2

Random Python unittesting snippet #1

December 18th, 2007 · No Comments

A small context manager for stating assertions about exceptions in Python unit tests:

@contextmanager
def assert_raises(*exc_types):
    """A context to ensure that an exception of a given type is thrown.
 
    Instead of
 
    @nose.tools.raises(ValueError)
    def test_that_raises():
        # ... lengthy setup
        raise ValueError
 
    you can write
 
    def test_that_raises_at_the_end():
        # ... lengthy setup
        with assert_raises(ValueError):
            raise ValueError
 
    to make the scope for catching exceptions as small as possible.
    """
    try:
        yield
    except exc_types:
        pass
    except:
        raise
    else:
        raise AssertionError("Failed to throw exception of type(s) %s." % (
            ", ".join(exc_type.__name__ for exc_type in exc_types),))

Tags: lang:en · programming · python

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment