Fork me on GitHub

Context Managers

Attest provides some context managers that are useful for writing tests.

attest.contexts.raises(*exceptions)[source]

Fails if none of the exceptions are raised inside the context. This reverses failure semantics and is useful for testing code that uses exceptions as part of its API.

with raises(IOError) as error:
    open('/etc/passwd', 'w')

assert error.errno == 13
Parameters:exceptions – Expected exception classes.
Returns:An Error on which the caught exception is set after the context has executed, if one was raised.
Raises AssertionError:
 If none of the expected exceptions are raised in the context.

New in version 0.5.

class attest.contexts.Error[source]

Container of metadata for an exception caught by raises().

Attribute access and string adaption is forwarded to the exception object. To test the type however you need to use the exc attribute directly.

New in version 0.5.

exc

The actual exception instance.

attest.contexts.capture_output()[source]

Captures standard output and error during the context. Returns a tuple of the two streams as lists of lines, added after the context has executed.

with capture_output() as (out, err):
    print 'Captured'

assert out == ['Captured']
attest.contexts.disable_imports(*names)[source]

Blocks the given names from being imported inside the context. This is useful for testing import-dependent fallbacks.

>>> from attest import disable_imports
>>> with disable_imports('sys'):
...     import sys
...
Traceback (most recent call last):
ImportError: 'sys' is disabled

New in version 0.4.