API Reference

Collecting tests

To run tests, they must be collected in a Tests instance. There are many ways this can be achieved, allowing flexibility and separation.

  • Register individual functions with the Tests.test() decorator.
  • Register other collections with Tests.register() or as arguments to the constructor. A collection according to Attest is an iterable yielding test callables, this includes:
    • Lists of lambdas and function references.
    • Tests instances.
    • Instances of subclasses of TestBase.
    • Classes are instantiated and returned, allowing Tests.register() to be used as a class decorator in Python 2.6 or later.
class attest.Tests(tests=())[source]

Collection of test functions.

Parameters:tests – Iterable of other test collections to register with this one.
run(reporter=auto_reporter)[source]

Run all tests in this collection.

Parameters:reporter – An instance of AbstractReporter or a callable returning something implementing that API (not enforced).
test(func)[source]

Decorate a function as a test belonging to this collection.

context(func)[source]

Decorate a function as a contextmanager() for running the tests in this collection in. Corresponds to setup and teardown in other testing libraries.

db = Tests()

@db.context
def connect():
    con = connect_db()
    try:
        yield con
    finally:
        con.disconnect()

@db.test
def using_connection(con):
    Assert(con).is_not(None)

The above corresponds to:

db = Tests()

def connect():
    con = connect_db()
    try:
        yield con
    finally:
        con.disconnect()

@db.test
def using_connection():
    with connect() as con:
        Assert(con).is_not(None)

The difference is that this decorator applies the context to all tests defined in its collection, so it’s less repetitive.

Yielding None or nothing passes no arguments to the test, yielding a single value other than a tuple passes that value as the sole argument to the test, yielding a tuple splats the tuple as the arguments to the test. If you want to yield a tuple as the sole argument, wrap it in a one-tuple or unsplat the args in the test.

register(tests)[source]

Merge in another test collection.

test_suite()[source]

Create a unittest.TestSuite from this collection.

class attest.TestBase[source]

Base for test classes. Decorate test methods with test(). Needs to be registered with a Tests collection to be run. For setup and teardown, override __context__() like a contextmanager() (without the decorator).

class Math(TestBase):

    def __context__(self):
        self.two = 1 + 1
        yield
        del self.two

    @test
    def arithmetics(self):
        Assert(self.two) == 2

suite = Tests([Math()])
suite.run()
attest.test(meth)[source]

Mark a TestBase method as a test and wrap it to run in the TestBase.__context__() of the subclass.

Asserting conditions

class attest.Assert(obj=None)[source]

Wrap an object such that boolean operations on it fails with an AssertionError if the operation results in False, with more helpful error messages on failure than assert.

A test failure is simply an unhandled exception, so it is completely optional to use this class.

Examples:

Assert(1 + 1) == 2
2 in Assert([1, 2, 3])

Attributes are proxied to the wrapped object, returning the result wrapped as well:

hello = Assert('hello')
hello == 'hello'
hello.upper() == 'HELLO'
hello.capitalize() == 'Hello'

Used in boolean context, fails if non-true. These all fail:

bool(Assert(0))
if Assert(0): pass
assert Assert(0)

Identical to, except for the more helpful failure message:

Assert(bool(0)) == True
obj

The wrapped object

__class__[source]

The class of the wrapped object, also wrapped in Assert. Can be used for type testing:

Assert('Hello World').__class__.is_(str)
static raises(exceptions)[source]

Context manager that fails if a particular exception is not raised. Yields the caught exception wrapped in Assert:

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

error.errno == 13
Parameters:exceptions – Expected exception classes.
static not_raising(exception)[source]

Context manager that fails if a particular exception is raised. A raised exception consitutes a failure anyway and this is mainly used for testing Attest itself.

with Assert.not_raising(IOError):
    open('/etc/passwd', 'r')
Parameters:exception – An exception class.
__str__()[source]

Wrapped proxy to the wrapped object’s __str__, can be used for testing the string adaption of the object:

Assert(1).__str__() == '1'

Warning

str() on Assert objects does not work.

__getattr__(name)[source]

Proxy all attributes to the wrapped object, wrapping the result.

__call__(*args, **kwargs)[source]

Allow calling of wrapped callables, wrapping the return value. Useful for testing methods on a wrapped object via attribute proxying:

Assert('Hello').upper() == 'HELLO'
__getitem__(key)[source]

Access an item on the wrapped object and return the result wrapped as well.

Assert([1, 2, 3])[1] == 2
__eq__(obj)[source]

Test for equality with ==.

__ne__(obj)[source]

Test for inequality with !=.

is_(obj)[source]

The is operator is not overridable, for good reasons (that would defeat its purpose), so you can use this method for asserting identity:

Assert(True).is_(True)
is_not(obj)[source]

The negated form of is_(), corresponding to the is not operation:

Assert([]).is_not([])
__contains__(obj)[source]

Test for membership with in.

in_(obj)[source]

Assert membership. While you can use the in operator, its order is inconsistent with the rest of the operators and doesn’t work with the not in operation.

2 in Assert([1, 2, 3])
Assert(2).in_([1, 2, 3])
not_in(obj)[source]

The negated form of in_(), corresponding to the not in operation:

Assert(0).not_in([1, 2, 3])
__lt__(obj)[source]

Test for lesserness with <.

__le__(obj)[source]

Test for lesserness or equality with <=.

__gt__(obj)[source]

Test for greaterness with >.

__ge__(obj)[source]

Test for greaterness or equality with >=.

__nonzero__()[source]

Test for truthiness in boolean context.

__repr__()[source]

Not proxied to the wrapped object. To test that do something like:

Assert(repr(obj)) == 'expectation'
attest.assert_(expr, msg=None)[source]

Like assert, but counts the assertion.

attest.capture_output()[source]

Context manager capturing standard output and error. Yields a tuple of the two streams as lists of lines.

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

Assert(out) == ['Captured']

Running tests with distribute

class attest.Loader[source]

Run tests with Attest via distribute:

setup(
    test_loader='attest:Loader',
    test_suite='tests.collection',
)

Now, python setup.py -q test is equivalent to:

from tests import collection
collection.run()

If you want to run the tests as a normal unittest suite, try Tests.test_suite() instead:

setup(
    test_suite='tests.collection.test_suite'
)

Reporters

Reporters are in charge of handling the state and outcome of test-runs. They might output machine- or human-readable reports on the console, or display the results in a graphical user interface.

class attest.AbstractReporter[source]

Optional base for reporters, serves as documentation and improves errors for incomplete reporters.

Parameters:tests – The list of test functions we will be running.
begin(tests)[source]

Called with the list of tests when a test run has begun.

success(test, stdout, stderr)[source]

When a test succeeds, this method is called with the test function and the captured stdout and stderr output as lists of lines.

failure(test, error, traceback, stdout, stderr)[source]

When a test fails, this method is called with the test function, the exception instance that was raised, a cleaned up traceback string and the captured stdout and stderr output as lists of lines.

finished()[source]

Called when all tests have run.

class attest.FancyReporter(style='bw')[source]

Heavily uses ANSI escape codes for fancy output to 256-color terminals. Progress of running the tests is indicated by a progressbar and failures are shown with syntax highlighted tracebacks.

class attest.PlainReporter[source]

Plain text ASCII output for humans.

class attest.XmlReporter[source]

Report the result of a testrun in an XML format. Not compatible with JUnit or XUnit.

attest.auto_reporter(style=None)[source]

Select a reporter based on the target output.

This is the default reporter.

Parameters:style – Passed to FancyReporter if it is used.
Return type:FancyReporter if output is a terminal otherwise a PlainReporter.
attest.get_reporter_by_name(name, default='auto')[source]

Get an AbstractReporter by name, falling back on a default.

Available reporters:

Parameters:
  • name – One of the above strings.
  • default – The fallback reporter if no reporter has the supplied name, defaulting to 'auto'.
Raises KeyError:
 

If neither the name or the default is a valid name of a reporter.

Return type:

Callable returning an instance of an AbstractReporter.

Table Of Contents

Previous topic

How to attest to the correctness of an application

This Page