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.
-
warns
(*warnings, any=False)[source]¶ Context manager that succeeds if all warnings are issued inside the context. Yields a list of matching captured warnings as exception objects.
>>> with warns(UserWarning) as captured: ... warnings.warn("Example warning", UserWarning) ... >>> unicode(captured[0]) == "Example warning" True
Parameters: any – Require only one of the warnings to be issued (rather than all). Note
warnings
filtering is overridden to"always"
for monitored warnings.
-
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.