Fork me on GitHub

Context Managers

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

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')
...
>>> 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 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.

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'
...
>>> out
['Captured']
disable_imports(*names)[source]

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

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

New in version 0.4.

tempdir()[source]

Creates a temporary directory, removing it and everything in it when the context exits. For files you can use TemporaryFile() as a context manager.

Returns the path to the directory. Arguments are passed to mkdtemp().

New in version 0.6.