1 ==========================
2 testtools for test authors
3 ==========================
5 If you are writing tests for a Python project and you (rather wisely) want to
6 use testtools to do so, this is the manual for you.
8 We assume that you already know Python and that you know something about
9 automated testing already.
11 If you are a test author of an unusually large or unusually unusual test
12 suite, you might be interested in :doc:`for-framework-folk`.
14 You might also be interested in the `testtools API docs`_.
20 testtools is a set of extensions to Python's standard unittest module.
21 Writing tests with testtools is very much like writing tests with standard
22 Python, or with Twisted's "trial_", or nose_, except a little bit easier and
25 Below, we'll try to give some examples of how to use testtools in its most
26 basic way, as well as a sort of feature-by-feature breakdown of the cool bits
27 that you could easily miss.
33 Here's what a basic testtools unit tests look like::
35 from testtools import TestCase
36 from myproject import silly
38 class TestSillySquare(TestCase):
39 """Tests for silly square function."""
41 def test_square(self):
42 # 'square' takes a number and multiplies it by itself.
43 result = silly.square(7)
44 self.assertEqual(result, 49)
46 def test_square_bad_input(self):
47 # 'square' raises a TypeError if it's given bad input, say a
49 self.assertRaises(TypeError, silly.square, "orange")
52 Here you have a class that inherits from ``testtools.TestCase`` and bundles
53 together a bunch of related tests. The tests themselves are methods on that
54 class that begin with ``test_``.
59 You can run these tests in many ways. testtools provides a very basic
60 mechanism for doing so::
62 $ python -m testtools.run exampletest
68 where 'exampletest' is a module that contains unit tests. By default,
69 ``testtools.run`` will *not* recursively search the module or package for unit
70 tests. To do this, you will need to either have the discover_ module
71 installed or have Python 2.7 or later, and then run::
73 $ python -m testtools.run discover packagecontainingtests
75 For more information see the Python 2.7 unittest documentation, or::
77 python -m testtools.run --help
79 As your testing needs grow and evolve, you will probably want to use a more
80 sophisticated test runner. There are many of these for Python, and almost all
81 of them will happily run testtools tests. In particular:
87 * `zope.testrunner`_ (aka zope.testing)
89 From now on, we'll assume that you know how to run your tests.
91 Running test with Distutils
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94 If you are using Distutils_ to build your Python project, you can use the testtools
95 Distutils_ command to integrate testtools into your Distutils_ workflow::
97 from distutils.core import setup
98 from testtools import TestCommand
102 cmdclass={'test': TestCommand}
107 $ python setup.py test -m exampletest
109 Ran 2 tests in 0.000s
113 For more information about the capabilities of the `TestCommand` command see::
115 $ python setup.py test --help
117 You can use the `setup configuration`_ to specify the default behavior of the
118 `TestCommand` command.
123 The core of automated testing is making assertions about the way things are,
124 and getting a nice, helpful, informative error message when things are not as
127 All of the assertions that you can find in Python standard unittest_ can be
128 found in testtools (remember, testtools extends unittest). testtools changes
129 the behaviour of some of those assertions slightly and adds some new
130 assertions that you will almost certainly find useful.
133 Improved assertRaises
134 ---------------------
136 ``TestCase.assertRaises`` returns the caught exception. This is useful for
137 asserting more things about the exception than just the type::
139 def test_square_bad_input(self):
140 # 'square' raises a TypeError if it's given bad input, say a
142 e = self.assertRaises(TypeError, silly.square, "orange")
143 self.assertEqual("orange", e.bad_value)
144 self.assertEqual("Cannot square 'orange', not a number.", str(e))
146 Note that this is incompatible with the ``assertRaises`` in unittest2 and
153 If you are using a version of Python that supports the ``with`` context
154 manager syntax, you might prefer to use that syntax to ensure that code raises
155 particular errors. ``ExpectedException`` does just that. For example::
157 def test_square_root_bad_input_2(self):
158 # 'square' raises a TypeError if it's given bad input.
159 with ExpectedException(TypeError, "Cannot square.*"):
160 silly.square('orange')
162 The first argument to ``ExpectedException`` is the type of exception you
163 expect to see raised. The second argument is optional, and can be either a
164 regular expression or a matcher. If it is a regular expression, the ``str()``
165 of the raised exception must match the regular expression. If it is a matcher,
166 then the raised exception object must match it.
169 assertIn, assertNotIn
170 ---------------------
172 These two assertions check whether a value is in a sequence and whether a
173 value is not in a sequence. They are "assert" versions of the ``in`` and
174 ``not in`` operators. For example::
176 def test_assert_in_example(self):
177 self.assertIn('a', 'cat')
178 self.assertNotIn('o', 'cat')
179 self.assertIn(5, list_of_primes_under_ten)
180 self.assertNotIn(12, list_of_primes_under_ten)
183 assertIs, assertIsNot
184 ---------------------
186 These two assertions check whether values are identical to one another. This
187 is sometimes useful when you want to test something more strict than mere
188 equality. For example::
190 def test_assert_is_example(self):
194 self.assertIs(foo, foo_alias)
195 self.assertIsNot(foo, bar)
196 self.assertEqual(foo, bar) # They are equal, but not identical
202 As much as we love duck-typing and polymorphism, sometimes you need to check
203 whether or not a value is of a given type. This method does that. For
206 def test_assert_is_instance_example(self):
208 self.assertIsInstance(now, datetime)
210 Note that there is no ``assertIsNotInstance`` in testtools currently.
216 Sometimes it's useful to write tests that fail. For example, you might want
217 to turn a bug report into a unit test, but you don't know how to fix the bug
218 yet. Or perhaps you want to document a known, temporary deficiency in a
221 testtools gives you the ``TestCase.expectFailure`` to help with this. You use
222 it to say that you expect this assertion to fail. When the test runs and the
223 assertion fails, testtools will report it as an "expected failure".
227 def test_expect_failure_example(self):
229 "cats should be dogs", self.assertEqual, 'cats', 'dogs')
231 As long as 'cats' is not equal to 'dogs', the test will be reported as an
234 If ever by some miracle 'cats' becomes 'dogs', then testtools will report an
235 "unexpected success". Unlike standard unittest, testtools treats this as
236 something that fails the test suite, like an error or a failure.
242 The built-in assertion methods are very useful, they are the bread and butter
243 of writing tests. However, soon enough you will probably want to write your
244 own assertions. Perhaps there are domain specific things that you want to
245 check (e.g. assert that two widgets are aligned parallel to the flux grid), or
246 perhaps you want to check something that could almost but not quite be found
247 in some other standard library (e.g. assert that two paths point to the same
250 When you are in such situations, you could either make a base class for your
251 project that inherits from ``testtools.TestCase`` and make sure that all of
252 your tests derive from that, *or* you could use the testtools ``Matcher``
259 Here's a really basic example using stock matchers found in testtools::
262 from testtools.matchers import Equals
264 class TestSquare(TestCase):
265 def test_square(self):
267 self.assertThat(result, Equals(49))
269 The line ``self.assertThat(result, Equals(49))`` is equivalent to
270 ``self.assertEqual(result, 49)`` and means "assert that ``result`` equals 49".
271 The difference is that ``assertThat`` is a more general method that takes some
272 kind of observed value (in this case, ``result``) and any matcher object
273 (here, ``Equals(49)``).
275 The matcher object could be absolutely anything that implements the Matcher
276 protocol. This means that you can make more complex matchers by combining
279 def test_square_silly(self):
281 self.assertThat(result, Not(Equals(50)))
283 Which is roughly equivalent to::
285 def test_square_silly(self):
287 self.assertNotEqual(result, 50)
293 testtools comes with many matchers built in. They can all be found in and
294 imported from the ``testtools.matchers`` module.
299 Matches if two items are equal. For example::
301 def test_equals_example(self):
302 self.assertThat([42], Equals([42]))
308 Matches if two items are identical. For example::
310 def test_is_example(self):
312 self.assertThat(foo, Is(foo))
318 Adapts isinstance() to use as a matcher. For example::
320 def test_isinstance_example(self):
322 self.assertThat(MyClass(), IsInstance(MyClass))
323 self.assertThat(MyClass(), IsInstance(MyClass, str))
329 Matches if a callable raises a particular type of exception. For example::
331 def test_raises_example(self):
332 self.assertThat(lambda: 1/0, raises(ZeroDivisionError))
334 This is actually a convenience function that combines two other matchers:
335 Raises_ and MatchesException_.
341 Matches a string as if it were the output of a doctest_ example. Very useful
342 for making assertions about large chunks of text. For example::
346 def test_doctest_example(self):
347 output = "Colorless green ideas"
350 DocTestMatches("Colorless ... ideas", doctest.ELLIPSIS))
352 We highly recommend using the following flags::
354 doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_NDIFF
360 Matches if the given thing is greater than the thing in the matcher. For
363 def test_greater_than_example(self):
364 self.assertThat(3, GreaterThan(2))
370 Matches if the given thing is less than the thing in the matcher. For
373 def test_less_than_example(self):
374 self.assertThat(2, LessThan(3))
380 These matchers check to see if a string starts with or ends with a particular
381 substring. For example::
383 def test_starts_and_ends_with_example(self):
384 self.assertThat('underground', StartsWith('und'))
385 self.assertThat('underground', EndsWith('und'))
391 This matcher checks to see if the given thing contains the thing in the
392 matcher. For example::
394 def test_contains_example(self):
395 self.assertThat('abc', Contains('b'))
401 Matches an exc_info tuple if the exception is of the correct type. For
404 def test_matches_exception_example(self):
406 raise RuntimeError('foo')
408 exc_info = sys.exc_info()
409 self.assertThat(exc_info, MatchesException(RuntimeError))
410 self.assertThat(exc_info, MatchesException(RuntimeError('bar'))
412 Most of the time, you will want to uses `The raises helper`_ instead.
418 Matches if something is not equal to something else. Note that this is subtly
419 different to ``Not(Equals(x))``. ``NotEquals(x)`` will match if ``y != x``,
420 ``Not(Equals(x))`` will match if ``not y == x``.
422 You only need to worry about this distinction if you are testing code that
423 relies on badly written overloaded equality operators.
429 Matches if the keys of one dict are equal to the keys of another dict. For
432 def test_keys_equal(self):
435 self.assertThat(x, KeysEqual(y))
441 Matches a string against a regular expression, which is a wonderful thing to
442 be able to do, if you think about it::
444 def test_matches_regex_example(self):
445 self.assertThat('foo', MatchesRegex('fo+'))
448 File- and path-related matchers
449 -------------------------------
451 testtools also has a number of matchers to help with asserting things about
452 the state of the filesystem.
457 Matches if a path exists::
459 self.assertThat('/', PathExists())
465 Matches if a path exists and it refers to a directory::
467 # This will pass on most Linux systems.
468 self.assertThat('/home/', DirExists())
470 self.assertThat('/home/jml/some-file.txt', DirExists())
476 Matches if a path exists and it refers to a file (as opposed to a directory)::
478 # This will pass on most Linux systems.
479 self.assertThat('/bin/true', FileExists())
481 self.assertThat('/home/', FileExists())
487 Matches if the given directory contains the specified files and directories.
488 Say we have a directory ``foo`` that has the files ``a``, ``b`` and ``c``,
491 self.assertThat('foo', DirContains(['a', 'b', 'c']))
495 self.assertThat('foo', DirContains(['a', 'b']))
499 The matcher sorts both the input and the list of names we get back from the
502 You can use this in a more advanced way, and match the sorted directory
503 listing against an arbitrary matcher::
505 self.assertThat('foo', DirContains(matcher=Contains('a')))
511 Matches if the given file has the specified contents. Say there's a file
512 called ``greetings.txt`` with the contents, ``Hello World!``::
514 self.assertThat('greetings.txt', FileContains("Hello World!"))
518 You can also use this in a more advanced way, and match the contents of the
519 file against an arbitrary matcher::
521 self.assertThat('greetings.txt', FileContains(matcher=Contains('!')))
527 Used for asserting that a file or directory has certain permissions. Uses
528 octal-mode permissions for both input and matching. For example::
530 self.assertThat('/tmp', HasPermissions('1777'))
531 self.assertThat('id_rsa', HasPermissions('0600'))
533 This is probably more useful on UNIX systems than on Windows systems.
539 Matches if two paths actually refer to the same thing. The paths don't have
540 to exist, but if they do exist, ``SamePath`` will resolve any symlinks.::
542 self.assertThat('somefile', SamePath('childdir/../somefile'))
548 Matches the contents of a tarball. In many ways, much like ``DirContains``,
549 but instead of matching on ``os.listdir`` matches on ``TarFile.getnames``.
555 One great thing about matchers is that you can readily combine existing
556 matchers to get variations on their behaviour or to quickly build more complex
559 Below are a few of the combining matchers that come with testtools.
565 Negates another matcher. For example::
567 def test_not_example(self):
568 self.assertThat([42], Not(Equals("potato")))
569 self.assertThat([42], Not(Is([42])))
571 If you find yourself using ``Not`` frequently, you may wish to create a custom
572 matcher for it. For example::
574 IsNot = lambda x: Not(Is(x))
576 def test_not_example_2(self):
577 self.assertThat([42], IsNot([42]))
583 Used to add custom notes to a matcher. For example::
585 def test_annotate_example(self):
588 result, Annotate("Not the answer to the Question!", Equals(42))
590 Since the annotation is only ever displayed when there is a mismatch
591 (e.g. when ``result`` does not equal 42), it's a good idea to phrase the note
592 negatively, so that it describes what a mismatch actually means.
594 As with Not_, you may wish to create a custom matcher that describes a
595 common operation. For example::
597 PoliticallyEquals = lambda x: Annotate("Death to the aristos!", Equals(x))
599 def test_annotate_example_2(self):
600 self.assertThat("orange", PoliticallyEquals("yellow"))
602 You can have assertThat perform the annotation for you as a convenience::
604 def test_annotate_example_3(self):
605 self.assertThat("orange", Equals("yellow"), "Death to the aristos!")
611 Used to make a matcher that applies a function to the matched object before
612 matching. This can be used to aid in creating trivial matchers as functions, for
615 def test_after_preprocessing_example(self):
616 def HasFileContent(content):
618 return open(path).read()
619 return AfterPreprocessing(_read, Equals(content))
620 self.assertThat('/tmp/foo.txt', PathHasFileContent("Hello world!"))
626 Combines many matchers to make a new matcher. The new matcher will only match
627 things that match every single one of the component matchers.
629 It's much easier to understand in Python than in English::
631 def test_matches_all_example(self):
632 has_und_at_both_ends = MatchesAll(StartsWith("und"), EndsWith("und"))
634 self.assertThat("underground", has_und_at_both_ends)
636 self.assertThat("found", has_und_at_both_ends)
638 self.assertThat("undead", has_und_at_both_ends)
640 At this point some people ask themselves, "why bother doing this at all? why
641 not just have two separate assertions?". It's a good question.
643 The first reason is that when a ``MatchesAll`` gets a mismatch, the error will
644 include information about all of the bits that mismatched. When you have two
645 separate assertions, as below::
647 def test_two_separate_assertions(self):
648 self.assertThat("foo", StartsWith("und"))
649 self.assertThat("foo", EndsWith("und"))
651 Then you get absolutely no information from the second assertion if the first
652 assertion fails. Tests are largely there to help you debug code, so having
653 more information in error messages is a big help.
655 The second reason is that it is sometimes useful to give a name to a set of
656 matchers. ``has_und_at_both_ends`` is a bit contrived, of course, but it is
657 clear. The ``FileExists`` and ``DirExists`` matchers included in testtools
658 are perhaps better real examples.
660 If you want only the first mismatch to be reported, pass ``first_only=True``
661 as a keyword parameter to ``MatchesAll``.
667 Like MatchesAll_, ``MatchesAny`` combines many matchers to make a new
668 matcher. The difference is that the new matchers will match a thing if it
669 matches *any* of the component matchers.
673 def test_matches_any_example(self):
674 self.assertThat(42, MatchesAny(Equals(5), Not(Equals(6))))
680 Matches many values against a single matcher. Can be used to make sure that
681 many things all meet the same condition::
683 def test_all_match_example(self):
684 self.assertThat([2, 3, 5, 7], AllMatch(LessThan(10)))
686 If the match fails, then all of the values that fail to match will be included
687 in the error message.
689 In some ways, this is the converse of MatchesAll_.
695 Where ``MatchesAny`` and ``MatchesAll`` combine many matchers to match a
696 single value, ``MatchesListwise`` combines many matches to match many values.
700 def test_matches_listwise_example(self):
702 [1, 2, 3], MatchesListwise(map(Equals, [1, 2, 3])))
704 This is useful for writing custom, domain-specific matchers.
706 If you want only the first mismatch to be reported, pass ``first_only=True``
707 to ``MatchesListwise``.
713 Combines many matchers to match many values, without regard to their order.
717 def test_matches_setwise_example(self):
719 [1, 2, 3], MatchesSetwise(Equals(2), Equals(3), Equals(1)))
721 Much like ``MatchesListwise``, best used for writing custom, domain-specific
728 Creates a matcher that matches certain attributes of an object against a
729 pre-defined set of matchers.
731 It's much easier to understand in Python than in English::
733 def test_matches_structure_example(self):
737 matcher = MatchesStructure(a=Equals(1), b=Equals(2))
738 self.assertThat(foo, matcher)
740 Since all of the matchers used were ``Equals``, we could also write this using
741 the ``byEquality`` helper::
743 def test_matches_structure_example(self):
747 matcher = MatchesStructure.byEquality(a=1, b=2)
748 self.assertThat(foo, matcher)
750 ``MatchesStructure.fromExample`` takes an object and a list of attributes and
751 creates a ``MatchesStructure`` matcher where each attribute of the matched
752 object must equal each attribute of the example object. For example::
754 matcher = MatchesStructure.fromExample(foo, 'a', 'b')
756 is exactly equivalent to ``matcher`` in the previous example.
762 Sometimes, all you want to do is create a matcher that matches if a given
763 function returns True, and mismatches if it returns False.
765 For example, you might have an ``is_prime`` function and want to make a
766 matcher based on it::
768 def test_prime_numbers(self):
769 IsPrime = MatchesPredicate(is_prime, '%s is not prime.')
770 self.assertThat(7, IsPrime)
771 self.assertThat(1983, IsPrime)
773 self.assertThat(42, IsPrime)
775 Which will produce the error message::
777 Traceback (most recent call last):
778 File "...", line ..., in test_prime_numbers
779 self.assertThat(42, IsPrime)
780 MismatchError: 42 is not prime.
786 Takes whatever the callable raises as an exc_info tuple and matches it against
787 whatever matcher it was given. For example, if you want to assert that a
788 callable raises an exception of a given type::
790 def test_raises_example(self):
792 lambda: 1/0, Raises(MatchesException(ZeroDivisionError)))
794 Although note that this could also be written as::
796 def test_raises_example_convenient(self):
797 self.assertThat(lambda: 1/0, raises(ZeroDivisionError))
799 See also MatchesException_ and `the raises helper`_
802 Writing your own matchers
803 -------------------------
805 Combining matchers is fun and can get you a very long way indeed, but
806 sometimes you will have to write your own. Here's how.
808 You need to make two closely-linked objects: a ``Matcher`` and a
809 ``Mismatch``. The ``Matcher`` knows how to actually make the comparison, and
810 the ``Mismatch`` knows how to describe a failure to match.
812 Here's an example matcher::
814 class IsDivisibleBy(object):
815 """Match if a number is divisible by another number."""
816 def __init__(self, divider):
817 self.divider = divider
819 return 'IsDivisibleBy(%s)' % (self.divider,)
820 def match(self, actual):
821 remainder = actual % self.divider
823 return IsDivisibleByMismatch(actual, self.divider, remainder)
827 The matcher has a constructor that takes parameters that describe what you
828 actually *expect*, in this case a number that other numbers ought to be
829 divisible by. It has a ``__str__`` method, the result of which is displayed
830 on failure by ``assertThat`` and a ``match`` method that does the actual
833 ``match`` takes something to match against, here ``actual``, and decides
834 whether or not it matches. If it does match, then ``match`` must return
835 ``None``. If it does *not* match, then ``match`` must return a ``Mismatch``
836 object. ``assertThat`` will call ``match`` and then fail the test if it
837 returns a non-None value. For example::
839 def test_is_divisible_by_example(self):
840 # This succeeds, since IsDivisibleBy(5).match(10) returns None.
841 self.assertThat(10, IsDivisbleBy(5))
842 # This fails, since IsDivisibleBy(7).match(10) returns a mismatch.
843 self.assertThat(10, IsDivisbleBy(7))
845 The mismatch is responsible for what sort of error message the failing test
846 generates. Here's an example mismatch::
848 class IsDivisibleByMismatch(object):
849 def __init__(self, number, divider, remainder):
851 self.divider = divider
852 self.remainder = remainder
855 return "%r is not divisible by %r, %r remains" % (
856 self.number, self.divider, self.remainder)
858 def get_details(self):
861 The mismatch takes information about the mismatch, and provides a ``describe``
862 method that assembles all of that into a nice error message for end users.
863 You can use the ``get_details`` method to provide extra, arbitrary data with
864 the mismatch (e.g. the contents of a log file). Most of the time it's fine to
865 just return an empty dict. You can read more about Details_ elsewhere in this
868 Sometimes you don't need to create a custom mismatch class. In particular, if
869 you don't care *when* the description is calculated, then you can just do that
870 in the Matcher itself like this::
872 def match(self, actual):
873 remainder = actual % self.divider
876 "%r is not divisible by %r, %r remains" % (
877 actual, self.divider, remainder))
881 When writing a ``describe`` method or constructing a ``Mismatch`` object the
882 code should ensure it only emits printable unicode. As this output must be
883 combined with other text and forwarded for presentation, letting through
884 non-ascii bytes of ambiguous encoding or control characters could throw an
885 exception or mangle the display. In most cases simply avoiding the ``%s``
886 format specifier and using ``%r`` instead will be enough. For examples of
887 more complex formatting see the ``testtools.matchers`` implementatons.
893 As we may have mentioned once or twice already, one of the great benefits of
894 automated tests is that they help find, isolate and debug errors in your
897 Frequently however, the information provided by a mere assertion failure is
898 not enough. It's often useful to have other information: the contents of log
899 files; what queries were run; benchmark timing information; what state certain
900 subsystem components are in and so forth.
902 testtools calls all of these things "details" and provides a single, powerful
903 mechanism for including this information in your test run.
905 Here's an example of how to add them::
907 from testtools import TestCase
908 from testtools.content import text_content
910 class TestSomething(TestCase):
912 def test_thingy(self):
913 self.addDetail('arbitrary-color-name', text_content("blue"))
914 1 / 0 # Gratuitous error!
916 A detail an arbitrary piece of content given a name that's unique within the
917 test. Here the name is ``arbitrary-color-name`` and the content is
918 ``text_content("blue")``. The name can be any text string, and the content
919 can be any ``testtools.content.Content`` object.
921 When the test runs, testtools will show you something like this::
923 ======================================================================
924 ERROR: exampletest.TestSomething.test_thingy
925 ----------------------------------------------------------------------
926 arbitrary-color-name: {{{blue}}}
928 Traceback (most recent call last):
929 File "exampletest.py", line 8, in test_thingy
930 1 / 0 # Gratuitous error!
931 ZeroDivisionError: integer division or modulo by zero
935 As you can see, the detail is included as an attachment, here saying
936 that our arbitrary-color-name is "blue".
942 For the actual content of details, testtools uses its own MIME-based Content
943 object. This allows you to attach any information that you could possibly
944 conceive of to a test, and allows testtools to use or serialize that
947 The basic ``testtools.content.Content`` object is constructed from a
948 ``testtools.content.ContentType`` and a nullary callable that must return an
949 iterator of chunks of bytes that the content is made from.
951 So, to make a Content object that is just a simple string of text, you can
954 from testtools.content import Content
955 from testtools.content_type import ContentType
957 text = Content(ContentType('text', 'plain'), lambda: ["some text"])
959 Because adding small bits of text content is very common, there's also a
962 text = text_content("some text")
964 To make content out of an image stored on disk, you could do something like::
966 image = Content(ContentType('image', 'png'), lambda: open('foo.png').read())
968 Or you could use the convenience function::
970 image = content_from_file('foo.png', ContentType('image', 'png'))
972 The ``lambda`` helps make sure that the file is opened and the actual bytes
973 read only when they are needed – by default, when the test is finished. This
974 means that tests can construct and add Content objects freely without worrying
975 too much about how they affect run time.
981 A very common use of details is to add a log file to failing tests. Say your
982 project has a server represented by a class ``SomeServer`` that you can start
983 up and shut down in tests, but runs in another process. You want to test
984 interaction with that server, and whenever the interaction fails, you want to
985 see the client-side error *and* the logs from the server-side. Here's how you
988 from testtools import TestCase
989 from testtools.content import attach_file, Content
990 from testtools.content_type import UTF8_TEXT
992 from myproject import SomeServer
994 class SomeTestCase(TestCase):
997 super(SomeTestCase, self).setUp()
998 self.server = SomeServer()
999 self.server.start_up()
1000 self.addCleanup(self.server.shut_down)
1001 self.addCleanup(attach_file, self.server.logfile, self)
1003 def attach_log_file(self):
1007 lambda: open(self.server.logfile, 'r').readlines()))
1009 def test_a_thing(self):
1010 self.assertEqual("cool", self.server.temperature)
1012 This test will attach the log file of ``SomeServer`` to each test that is
1013 run. testtools will only display the log file for failing tests, so it's not
1016 If the act of adding at detail is expensive, you might want to use
1017 addOnException_ so that you only do it when a test actually raises an
1021 Controlling test execution
1022 ==========================
1029 ``TestCase.addCleanup`` is a robust way to arrange for a clean up function to
1030 be called before ``tearDown``. This is a powerful and simple alternative to
1031 putting clean up logic in a try/finally block or ``tearDown`` method. For
1036 self.addCleanup(foo.unlock)
1039 This is particularly useful if you have some sort of factory in your test::
1041 def make_locked_foo(self):
1044 self.addCleanup(foo.unlock)
1047 def test_frotz_a_foo(self):
1048 foo = self.make_locked_foo()
1050 self.assertEqual(foo.frotz_count, 1)
1052 Any extra arguments or keyword arguments passed to ``addCleanup`` are passed
1053 to the callable at cleanup time.
1055 Cleanups can also report multiple errors, if appropriate by wrapping them in
1056 a ``testtools.MultipleExceptions`` object::
1058 raise MultipleExceptions(exc_info1, exc_info2)
1064 Tests often depend on a system being set up in a certain way, or having
1065 certain resources available to them. Perhaps a test needs a connection to the
1066 database or access to a running external server.
1068 One common way of doing this is to do::
1070 class SomeTest(TestCase):
1072 super(SomeTest, self).setUp()
1073 self.server = Server()
1075 self.addCleanup(self.server.tearDown)
1077 testtools provides a more convenient, declarative way to do the same thing::
1079 class SomeTest(TestCase):
1081 super(SomeTest, self).setUp()
1082 self.server = self.useFixture(Server())
1084 ``useFixture(fixture)`` calls ``setUp`` on the fixture, schedules a clean up
1085 to clean it up, and schedules a clean up to attach all details_ held by the
1086 fixture to the test case. The fixture object must meet the
1087 ``fixtures.Fixture`` protocol (version 0.3.4 or newer, see fixtures_).
1089 If you have anything beyond the most simple test set up, we recommend that
1090 you put this set up into a ``Fixture`` class. Once there, the fixture can be
1091 easily re-used by other tests and can be combined with other fixtures to make
1092 more complex resources.
1098 Many reasons exist to skip a test: a dependency might be missing; a test might
1099 be too expensive and thus should not berun while on battery power; or perhaps
1100 the test is testing an incomplete feature.
1102 ``TestCase.skipTest`` is a simple way to have a test stop running and be
1103 reported as a skipped test, rather than a success, error or failure. For
1106 def test_make_symlink(self):
1107 symlink = getattr(os, 'symlink', None)
1109 self.skipTest("No symlink support")
1110 symlink(whatever, something_else)
1112 Using ``skipTest`` means that you can make decisions about what tests to run
1113 as late as possible, and close to the actual tests. Without it, you might be
1114 forced to use convoluted logic during test loading, which is a bit of a mess.
1120 If you are using this feature when running your test suite with a legacy
1121 ``TestResult`` object that is missing the ``addSkip`` method, then the
1122 ``addError`` method will be invoked instead. If you are using a test result
1123 from testtools, you do not have to worry about this.
1125 In older versions of testtools, ``skipTest`` was known as ``skip``. Since
1126 Python 2.7 added ``skipTest`` support, the ``skip`` name is now deprecated.
1127 No warning is emitted yet – some time in the future we may do so.
1133 Sometimes, you might wish to do something only when a test fails. Perhaps you
1134 need to run expensive diagnostic routines or some such.
1135 ``TestCase.addOnException`` allows you to easily do just this. For example::
1137 class SomeTest(TestCase):
1139 super(SomeTest, self).setUp()
1140 self.server = self.useFixture(SomeServer())
1141 self.addOnException(self.attach_server_diagnostics)
1143 def attach_server_diagnostics(self, exc_info):
1144 self.server.prep_for_diagnostics() # Expensive!
1145 self.addDetail('server-diagnostics', self.server.get_diagnostics)
1147 def test_a_thing(self):
1148 self.assertEqual('cheese', 'chalk')
1150 In this example, ``attach_server_diagnostics`` will only be called when a test
1151 fails. It is given the exc_info tuple of the error raised by the test, just
1152 in case it is needed.
1158 testtools provides *highly experimental* support for running Twisted tests –
1159 tests that return a Deferred_ and rely on the Twisted reactor. You should not
1160 use this feature right now. We reserve the right to change the API and
1161 behaviour without telling you first.
1163 However, if you are going to, here's how you do it::
1165 from testtools import TestCase
1166 from testtools.deferredruntest import AsynchronousDeferredRunTest
1168 class MyTwistedTests(TestCase):
1170 run_tests_with = AsynchronousDeferredRunTest
1176 In particular, note that you do *not* have to use a special base ``TestCase``
1177 in order to run Twisted tests.
1179 You can also run individual tests within a test case class using the Twisted
1182 class MyTestsSomeOfWhichAreTwisted(TestCase):
1184 def test_normal(self):
1187 @run_test_with(AsynchronousDeferredRunTest)
1188 def test_twisted(self):
1192 Here are some tips for converting your Trial tests into testtools tests.
1194 * Use the ``AsynchronousDeferredRunTest`` runner
1195 * Make sure to upcall to ``setUp`` and ``tearDown``
1196 * Don't use ``setUpClass`` or ``tearDownClass``
1197 * Don't expect setting .todo, .timeout or .skip attributes to do anything
1198 * ``flushLoggedErrors`` is ``testtools.deferredruntest.flush_logged_errors``
1199 * ``assertFailure`` is ``testtools.deferredruntest.assert_fails_with``
1200 * Trial spins the reactor a couple of times before cleaning it up,
1201 ``AsynchronousDeferredRunTest`` does not. If you rely on this behavior, use
1202 ``AsynchronousDeferredRunTestForBrokenTwisted``.
1208 testtools comes with a few little things that make it a little bit easier to
1215 ``patch`` is a convenient way to monkey-patch a Python object for the duration
1216 of your test. It's especially useful for testing legacy code. e.g.::
1219 my_stream = StringIO()
1220 self.patch(sys, 'stderr', my_stream)
1221 run_some_code_that_prints_to_stderr()
1222 self.assertEqual('', my_stream.getvalue())
1224 The call to ``patch`` above masks ``sys.stderr`` with ``my_stream`` so that
1225 anything printed to stderr will be captured in a StringIO variable that can be
1226 actually tested. Once the test is done, the real ``sys.stderr`` is restored to
1233 Often when writing unit tests, you want to create an object that is a
1234 completely normal instance of its type. You don't want there to be anything
1235 special about its properties, because you are testing generic behaviour rather
1236 than specific conditions.
1238 A lot of the time, test authors do this by making up silly strings and numbers
1239 and passing them to constructors (e.g. 42, 'foo', "bar" etc), and that's
1240 fine. However, sometimes it's useful to be able to create arbitrary objects
1241 at will, without having to make up silly sample data.
1243 To help with this, ``testtools.TestCase`` implements creation methods called
1244 ``getUniqueString`` and ``getUniqueInteger``. They return strings and
1245 integers that are unique within the context of the test that can be used to
1246 assemble more complex objects. Here's a basic example where
1247 ``getUniqueString`` is used instead of saying "foo" or "bar" or whatever::
1249 class SomeTest(TestCase):
1251 def test_full_name(self):
1252 first_name = self.getUniqueString()
1253 last_name = self.getUniqueString()
1254 p = Person(first_name, last_name)
1255 self.assertEqual(p.full_name, "%s %s" % (first_name, last_name))
1258 And here's how it could be used to make a complicated test::
1260 class TestCoupleLogic(TestCase):
1262 def make_arbitrary_person(self):
1263 return Person(self.getUniqueString(), self.getUniqueString())
1265 def test_get_invitation(self):
1266 a = self.make_arbitrary_person()
1267 b = self.make_arbitrary_person()
1268 couple = Couple(a, b)
1269 event_name = self.getUniqueString()
1270 invitation = couple.get_invitation(event_name)
1273 "We invite %s and %s to %s" % (
1274 a.full_name, b.full_name, event_name))
1276 Essentially, creation methods like these are a way of reducing the number of
1277 assumptions in your tests and communicating to test readers that the exact
1278 details of certain variables don't actually matter.
1280 See pages 419-423 of `xUnit Test Patterns`_ by Gerard Meszaros for a detailed
1281 discussion of creation methods.
1290 Lots of the time we would like to conditionally import modules. testtools
1291 needs to do this itself, and graciously extends the ability to its users.
1296 from twisted.internet import defer
1302 defer = try_import('twisted.internet.defer')
1308 from StringIO import StringIO
1310 from io import StringIO
1314 StringIO = try_imports(['StringIO.StringIO', 'io.StringIO'])
1317 Safe attribute testing
1318 ----------------------
1320 ``hasattr`` is broken_ on many versions of Python. testtools provides
1321 ``safe_hasattr``, which can be used to safely test whether an object has a
1322 particular attribute.
1328 Sometimes you want to be able to pass around a function with the arguments
1329 already specified. The normal way of doing this in Python is::
1331 nullary = lambda: f(*args, **kwargs)
1334 Which is mostly good enough, but loses a bit of debugging information. If you
1335 take the ``repr()`` of ``nullary``, you're only told that it's a lambda, and
1336 you get none of the juicy meaning that you'd get from the ``repr()`` of ``f``.
1338 The solution is to use ``Nullary`` instead::
1340 nullary = Nullary(f, *args, **kwargs)
1343 Here, ``repr(nullary)`` will be the same as ``repr(f)``.
1346 .. _testrepository: https://launchpad.net/testrepository
1347 .. _Trial: http://twistedmatrix.com/documents/current/core/howto/testing.html
1348 .. _nose: http://somethingaboutorange.com/mrl/projects/nose/
1349 .. _unittest2: http://pypi.python.org/pypi/unittest2
1350 .. _zope.testrunner: http://pypi.python.org/pypi/zope.testrunner/
1351 .. _xUnit test patterns: http://xunitpatterns.com/
1352 .. _fixtures: http://pypi.python.org/pypi/fixtures
1353 .. _unittest: http://docs.python.org/library/unittest.html
1354 .. _doctest: http://docs.python.org/library/doctest.html
1355 .. _Deferred: http://twistedmatrix.com/documents/current/core/howto/defer.html
1356 .. _discover: http://pypi.python.org/pypi/discover
1357 .. _`testtools API docs`: http://mumak.net/testtools/apidocs/
1358 .. _Distutils: http://docs.python.org/library/distutils.html
1359 .. _`setup configuration`: http://docs.python.org/distutils/configfile.html
1360 .. _broken: http://chipaca.com/post/3210673069/hasattr-17-less-harmful