04c4be6b0dba841a47a8cc7a3856721828a24c13
[mat/samba.git] / lib / testtools / doc / for-test-authors.rst
1 ==========================
2 testtools for test authors
3 ==========================
4
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.
7
8 We assume that you already know Python and that you know something about
9 automated testing already.
10
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`.
13
14 You might also be interested in the `testtools API docs`_.
15
16
17 Introduction
18 ============
19
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
23 more enjoyable.
24
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.
28
29
30 The basics
31 ==========
32
33 Here's what a basic testtools unit tests look like::
34
35   from testtools import TestCase
36   from myproject import silly
37
38   class TestSillySquare(TestCase):
39       """Tests for silly square function."""
40
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)
45
46       def test_square_bad_input(self):
47           # 'square' raises a TypeError if it's given bad input, say a
48           # string.
49           self.assertRaises(TypeError, silly.square, "orange")
50
51
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_``.
55
56 Running your tests
57 ------------------
58
59 You can run these tests in many ways.  testtools provides a very basic
60 mechanism for doing so::
61
62   $ python -m testtools.run exampletest
63   Tests running...
64   Ran 2 tests in 0.000s
65
66   OK
67
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::
72
73   $ python -m testtools.run discover packagecontainingtests
74
75 For more information see the Python 2.7 unittest documentation, or::
76
77     python -m testtools.run --help
78
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:
82
83 * testrepository_
84 * Trial_
85 * nose_
86 * unittest2_
87 * `zope.testrunner`_ (aka zope.testing)
88
89 From now on, we'll assume that you know how to run your tests.
90
91 Running test with Distutils
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93
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::
96
97   from distutils.core import setup
98   from testtools import TestCommand
99   setup(name='foo',
100       version='1.0',
101       py_modules=['foo'],
102       cmdclass={'test': TestCommand}
103   )
104
105 You can then run::
106
107   $ python setup.py test -m exampletest
108   Tests running...
109   Ran 2 tests in 0.000s
110
111   OK
112
113 For more information about the capabilities of the `TestCommand` command see::
114
115         $ python setup.py test --help
116
117 You can use the `setup configuration`_ to specify the default behavior of the
118 `TestCommand` command.
119
120 Assertions
121 ==========
122
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
125 they ought to be.
126
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.
131
132
133 Improved assertRaises
134 ---------------------
135
136 ``TestCase.assertRaises`` returns the caught exception.  This is useful for
137 asserting more things about the exception than just the type::
138
139   def test_square_bad_input(self):
140       # 'square' raises a TypeError if it's given bad input, say a
141       # string.
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))
145
146 Note that this is incompatible with the ``assertRaises`` in unittest2 and
147 Python2.7.
148
149
150 ExpectedException
151 -----------------
152
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::
156
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')
161
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.
167
168
169 assertIn, assertNotIn
170 ---------------------
171
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::
175
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)
181
182
183 assertIs, assertIsNot
184 ---------------------
185
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::
189
190   def test_assert_is_example(self):
191       foo = [None]
192       foo_alias = foo
193       bar = [None]
194       self.assertIs(foo, foo_alias)
195       self.assertIsNot(foo, bar)
196       self.assertEqual(foo, bar) # They are equal, but not identical
197
198
199 assertIsInstance
200 ----------------
201
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
204 example::
205
206   def test_assert_is_instance_example(self):
207       now = datetime.now()
208       self.assertIsInstance(now, datetime)
209
210 Note that there is no ``assertIsNotInstance`` in testtools currently.
211
212
213 expectFailure
214 -------------
215
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
219 dependency.
220
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".
224
225 Here's an example::
226
227   def test_expect_failure_example(self):
228       self.expectFailure(
229           "cats should be dogs", self.assertEqual, 'cats', 'dogs')
230
231 As long as 'cats' is not equal to 'dogs', the test will be reported as an
232 expected failure.
233
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.
237
238
239 Matchers
240 ========
241
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
248 file).
249
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``
253 system.
254
255
256 Using Matchers
257 --------------
258
259 Here's a really basic example using stock matchers found in testtools::
260
261   import testtools
262   from testtools.matchers import Equals
263
264   class TestSquare(TestCase):
265       def test_square(self):
266          result = square(7)
267          self.assertThat(result, Equals(49))
268
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)``).
274
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
277 existing ones::
278
279   def test_square_silly(self):
280       result = square(7)
281       self.assertThat(result, Not(Equals(50)))
282
283 Which is roughly equivalent to::
284
285   def test_square_silly(self):
286       result = square(7)
287       self.assertNotEqual(result, 50)
288
289
290 Stock matchers
291 --------------
292
293 testtools comes with many matchers built in.  They can all be found in and
294 imported from the ``testtools.matchers`` module.
295
296 Equals
297 ~~~~~~
298
299 Matches if two items are equal. For example::
300
301   def test_equals_example(self):
302       self.assertThat([42], Equals([42]))
303
304
305 Is
306 ~~~
307
308 Matches if two items are identical.  For example::
309
310   def test_is_example(self):
311       foo = object()
312       self.assertThat(foo, Is(foo))
313
314
315 IsInstance
316 ~~~~~~~~~~
317
318 Adapts isinstance() to use as a matcher.  For example::
319
320   def test_isinstance_example(self):
321       class MyClass:pass
322       self.assertThat(MyClass(), IsInstance(MyClass))
323       self.assertThat(MyClass(), IsInstance(MyClass, str))
324
325
326 The raises helper
327 ~~~~~~~~~~~~~~~~~
328
329 Matches if a callable raises a particular type of exception.  For example::
330
331   def test_raises_example(self):
332       self.assertThat(lambda: 1/0, raises(ZeroDivisionError))
333
334 This is actually a convenience function that combines two other matchers:
335 Raises_ and MatchesException_.
336
337
338 DocTestMatches
339 ~~~~~~~~~~~~~~
340
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::
343
344   import doctest
345
346   def test_doctest_example(self):
347       output = "Colorless green ideas"
348       self.assertThat(
349           output,
350           DocTestMatches("Colorless ... ideas", doctest.ELLIPSIS))
351
352 We highly recommend using the following flags::
353
354   doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_NDIFF
355
356
357 GreaterThan
358 ~~~~~~~~~~~
359
360 Matches if the given thing is greater than the thing in the matcher.  For
361 example::
362
363   def test_greater_than_example(self):
364       self.assertThat(3, GreaterThan(2))
365
366
367 LessThan
368 ~~~~~~~~
369
370 Matches if the given thing is less than the thing in the matcher.  For
371 example::
372
373   def test_less_than_example(self):
374       self.assertThat(2, LessThan(3))
375
376
377 StartsWith, EndsWith
378 ~~~~~~~~~~~~~~~~~~~~
379
380 These matchers check to see if a string starts with or ends with a particular
381 substring.  For example::
382
383   def test_starts_and_ends_with_example(self):
384       self.assertThat('underground', StartsWith('und'))
385       self.assertThat('underground', EndsWith('und'))
386
387
388 Contains
389 ~~~~~~~~
390
391 This matcher checks to see if the given thing contains the thing in the
392 matcher.  For example::
393
394   def test_contains_example(self):
395       self.assertThat('abc', Contains('b'))
396
397
398 MatchesException
399 ~~~~~~~~~~~~~~~~
400
401 Matches an exc_info tuple if the exception is of the correct type.  For
402 example::
403
404   def test_matches_exception_example(self):
405       try:
406           raise RuntimeError('foo')
407       except RuntimeError:
408           exc_info = sys.exc_info()
409       self.assertThat(exc_info, MatchesException(RuntimeError))
410       self.assertThat(exc_info, MatchesException(RuntimeError('bar'))
411
412 Most of the time, you will want to uses `The raises helper`_ instead.
413
414
415 NotEquals
416 ~~~~~~~~~
417
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``.
421
422 You only need to worry about this distinction if you are testing code that
423 relies on badly written overloaded equality operators.
424
425
426 KeysEqual
427 ~~~~~~~~~
428
429 Matches if the keys of one dict are equal to the keys of another dict.  For
430 example::
431
432   def test_keys_equal(self):
433       x = {'a': 1, 'b': 2}
434       y = {'a': 2, 'b': 3}
435       self.assertThat(a, KeysEqual(b))
436
437
438 MatchesRegex
439 ~~~~~~~~~~~~
440
441 Matches a string against a regular expression, which is a wonderful thing to
442 be able to do, if you think about it::
443
444   def test_matches_regex_example(self):
445       self.assertThat('foo', MatchesRegex('fo+'))
446
447
448 Combining matchers
449 ------------------
450
451 One great thing about matchers is that you can readily combine existing
452 matchers to get variations on their behaviour or to quickly build more complex
453 assertions.
454
455 Below are a few of the combining matchers that come with testtools.
456
457
458 Not
459 ~~~
460
461 Negates another matcher.  For example::
462
463   def test_not_example(self):
464       self.assertThat([42], Not(Equals("potato")))
465       self.assertThat([42], Not(Is([42])))
466
467 If you find yourself using ``Not`` frequently, you may wish to create a custom
468 matcher for it.  For example::
469
470   IsNot = lambda x: Not(Is(x))
471
472   def test_not_example_2(self):
473       self.assertThat([42], IsNot([42]))
474
475
476 Annotate
477 ~~~~~~~~
478
479 Used to add custom notes to a matcher.  For example::
480
481   def test_annotate_example(self):
482       result = 43
483       self.assertThat(
484           result, Annotate("Not the answer to the Question!", Equals(42))
485
486 Since the annotation is only ever displayed when there is a mismatch
487 (e.g. when ``result`` does not equal 42), it's a good idea to phrase the note
488 negatively, so that it describes what a mismatch actually means.
489
490 As with Not_, you may wish to create a custom matcher that describes a
491 common operation.  For example::
492
493   PoliticallyEquals = lambda x: Annotate("Death to the aristos!", Equals(x))
494
495   def test_annotate_example_2(self):
496       self.assertThat("orange", PoliticallyEquals("yellow"))
497
498 You can have assertThat perform the annotation for you as a convenience::
499
500   def test_annotate_example_3(self):
501       self.assertThat("orange", Equals("yellow"), "Death to the aristos!")
502
503
504 AfterPreprocessing
505 ~~~~~~~~~~~~~~~~~~
506
507 Used to make a matcher that applies a function to the matched object before
508 matching. This can be used to aid in creating trivial matchers as functions, for
509 example::
510
511   def test_after_preprocessing_example(self):
512       def HasFileContent(content):
513           def _read(path):
514               return open(path).read()
515           return AfterPreprocessing(_read, Equals(content))
516       self.assertThat('/tmp/foo.txt', PathHasFileContent("Hello world!"))
517
518
519 MatchesAll
520 ~~~~~~~~~~
521
522 Combines many matchers to make a new matcher.  The new matcher will only match
523 things that match every single one of the component matchers.
524
525 It's much easier to understand in Python than in English::
526
527   def test_matches_all_example(self):
528       has_und_at_both_ends = MatchesAll(StartsWith("und"), EndsWith("und"))
529       # This will succeed.
530       self.assertThat("underground", has_und_at_both_ends)
531       # This will fail.
532       self.assertThat("found", has_und_at_both_ends)
533       # So will this.
534       self.assertThat("undead", has_und_at_both_ends)
535
536 At this point some people ask themselves, "why bother doing this at all? why
537 not just have two separate assertions?".  It's a good question.
538
539 The first reason is that when a ``MatchesAll`` gets a mismatch, the error will
540 include information about all of the bits that mismatched.  When you have two
541 separate assertions, as below::
542
543   def test_two_separate_assertions(self):
544        self.assertThat("foo", StartsWith("und"))
545        self.assertThat("foo", EndsWith("und"))
546
547 Then you get absolutely no information from the second assertion if the first
548 assertion fails.  Tests are largely there to help you debug code, so having
549 more information in error messages is a big help.
550
551 The second reason is that it is sometimes useful to give a name to a set of
552 matchers. ``has_und_at_both_ends`` is a bit contrived, of course, but it is
553 clear.
554
555
556 MatchesAny
557 ~~~~~~~~~~
558
559 Like MatchesAll_, ``MatchesAny`` combines many matchers to make a new
560 matcher.  The difference is that the new matchers will match a thing if it
561 matches *any* of the component matchers.
562
563 For example::
564
565   def test_matches_any_example(self):
566       self.assertThat(42, MatchesAny(Equals(5), Not(Equals(6))))
567
568
569 AllMatch
570 ~~~~~~~~
571
572 Matches many values against a single matcher.  Can be used to make sure that
573 many things all meet the same condition::
574
575   def test_all_match_example(self):
576       self.assertThat([2, 3, 5, 7], AllMatch(LessThan(10)))
577
578 If the match fails, then all of the values that fail to match will be included
579 in the error message.
580
581 In some ways, this is the converse of MatchesAll_.
582
583
584 MatchesListwise
585 ~~~~~~~~~~~~~~~
586
587 Where ``MatchesAny`` and ``MatchesAll`` combine many matchers to match a
588 single value, ``MatchesListwise`` combines many matches to match many values.
589
590 For example::
591
592   def test_matches_listwise_example(self):
593       self.assertThat(
594           [1, 2, 3], MatchesListwise(map(Equals, [1, 2, 3])))
595
596 This is useful for writing custom, domain-specific matchers.
597
598
599 MatchesSetwise
600 ~~~~~~~~~~~~~~
601
602 Combines many matchers to match many values, without regard to their order.
603
604 Here's an example::
605
606   def test_matches_setwise_example(self):
607       self.assertThat(
608           [1, 2, 3], MatchesSetwise(Equals(2), Equals(3), Equals(1)))
609
610 Much like ``MatchesListwise``, best used for writing custom, domain-specific
611 matchers.
612
613
614 MatchesStructure
615 ~~~~~~~~~~~~~~~~
616
617 Creates a matcher that matches certain attributes of an object against a
618 pre-defined set of matchers.
619
620 It's much easier to understand in Python than in English::
621
622   def test_matches_structure_example(self):
623       foo = Foo()
624       foo.a = 1
625       foo.b = 2
626       matcher = MatchesStructure(a=Equals(1), b=Equals(2))
627       self.assertThat(foo, matcher)
628
629 Since all of the matchers used were ``Equals``, we could also write this using
630 the ``byEquality`` helper::
631
632   def test_matches_structure_example(self):
633       foo = Foo()
634       foo.a = 1
635       foo.b = 2
636       matcher = MatchesStructure.byEquality(a=1, b=2)
637       self.assertThat(foo, matcher)
638
639 ``MatchesStructure.fromExample`` takes an object and a list of attributes and
640 creates a ``MatchesStructure`` matcher where each attribute of the matched
641 object must equal each attribute of the example object.  For example::
642
643       matcher = MatchesStructure.fromExample(foo, 'a', 'b')
644
645 is exactly equivalent to ``matcher`` in the previous example.
646
647
648 Raises
649 ~~~~~~
650
651 Takes whatever the callable raises as an exc_info tuple and matches it against
652 whatever matcher it was given.  For example, if you want to assert that a
653 callable raises an exception of a given type::
654
655   def test_raises_example(self):
656       self.assertThat(
657           lambda: 1/0, Raises(MatchesException(ZeroDivisionError)))
658
659 Although note that this could also be written as::
660
661   def test_raises_example_convenient(self):
662       self.assertThat(lambda: 1/0, raises(ZeroDivisionError))
663
664 See also MatchesException_ and `the raises helper`_
665
666
667 Writing your own matchers
668 -------------------------
669
670 Combining matchers is fun and can get you a very long way indeed, but
671 sometimes you will have to write your own.  Here's how.
672
673 You need to make two closely-linked objects: a ``Matcher`` and a
674 ``Mismatch``.  The ``Matcher`` knows how to actually make the comparison, and
675 the ``Mismatch`` knows how to describe a failure to match.
676
677 Here's an example matcher::
678
679   class IsDivisibleBy(object):
680       """Match if a number is divisible by another number."""
681       def __init__(self, divider):
682           self.divider = divider
683       def __str__(self):
684           return 'IsDivisibleBy(%s)' % (self.divider,)
685       def match(self, actual):
686           remainder = actual % self.divider
687           if remainder != 0:
688               return IsDivisibleByMismatch(actual, self.divider, remainder)
689           else:
690               return None
691
692 The matcher has a constructor that takes parameters that describe what you
693 actually *expect*, in this case a number that other numbers ought to be
694 divisible by.  It has a ``__str__`` method, the result of which is displayed
695 on failure by ``assertThat`` and a ``match`` method that does the actual
696 matching.
697
698 ``match`` takes something to match against, here ``actual``, and decides
699 whether or not it matches.  If it does match, then ``match`` must return
700 ``None``.  If it does *not* match, then ``match`` must return a ``Mismatch``
701 object. ``assertThat`` will call ``match`` and then fail the test if it
702 returns a non-None value.  For example::
703
704   def test_is_divisible_by_example(self):
705       # This succeeds, since IsDivisibleBy(5).match(10) returns None.
706       self.assertThat(10, IsDivisbleBy(5))
707       # This fails, since IsDivisibleBy(7).match(10) returns a mismatch.
708       self.assertThat(10, IsDivisbleBy(7))
709
710 The mismatch is responsible for what sort of error message the failing test
711 generates.  Here's an example mismatch::
712
713   class IsDivisibleByMismatch(object):
714       def __init__(self, number, divider, remainder):
715           self.number = number
716           self.divider = divider
717           self.remainder = remainder
718
719       def describe(self):
720           return "%r is not divisible by %r, %r remains" % (
721               self.number, self.divider, self.remainder)
722
723       def get_details(self):
724           return {}
725
726 The mismatch takes information about the mismatch, and provides a ``describe``
727 method that assembles all of that into a nice error message for end users.
728 You can use the ``get_details`` method to provide extra, arbitrary data with
729 the mismatch (e.g. the contents of a log file).  Most of the time it's fine to
730 just return an empty dict.  You can read more about Details_ elsewhere in this
731 document.
732
733 Sometimes you don't need to create a custom mismatch class.  In particular, if
734 you don't care *when* the description is calculated, then you can just do that
735 in the Matcher itself like this::
736
737   def match(self, actual):
738       remainder = actual % self.divider
739       if remainder != 0:
740           return Mismatch(
741               "%r is not divisible by %r, %r remains" % (
742                   actual, self.divider, remainder))
743       else:
744           return None
745
746 When writing a ``describe`` method or constructing a ``Mismatch`` object the
747 code should ensure it only emits printable unicode.  As this output must be
748 combined with other text and forwarded for presentation, letting through
749 non-ascii bytes of ambiguous encoding or control characters could throw an
750 exception or mangle the display.  In most cases simply avoiding the ``%s``
751 format specifier and using ``%r`` instead will be enough.  For examples of
752 more complex formatting see the ``testtools.matchers`` implementatons.
753
754
755 Details
756 =======
757
758 As we may have mentioned once or twice already, one of the great benefits of
759 automated tests is that they help find, isolate and debug errors in your
760 system.
761
762 Frequently however, the information provided by a mere assertion failure is
763 not enough.  It's often useful to have other information: the contents of log
764 files; what queries were run; benchmark timing information; what state certain
765 subsystem components are in and so forth.
766
767 testtools calls all of these things "details" and provides a single, powerful
768 mechanism for including this information in your test run.
769
770 Here's an example of how to add them::
771
772   from testtools import TestCase
773   from testtools.content import text_content
774
775   class TestSomething(TestCase):
776
777       def test_thingy(self):
778           self.addDetail('arbitrary-color-name', text_content("blue"))
779           1 / 0 # Gratuitous error!
780
781 A detail an arbitrary piece of content given a name that's unique within the
782 test.  Here the name is ``arbitrary-color-name`` and the content is
783 ``text_content("blue")``.  The name can be any text string, and the content
784 can be any ``testtools.content.Content`` object.
785
786 When the test runs, testtools will show you something like this::
787
788   ======================================================================
789   ERROR: exampletest.TestSomething.test_thingy
790   ----------------------------------------------------------------------
791   arbitrary-color-name: {{{blue}}}
792
793   Traceback (most recent call last):
794     File "exampletest.py", line 8, in test_thingy
795       1 / 0 # Gratuitous error!
796   ZeroDivisionError: integer division or modulo by zero
797   ------------
798   Ran 1 test in 0.030s
799
800 As you can see, the detail is included as an attachment, here saying
801 that our arbitrary-color-name is "blue".
802
803
804 Content
805 -------
806
807 For the actual content of details, testtools uses its own MIME-based Content
808 object.  This allows you to attach any information that you could possibly
809 conceive of to a test, and allows testtools to use or serialize that
810 information.
811
812 The basic ``testtools.content.Content`` object is constructed from a
813 ``testtools.content.ContentType`` and a nullary callable that must return an
814 iterator of chunks of bytes that the content is made from.
815
816 So, to make a Content object that is just a simple string of text, you can
817 do::
818
819   from testtools.content import Content
820   from testtools.content_type import ContentType
821
822   text = Content(ContentType('text', 'plain'), lambda: ["some text"])
823
824 Because adding small bits of text content is very common, there's also a
825 convenience method::
826
827   text = text_content("some text")
828
829 To make content out of an image stored on disk, you could do something like::
830
831   image = Content(ContentType('image', 'png'), lambda: open('foo.png').read())
832
833 Or you could use the convenience function::
834
835   image = content_from_file('foo.png', ContentType('image', 'png'))
836
837 The ``lambda`` helps make sure that the file is opened and the actual bytes
838 read only when they are needed – by default, when the test is finished.  This
839 means that tests can construct and add Content objects freely without worrying
840 too much about how they affect run time.
841
842
843 A realistic example
844 -------------------
845
846 A very common use of details is to add a log file to failing tests.  Say your
847 project has a server represented by a class ``SomeServer`` that you can start
848 up and shut down in tests, but runs in another process.  You want to test
849 interaction with that server, and whenever the interaction fails, you want to
850 see the client-side error *and* the logs from the server-side.  Here's how you
851 might do it::
852
853   from testtools import TestCase
854   from testtools.content import attach_file, Content
855   from testtools.content_type import UTF8_TEXT
856
857   from myproject import SomeServer
858
859   class SomeTestCase(TestCase):
860
861       def setUp(self):
862           super(SomeTestCase, self).setUp()
863           self.server = SomeServer()
864           self.server.start_up()
865           self.addCleanup(self.server.shut_down)
866           self.addCleanup(attach_file, self.server.logfile, self)
867
868       def attach_log_file(self):
869           self.addDetail(
870               'log-file',
871               Content(UTF8_TEXT,
872                       lambda: open(self.server.logfile, 'r').readlines()))
873
874       def test_a_thing(self):
875           self.assertEqual("cool", self.server.temperature)
876
877 This test will attach the log file of ``SomeServer`` to each test that is
878 run.  testtools will only display the log file for failing tests, so it's not
879 such a big deal.
880
881 If the act of adding at detail is expensive, you might want to use
882 addOnException_ so that you only do it when a test actually raises an
883 exception.
884
885
886 Controlling test execution
887 ==========================
888
889 .. _addCleanup:
890
891 addCleanup
892 ----------
893
894 ``TestCase.addCleanup`` is a robust way to arrange for a clean up function to
895 be called before ``tearDown``.  This is a powerful and simple alternative to
896 putting clean up logic in a try/finally block or ``tearDown`` method.  For
897 example::
898
899   def test_foo(self):
900       foo.lock()
901       self.addCleanup(foo.unlock)
902       ...
903
904 This is particularly useful if you have some sort of factory in your test::
905
906   def make_locked_foo(self):
907       foo = Foo()
908       foo.lock()
909       self.addCleanup(foo.unlock)
910       return foo
911
912   def test_frotz_a_foo(self):
913       foo = self.make_locked_foo()
914       foo.frotz()
915       self.assertEqual(foo.frotz_count, 1)
916
917 Any extra arguments or keyword arguments passed to ``addCleanup`` are passed
918 to the callable at cleanup time.
919
920 Cleanups can also report multiple errors, if appropriate by wrapping them in
921 a ``testtools.MultipleExceptions`` object::
922
923   raise MultipleExceptions(exc_info1, exc_info2)
924
925
926 Fixtures
927 --------
928
929 Tests often depend on a system being set up in a certain way, or having
930 certain resources available to them.  Perhaps a test needs a connection to the
931 database or access to a running external server.
932
933 One common way of doing this is to do::
934
935   class SomeTest(TestCase):
936       def setUp(self):
937           super(SomeTest, self).setUp()
938           self.server = Server()
939           self.server.setUp()
940           self.addCleanup(self.server.tearDown)
941
942 testtools provides a more convenient, declarative way to do the same thing::
943
944   class SomeTest(TestCase):
945       def setUp(self):
946           super(SomeTest, self).setUp()
947           self.server = self.useFixture(Server())
948
949 ``useFixture(fixture)`` calls ``setUp`` on the fixture, schedules a clean up
950 to clean it up, and schedules a clean up to attach all details_ held by the
951 fixture to the test case.  The fixture object must meet the
952 ``fixtures.Fixture`` protocol (version 0.3.4 or newer, see fixtures_).
953
954 If you have anything beyond the most simple test set up, we recommend that
955 you put this set up into a ``Fixture`` class.  Once there, the fixture can be
956 easily re-used by other tests and can be combined with other fixtures to make
957 more complex resources.
958
959
960 Skipping tests
961 --------------
962
963 Many reasons exist to skip a test: a dependency might be missing; a test might
964 be too expensive and thus should not berun while on battery power; or perhaps
965 the test is testing an incomplete feature.
966
967 ``TestCase.skipTest`` is a simple way to have a test stop running and be
968 reported as a skipped test, rather than a success, error or failure.  For
969 example::
970
971   def test_make_symlink(self):
972       symlink = getattr(os, 'symlink', None)
973       if symlink is None:
974           self.skipTest("No symlink support")
975       symlink(whatever, something_else)
976
977 Using ``skipTest`` means that you can make decisions about what tests to run
978 as late as possible, and close to the actual tests.  Without it, you might be
979 forced to use convoluted logic during test loading, which is a bit of a mess.
980
981
982 Legacy skip support
983 ~~~~~~~~~~~~~~~~~~~
984
985 If you are using this feature when running your test suite with a legacy
986 ``TestResult`` object that is missing the ``addSkip`` method, then the
987 ``addError`` method will be invoked instead.  If you are using a test result
988 from testtools, you do not have to worry about this.
989
990 In older versions of testtools, ``skipTest`` was known as ``skip``. Since
991 Python 2.7 added ``skipTest`` support, the ``skip`` name is now deprecated.
992 No warning is emitted yet – some time in the future we may do so.
993
994
995 addOnException
996 --------------
997
998 Sometimes, you might wish to do something only when a test fails.  Perhaps you
999 need to run expensive diagnostic routines or some such.
1000 ``TestCase.addOnException`` allows you to easily do just this.  For example::
1001
1002   class SomeTest(TestCase):
1003       def setUp(self):
1004           super(SomeTest, self).setUp()
1005           self.server = self.useFixture(SomeServer())
1006           self.addOnException(self.attach_server_diagnostics)
1007
1008       def attach_server_diagnostics(self, exc_info):
1009           self.server.prep_for_diagnostics() # Expensive!
1010           self.addDetail('server-diagnostics', self.server.get_diagnostics)
1011
1012       def test_a_thing(self):
1013           self.assertEqual('cheese', 'chalk')
1014
1015 In this example, ``attach_server_diagnostics`` will only be called when a test
1016 fails.  It is given the exc_info tuple of the error raised by the test, just
1017 in case it is needed.
1018
1019
1020 Twisted support
1021 ---------------
1022
1023 testtools provides *highly experimental* support for running Twisted tests –
1024 tests that return a Deferred_ and rely on the Twisted reactor.  You should not
1025 use this feature right now.  We reserve the right to change the API and
1026 behaviour without telling you first.
1027
1028 However, if you are going to, here's how you do it::
1029
1030   from testtools import TestCase
1031   from testtools.deferredruntest import AsynchronousDeferredRunTest
1032
1033   class MyTwistedTests(TestCase):
1034
1035       run_tests_with = AsynchronousDeferredRunTest
1036
1037       def test_foo(self):
1038           # ...
1039           return d
1040
1041 In particular, note that you do *not* have to use a special base ``TestCase``
1042 in order to run Twisted tests.
1043
1044 You can also run individual tests within a test case class using the Twisted
1045 test runner::
1046
1047    class MyTestsSomeOfWhichAreTwisted(TestCase):
1048
1049        def test_normal(self):
1050            pass
1051
1052        @run_test_with(AsynchronousDeferredRunTest)
1053        def test_twisted(self):
1054            # ...
1055            return d
1056
1057 Here are some tips for converting your Trial tests into testtools tests.
1058
1059 * Use the ``AsynchronousDeferredRunTest`` runner
1060 * Make sure to upcall to ``setUp`` and ``tearDown``
1061 * Don't use ``setUpClass`` or ``tearDownClass``
1062 * Don't expect setting .todo, .timeout or .skip attributes to do anything
1063 * ``flushLoggedErrors`` is ``testtools.deferredruntest.flush_logged_errors``
1064 * ``assertFailure`` is ``testtools.deferredruntest.assert_fails_with``
1065 * Trial spins the reactor a couple of times before cleaning it up,
1066   ``AsynchronousDeferredRunTest`` does not.  If you rely on this behavior, use
1067   ``AsynchronousDeferredRunTestForBrokenTwisted``.
1068
1069
1070 Test helpers
1071 ============
1072
1073 testtools comes with a few little things that make it a little bit easier to
1074 write tests.
1075
1076
1077 TestCase.patch
1078 --------------
1079
1080 ``patch`` is a convenient way to monkey-patch a Python object for the duration
1081 of your test.  It's especially useful for testing legacy code.  e.g.::
1082
1083   def test_foo(self):
1084       my_stream = StringIO()
1085       self.patch(sys, 'stderr', my_stream)
1086       run_some_code_that_prints_to_stderr()
1087       self.assertEqual('', my_stream.getvalue())
1088
1089 The call to ``patch`` above masks ``sys.stderr`` with ``my_stream`` so that
1090 anything printed to stderr will be captured in a StringIO variable that can be
1091 actually tested. Once the test is done, the real ``sys.stderr`` is restored to
1092 its rightful place.
1093
1094
1095 Creation methods
1096 ----------------
1097
1098 Often when writing unit tests, you want to create an object that is a
1099 completely normal instance of its type.  You don't want there to be anything
1100 special about its properties, because you are testing generic behaviour rather
1101 than specific conditions.
1102
1103 A lot of the time, test authors do this by making up silly strings and numbers
1104 and passing them to constructors (e.g. 42, 'foo', "bar" etc), and that's
1105 fine.  However, sometimes it's useful to be able to create arbitrary objects
1106 at will, without having to make up silly sample data.
1107
1108 To help with this, ``testtools.TestCase`` implements creation methods called
1109 ``getUniqueString`` and ``getUniqueInteger``.  They return strings and
1110 integers that are unique within the context of the test that can be used to
1111 assemble more complex objects.  Here's a basic example where
1112 ``getUniqueString`` is used instead of saying "foo" or "bar" or whatever::
1113
1114   class SomeTest(TestCase):
1115
1116       def test_full_name(self):
1117           first_name = self.getUniqueString()
1118           last_name = self.getUniqueString()
1119           p = Person(first_name, last_name)
1120           self.assertEqual(p.full_name, "%s %s" % (first_name, last_name))
1121
1122
1123 And here's how it could be used to make a complicated test::
1124
1125   class TestCoupleLogic(TestCase):
1126
1127       def make_arbitrary_person(self):
1128           return Person(self.getUniqueString(), self.getUniqueString())
1129
1130       def test_get_invitation(self):
1131           a = self.make_arbitrary_person()
1132           b = self.make_arbitrary_person()
1133           couple = Couple(a, b)
1134           event_name = self.getUniqueString()
1135           invitation = couple.get_invitation(event_name)
1136           self.assertEqual(
1137               invitation,
1138               "We invite %s and %s to %s" % (
1139                   a.full_name, b.full_name, event_name))
1140
1141 Essentially, creation methods like these are a way of reducing the number of
1142 assumptions in your tests and communicating to test readers that the exact
1143 details of certain variables don't actually matter.
1144
1145 See pages 419-423 of `xUnit Test Patterns`_ by Gerard Meszaros for a detailed
1146 discussion of creation methods.
1147
1148
1149 General helpers
1150 ===============
1151
1152 Conditional imports
1153 -------------------
1154
1155 Lots of the time we would like to conditionally import modules.  testtools
1156 needs to do this itself, and graciously extends the ability to its users.
1157
1158 Instead of::
1159
1160   try:
1161       from twisted.internet import defer
1162   except ImportError:
1163       defer = None
1164
1165 You can do::
1166
1167    defer = try_import('twisted.internet.defer')
1168
1169
1170 Instead of::
1171
1172   try:
1173       from StringIO import StringIO
1174   except ImportError:
1175       from io import StringIO
1176
1177 You can do::
1178
1179   StringIO = try_imports(['StringIO.StringIO', 'io.StringIO'])
1180
1181
1182 Safe attribute testing
1183 ----------------------
1184
1185 ``hasattr`` is broken_ on many versions of Python.  testtools provides
1186 ``safe_hasattr``, which can be used to safely test whether an object has a
1187 particular attribute.
1188
1189
1190 .. _testrepository: https://launchpad.net/testrepository
1191 .. _Trial: http://twistedmatrix.com/documents/current/core/howto/testing.html
1192 .. _nose: http://somethingaboutorange.com/mrl/projects/nose/
1193 .. _unittest2: http://pypi.python.org/pypi/unittest2
1194 .. _zope.testrunner: http://pypi.python.org/pypi/zope.testrunner/
1195 .. _xUnit test patterns: http://xunitpatterns.com/
1196 .. _fixtures: http://pypi.python.org/pypi/fixtures
1197 .. _unittest: http://docs.python.org/library/unittest.html
1198 .. _doctest: http://docs.python.org/library/doctest.html
1199 .. _Deferred: http://twistedmatrix.com/documents/current/core/howto/defer.html
1200 .. _discover: http://pypi.python.org/pypi/discover
1201 .. _`testtools API docs`: http://mumak.net/testtools/apidocs/
1202 .. _Distutils: http://docs.python.org/library/distutils.html
1203 .. _`setup configuration`: http://docs.python.org/distutils/configfile.html
1204 .. _broken: http://chipaca.com/post/3210673069/hasattr-17-less-harmful