testtools API documentation

Generated reference documentation for all the public functionality of testtools.

Please send patches if you notice anything confusing or wrong, or that could be improved.

testtools

testtools.assertions

testtools.matchers

All the matchers.

Matchers, a way to express complex assertions outside the testcase.

Inspired by ‘hamcrest’.

Matcher provides the abstract API that all matchers need to implement.

Bundled matchers are listed in __all__: a list can be obtained by running $ python -c ‘import testtools.matchers; print testtools.matchers.__all__’

class testtools.matchers.AfterPreprocessing(preprocessor, matcher, annotate=True)

Matches if the value matches after passing through a function.

This can be used to aid in creating trivial matchers as functions, for example:

def PathHasFileContent(content):
    def _read(path):
        return open(path).read()
    return AfterPreprocessing(_read, Equals(content))
class testtools.matchers.AllMatch(matcher)

Matches if all provided values match the given matcher.

testtools.matchers.Always()

Always match.

That is:

self.assertThat(x, Always())

Will always match and never fail, no matter what x is. Most useful when passed to other higher-order matchers (e.g. MatchesListwise).

class testtools.matchers.Annotate(annotation, matcher)

Annotates a matcher with a descriptive string.

Mismatches are then described as ‘<mismatch>: <annotation>’.

classmethod if_message(annotation, matcher)

Annotate matcher only if annotation is non-empty.

class testtools.matchers.AnyMatch(matcher)

Matches if any of the provided values match the given matcher.

class testtools.matchers.ContainedByDict(expected)

Match a dictionary for which this is a super-dictionary.

Specify a dictionary mapping keys (often strings) to matchers. This is the ‘expected’ dict. Any dictionary that matches this must have only these keys, and the values must match the corresponding matchers in the expected dict. Dictionaries that have fewer keys can also match.

In other words, any matching dictionary must be contained by the dictionary given to the constructor.

Does not check for strict super-dictionary. That is, equal dictionaries match.

class testtools.matchers.Contains(needle)

Checks whether something is contained in another thing.

match(matchee)

Return None if this matcher matches something, a Mismatch otherwise.

testtools.matchers.ContainsAll(items)

Make a matcher that checks whether a list of things is contained in another thing.

The matcher effectively checks that the provided sequence is a subset of the matchee.

class testtools.matchers.ContainsDict(expected)

Match a dictionary for that contains a specified sub-dictionary.

Specify a dictionary mapping keys (often strings) to matchers. This is the ‘expected’ dict. Any dictionary that matches this must have at least these keys, and the values must match the corresponding matchers in the expected dict. Dictionaries that have more keys will also match.

In other words, any matching dictionary must contain the dictionary given to the constructor.

Does not check for strict sub-dictionary. That is, equal dictionaries match.

class testtools.matchers.DirContains(filenames=None, matcher=None)

Matches if the given directory contains files with the given names.

That is, is the directory listing exactly equal to the given files?

match(path)

Return None if this matcher matches something, a Mismatch otherwise.

testtools.matchers.DirExists()

Matches if the path exists and is a directory.

class testtools.matchers.DocTestMatches(example, flags=0)

See if a string matches a doctest example.

class testtools.matchers.EndsWith(expected)

Checks whether one string ends with another.

match(matchee)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.Equals(expected)

Matches if the items are equal.

comparator(b, /)

Same as a == b.

class testtools.matchers.FileContains(contents=None, matcher=None)

Matches if the given file has the specified contents.

match(path)

Return None if this matcher matches something, a Mismatch otherwise.

testtools.matchers.FileExists()

Matches if the given path exists and is a file.

class testtools.matchers.GreaterThan(expected)

Matches if the item is greater than the matchers reference object.

comparator(b, /)

Same as a > b.

class testtools.matchers.HasPermissions(octal_permissions)

Matches if a file has the given permissions.

Permissions are specified and matched as a four-digit octal string.

match(filename)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.Is(expected)

Matches if the items are identical.

comparator(b, /)

Same as a is b.

testtools.matchers.IsDeprecated(message)

Make a matcher that checks that a callable produces exactly one DeprecationWarning.

Parameters

message – Matcher for the warning message.

class testtools.matchers.IsInstance(*types)

Matcher that wraps isinstance.

class testtools.matchers.KeysEqual(*expected)

Checks whether a dict has particular keys.

match(matchee)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.LessThan(expected)

Matches if the item is less than the matchers reference object.

comparator(b, /)

Same as a < b.

class testtools.matchers.MatchesAll(*matchers, **options)

Matches if all of the matchers it is created with match.

class testtools.matchers.MatchesAny(*matchers)

Matches if any of the matchers it is created with match.

class testtools.matchers.MatchesDict(expected)

Match a dictionary exactly, by its keys.

Specify a dictionary mapping keys (often strings) to matchers. This is the ‘expected’ dict. Any dictionary that matches this must have exactly the same keys, and the values must match the corresponding matchers in the expected dict.

class testtools.matchers.MatchesException(exception, value_re=None)

Match an exc_info tuple against an exception instance or type.

match(other)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.MatchesListwise(matchers, first_only=False)

Matches if each matcher matches the corresponding value.

More easily explained by example than in words:

>>> from ._basic import Equals
>>> MatchesListwise([Equals(1)]).match([1])
>>> MatchesListwise([Equals(1), Equals(2)]).match([1, 2])
>>> print (MatchesListwise([Equals(1), Equals(2)]).match([2, 1]).describe())
Differences: [
2 != 1
1 != 2
]
>>> matcher = MatchesListwise([Equals(1), Equals(2)], first_only=True)
>>> print (matcher.match([3, 4]).describe())
3 != 1
class testtools.matchers.MatchesPredicate(predicate, message)

Match if a given function returns True.

It is reasonably common to want to make a very simple matcher based on a function that you already have that returns True or False given a single argument (i.e. a predicate function). This matcher makes it very easy to do so. e.g.:

IsEven = MatchesPredicate(lambda x: x % 2 == 0, '%s is not even')
self.assertThat(4, IsEven)
match(x)

Return None if this matcher matches something, a Mismatch otherwise.

testtools.matchers.MatchesPredicateWithParams(predicate, message, name=None)

Match if a given parameterised function returns True.

It is reasonably common to want to make a very simple matcher based on a function that you already have that returns True or False given some arguments. This matcher makes it very easy to do so. e.g.:

HasLength = MatchesPredicate(
    lambda x, y: len(x) == y, 'len({0}) is not {1}')
# This assertion will fail, as 'len([1, 2]) == 3' is False.
self.assertThat([1, 2], HasLength(3))

Note that unlike MatchesPredicate MatchesPredicateWithParams returns a factory which you then customise to use by constructing an actual matcher from it.

The predicate function should take the object to match as its first parameter. Any additional parameters supplied when constructing a matcher are supplied to the predicate as additional parameters when checking for a match.

Parameters
  • predicate – The predicate function.

  • message – A format string for describing mis-matches.

  • name – Optional replacement name for the matcher.

class testtools.matchers.MatchesRegex(pattern, flags=0)

Matches if the matchee is matched by a regular expression.

class testtools.matchers.MatchesSetwise(*matchers)

Matches if all the matchers match elements of the value being matched.

That is, each element in the ‘observed’ set must match exactly one matcher from the set of matchers, with no matchers left over.

The difference compared to MatchesListwise is that the order of the matchings does not matter.

class testtools.matchers.MatchesStructure(**kwargs)

Matcher that matches an object structurally.

‘Structurally’ here means that attributes of the object being matched are compared against given matchers.

fromExample allows the creation of a matcher from a prototype object and then modified versions can be created with update.

byEquality creates a matcher in much the same way as the constructor, except that the matcher for each of the attributes is assumed to be Equals.

byMatcher creates a similar matcher to byEquality, but you get to pick the matcher, rather than just using Equals.

classmethod byEquality(**kwargs)

Matches an object where the attributes equal the keyword values.

Similar to the constructor, except that the matcher is assumed to be Equals.

classmethod byMatcher(matcher, **kwargs)

Matches an object where the attributes match the keyword values.

Similar to the constructor, except that the provided matcher is used to match all of the values.

testtools.matchers.Never()

Never match.

That is:

self.assertThat(x, Never())

Will never match and always fail, no matter what x is. Included for completeness with Always(), but if you find a use for this, let us know!

class testtools.matchers.Not(matcher)

Inverts a matcher.

class testtools.matchers.NotEquals(expected)

Matches if the items are not equal.

In most cases, this is equivalent to Not(Equals(foo)). The difference only matters when testing __ne__ implementations.

comparator(b, /)

Same as a != b.

testtools.matchers.PathExists()

Matches if the given path exists.

Use like this:

assertThat('/some/path', PathExists())
class testtools.matchers.Raises(exception_matcher=None)

Match if the matchee raises an exception when called.

Exceptions which are not subclasses of Exception propagate out of the Raises.match call unless they are explicitly matched.

match(matchee)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.SameMembers(expected)

Matches if two iterators have the same members.

This is not the same as set equivalence. The two iterators must be of the same length and have the same repetitions.

match(observed)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.SamePath(path)

Matches if two paths are the same.

That is, the paths are equal, or they point to the same file but in different ways. The paths do not have to exist.

match(other_path)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.StartsWith(expected)

Checks whether one string starts with another.

match(matchee)

Return None if this matcher matches something, a Mismatch otherwise.

class testtools.matchers.TarballContains(paths)

Matches if the given tarball contains the given paths.

Uses TarFile.getnames() to get the paths out of the tarball.

match(tarball_path)

Return None if this matcher matches something, a Mismatch otherwise.

testtools.matchers.WarningMessage(category_type, message=None, filename=None, lineno=None, line=None)

Create a matcher that will match `warnings.WarningMessage`s.

For example, to match captured DeprecationWarning`s with a message about some ``foo` being replaced with bar:

WarningMessage(DeprecationWarning,
               message=MatchesAll(
                   Contains('foo is deprecated'),
                   Contains('use bar instead')))
Parameters

category_type (type) – A warning type, for example

DeprecationWarning. :param message_matcher: A matcher object that will be evaluated against warning’s message. :param filename_matcher: A matcher object that will be evaluated against the warning’s filename. :param lineno_matcher: A matcher object that will be evaluated against the warning’s line number. :param line_matcher: A matcher object that will be evaluated against the warning’s line of source code.

class testtools.matchers.Warnings(warnings_matcher=None)

Match if the matchee produces warnings.

testtools.matchers.raises(exception)

Make a matcher that checks that a callable raises an exception.

This is a convenience function, exactly equivalent to:

return Raises(MatchesException(exception))

See Raises and MatchesException for more information.

testtools.twistedsupport