feca41a4e69d5289981ff56ca6ab5dfd37df9325
[nivanova/samba-autobuild/.git] / lib / testtools / testtools / tests / test_matchers.py
1 # Copyright (c) 2008-2011 testtools developers. See LICENSE for details.
2
3 """Tests for matchers."""
4
5 import doctest
6 import re
7 import sys
8
9 from testtools import (
10     Matcher, # check that Matcher is exposed at the top level for docs.
11     TestCase,
12     )
13 from testtools.compat import (
14     StringIO,
15     _u,
16     )
17 from testtools.matchers import (
18     AfterPreprocessing,
19     AllMatch,
20     Annotate,
21     AnnotatedMismatch,
22     Contains,
23     Equals,
24     DocTestMatches,
25     DoesNotEndWith,
26     DoesNotStartWith,
27     EndsWith,
28     KeysEqual,
29     Is,
30     IsInstance,
31     LessThan,
32     GreaterThan,
33     MatchesAny,
34     MatchesAll,
35     MatchesException,
36     MatchesListwise,
37     MatchesRegex,
38     MatchesSetwise,
39     MatchesStructure,
40     Mismatch,
41     MismatchDecorator,
42     Not,
43     NotEquals,
44     Raises,
45     raises,
46     StartsWith,
47     )
48 from testtools.tests.helpers import FullStackRunTest
49
50 # Silence pyflakes.
51 Matcher
52
53
54 class TestMismatch(TestCase):
55
56     run_tests_with = FullStackRunTest
57
58     def test_constructor_arguments(self):
59         mismatch = Mismatch("some description", {'detail': "things"})
60         self.assertEqual("some description", mismatch.describe())
61         self.assertEqual({'detail': "things"}, mismatch.get_details())
62
63     def test_constructor_no_arguments(self):
64         mismatch = Mismatch()
65         self.assertThat(mismatch.describe,
66             Raises(MatchesException(NotImplementedError)))
67         self.assertEqual({}, mismatch.get_details())
68
69
70 class TestMatchersInterface(object):
71
72     run_tests_with = FullStackRunTest
73
74     def test_matches_match(self):
75         matcher = self.matches_matcher
76         matches = self.matches_matches
77         mismatches = self.matches_mismatches
78         for candidate in matches:
79             self.assertEqual(None, matcher.match(candidate))
80         for candidate in mismatches:
81             mismatch = matcher.match(candidate)
82             self.assertNotEqual(None, mismatch)
83             self.assertNotEqual(None, getattr(mismatch, 'describe', None))
84
85     def test__str__(self):
86         # [(expected, object to __str__)].
87         examples = self.str_examples
88         for expected, matcher in examples:
89             self.assertThat(matcher, DocTestMatches(expected))
90
91     def test_describe_difference(self):
92         # [(expected, matchee, matcher), ...]
93         examples = self.describe_examples
94         for difference, matchee, matcher in examples:
95             mismatch = matcher.match(matchee)
96             self.assertEqual(difference, mismatch.describe())
97
98     def test_mismatch_details(self):
99         # The mismatch object must provide get_details, which must return a
100         # dictionary mapping names to Content objects.
101         examples = self.describe_examples
102         for difference, matchee, matcher in examples:
103             mismatch = matcher.match(matchee)
104             details = mismatch.get_details()
105             self.assertEqual(dict(details), details)
106
107
108 class TestDocTestMatchesInterface(TestCase, TestMatchersInterface):
109
110     matches_matcher = DocTestMatches("Ran 1 test in ...s", doctest.ELLIPSIS)
111     matches_matches = ["Ran 1 test in 0.000s", "Ran 1 test in 1.234s"]
112     matches_mismatches = ["Ran 1 tests in 0.000s", "Ran 2 test in 0.000s"]
113
114     str_examples = [("DocTestMatches('Ran 1 test in ...s\\n')",
115         DocTestMatches("Ran 1 test in ...s")),
116         ("DocTestMatches('foo\\n', flags=8)", DocTestMatches("foo", flags=8)),
117         ]
118
119     describe_examples = [('Expected:\n    Ran 1 tests in ...s\nGot:\n'
120         '    Ran 1 test in 0.123s\n', "Ran 1 test in 0.123s",
121         DocTestMatches("Ran 1 tests in ...s", doctest.ELLIPSIS))]
122
123
124 class TestDocTestMatchesInterfaceUnicode(TestCase, TestMatchersInterface):
125
126     matches_matcher = DocTestMatches(_u("\xa7..."), doctest.ELLIPSIS)
127     matches_matches = [_u("\xa7"), _u("\xa7 more\n")]
128     matches_mismatches = ["\\xa7", _u("more \xa7"), _u("\n\xa7")]
129
130     str_examples = [("DocTestMatches(%r)" % (_u("\xa7\n"),),
131         DocTestMatches(_u("\xa7"))),
132         ]
133
134     describe_examples = [(
135         _u("Expected:\n    \xa7\nGot:\n    a\n"),
136         "a",
137         DocTestMatches(_u("\xa7"), doctest.ELLIPSIS))]
138
139
140 class TestDocTestMatchesSpecific(TestCase):
141
142     run_tests_with = FullStackRunTest
143
144     def test___init__simple(self):
145         matcher = DocTestMatches("foo")
146         self.assertEqual("foo\n", matcher.want)
147
148     def test___init__flags(self):
149         matcher = DocTestMatches("bar\n", doctest.ELLIPSIS)
150         self.assertEqual("bar\n", matcher.want)
151         self.assertEqual(doctest.ELLIPSIS, matcher.flags)
152
153
154 class TestEqualsInterface(TestCase, TestMatchersInterface):
155
156     matches_matcher = Equals(1)
157     matches_matches = [1]
158     matches_mismatches = [2]
159
160     str_examples = [("Equals(1)", Equals(1)), ("Equals('1')", Equals('1'))]
161
162     describe_examples = [("1 != 2", 2, Equals(1))]
163
164
165 class TestNotEqualsInterface(TestCase, TestMatchersInterface):
166
167     matches_matcher = NotEquals(1)
168     matches_matches = [2]
169     matches_mismatches = [1]
170
171     str_examples = [
172         ("NotEquals(1)", NotEquals(1)), ("NotEquals('1')", NotEquals('1'))]
173
174     describe_examples = [("1 == 1", 1, NotEquals(1))]
175
176
177 class TestIsInterface(TestCase, TestMatchersInterface):
178
179     foo = object()
180     bar = object()
181
182     matches_matcher = Is(foo)
183     matches_matches = [foo]
184     matches_mismatches = [bar, 1]
185
186     str_examples = [("Is(2)", Is(2))]
187
188     describe_examples = [("1 is not 2", 2, Is(1))]
189
190
191 class TestIsInstanceInterface(TestCase, TestMatchersInterface):
192
193     class Foo:pass
194
195     matches_matcher = IsInstance(Foo)
196     matches_matches = [Foo()]
197     matches_mismatches = [object(), 1, Foo]
198
199     str_examples = [
200             ("IsInstance(str)", IsInstance(str)),
201             ("IsInstance(str, int)", IsInstance(str, int)),
202             ]
203
204     describe_examples = [
205             ("'foo' is not an instance of int", 'foo', IsInstance(int)),
206             ("'foo' is not an instance of any of (int, type)", 'foo',
207              IsInstance(int, type)),
208             ]
209
210
211 class TestLessThanInterface(TestCase, TestMatchersInterface):
212
213     matches_matcher = LessThan(4)
214     matches_matches = [-5, 3]
215     matches_mismatches = [4, 5, 5000]
216
217     str_examples = [
218         ("LessThan(12)", LessThan(12)),
219         ]
220
221     describe_examples = [
222         ('4 is not > 5', 5, LessThan(4)),
223         ('4 is not > 4', 4, LessThan(4)),
224         ]
225
226
227 class TestGreaterThanInterface(TestCase, TestMatchersInterface):
228
229     matches_matcher = GreaterThan(4)
230     matches_matches = [5, 8]
231     matches_mismatches = [-2, 0, 4]
232
233     str_examples = [
234         ("GreaterThan(12)", GreaterThan(12)),
235         ]
236
237     describe_examples = [
238         ('5 is not < 4', 4, GreaterThan(5)),
239         ('4 is not < 4', 4, GreaterThan(4)),
240         ]
241
242
243 class TestContainsInterface(TestCase, TestMatchersInterface):
244
245     matches_matcher = Contains('foo')
246     matches_matches = ['foo', 'afoo', 'fooa']
247     matches_mismatches = ['f', 'fo', 'oo', 'faoo', 'foao']
248
249     str_examples = [
250         ("Contains(1)", Contains(1)),
251         ("Contains('foo')", Contains('foo')),
252         ]
253
254     describe_examples = [("1 not in 2", 2, Contains(1))]
255
256
257 def make_error(type, *args, **kwargs):
258     try:
259         raise type(*args, **kwargs)
260     except type:
261         return sys.exc_info()
262
263
264 class TestMatchesExceptionInstanceInterface(TestCase, TestMatchersInterface):
265
266     matches_matcher = MatchesException(ValueError("foo"))
267     error_foo = make_error(ValueError, 'foo')
268     error_bar = make_error(ValueError, 'bar')
269     error_base_foo = make_error(Exception, 'foo')
270     matches_matches = [error_foo]
271     matches_mismatches = [error_bar, error_base_foo]
272
273     str_examples = [
274         ("MatchesException(Exception('foo',))",
275          MatchesException(Exception('foo')))
276         ]
277     describe_examples = [
278         ("%r is not a %r" % (Exception, ValueError),
279          error_base_foo,
280          MatchesException(ValueError("foo"))),
281         ("ValueError('bar',) has different arguments to ValueError('foo',).",
282          error_bar,
283          MatchesException(ValueError("foo"))),
284         ]
285
286
287 class TestMatchesExceptionTypeInterface(TestCase, TestMatchersInterface):
288
289     matches_matcher = MatchesException(ValueError)
290     error_foo = make_error(ValueError, 'foo')
291     error_sub = make_error(UnicodeError, 'bar')
292     error_base_foo = make_error(Exception, 'foo')
293     matches_matches = [error_foo, error_sub]
294     matches_mismatches = [error_base_foo]
295
296     str_examples = [
297         ("MatchesException(%r)" % Exception,
298          MatchesException(Exception))
299         ]
300     describe_examples = [
301         ("%r is not a %r" % (Exception, ValueError),
302          error_base_foo,
303          MatchesException(ValueError)),
304         ]
305
306
307 class TestMatchesExceptionTypeReInterface(TestCase, TestMatchersInterface):
308
309     matches_matcher = MatchesException(ValueError, 'fo.')
310     error_foo = make_error(ValueError, 'foo')
311     error_sub = make_error(UnicodeError, 'foo')
312     error_bar = make_error(ValueError, 'bar')
313     matches_matches = [error_foo, error_sub]
314     matches_mismatches = [error_bar]
315
316     str_examples = [
317         ("MatchesException(%r)" % Exception,
318          MatchesException(Exception, 'fo.'))
319         ]
320     describe_examples = [
321         ("'bar' does not match /fo./",
322          error_bar, MatchesException(ValueError, "fo.")),
323         ]
324
325
326 class TestMatchesExceptionTypeMatcherInterface(TestCase, TestMatchersInterface):
327
328     matches_matcher = MatchesException(
329         ValueError, AfterPreprocessing(str, Equals('foo')))
330     error_foo = make_error(ValueError, 'foo')
331     error_sub = make_error(UnicodeError, 'foo')
332     error_bar = make_error(ValueError, 'bar')
333     matches_matches = [error_foo, error_sub]
334     matches_mismatches = [error_bar]
335
336     str_examples = [
337         ("MatchesException(%r)" % Exception,
338          MatchesException(Exception, Equals('foo')))
339         ]
340     describe_examples = [
341         ("5 != %r" % (error_bar[1],),
342          error_bar, MatchesException(ValueError, Equals(5))),
343         ]
344
345
346 class TestNotInterface(TestCase, TestMatchersInterface):
347
348     matches_matcher = Not(Equals(1))
349     matches_matches = [2]
350     matches_mismatches = [1]
351
352     str_examples = [
353         ("Not(Equals(1))", Not(Equals(1))),
354         ("Not(Equals('1'))", Not(Equals('1')))]
355
356     describe_examples = [('1 matches Equals(1)', 1, Not(Equals(1)))]
357
358
359 class TestMatchersAnyInterface(TestCase, TestMatchersInterface):
360
361     matches_matcher = MatchesAny(DocTestMatches("1"), DocTestMatches("2"))
362     matches_matches = ["1", "2"]
363     matches_mismatches = ["3"]
364
365     str_examples = [(
366         "MatchesAny(DocTestMatches('1\\n'), DocTestMatches('2\\n'))",
367         MatchesAny(DocTestMatches("1"), DocTestMatches("2"))),
368         ]
369
370     describe_examples = [("""Differences: [
371 Expected:
372     1
373 Got:
374     3
375
376 Expected:
377     2
378 Got:
379     3
380
381 ]""",
382         "3", MatchesAny(DocTestMatches("1"), DocTestMatches("2")))]
383
384
385 class TestMatchesAllInterface(TestCase, TestMatchersInterface):
386
387     matches_matcher = MatchesAll(NotEquals(1), NotEquals(2))
388     matches_matches = [3, 4]
389     matches_mismatches = [1, 2]
390
391     str_examples = [
392         ("MatchesAll(NotEquals(1), NotEquals(2))",
393          MatchesAll(NotEquals(1), NotEquals(2)))]
394
395     describe_examples = [("""Differences: [
396 1 == 1
397 ]""",
398                           1, MatchesAll(NotEquals(1), NotEquals(2)))]
399
400
401 class TestKeysEqual(TestCase, TestMatchersInterface):
402
403     matches_matcher = KeysEqual('foo', 'bar')
404     matches_matches = [
405         {'foo': 0, 'bar': 1},
406         ]
407     matches_mismatches = [
408         {},
409         {'foo': 0},
410         {'bar': 1},
411         {'foo': 0, 'bar': 1, 'baz': 2},
412         {'a': None, 'b': None, 'c': None},
413         ]
414
415     str_examples = [
416         ("KeysEqual('foo', 'bar')", KeysEqual('foo', 'bar')),
417         ]
418
419     describe_examples = [
420         ("['bar', 'foo'] does not match {'baz': 2, 'foo': 0, 'bar': 1}: "
421          "Keys not equal",
422          {'foo': 0, 'bar': 1, 'baz': 2}, KeysEqual('foo', 'bar')),
423         ]
424
425
426 class TestAnnotate(TestCase, TestMatchersInterface):
427
428     matches_matcher = Annotate("foo", Equals(1))
429     matches_matches = [1]
430     matches_mismatches = [2]
431
432     str_examples = [
433         ("Annotate('foo', Equals(1))", Annotate("foo", Equals(1)))]
434
435     describe_examples = [("1 != 2: foo", 2, Annotate('foo', Equals(1)))]
436
437     def test_if_message_no_message(self):
438         # Annotate.if_message returns the given matcher if there is no
439         # message.
440         matcher = Equals(1)
441         not_annotated = Annotate.if_message('', matcher)
442         self.assertIs(matcher, not_annotated)
443
444     def test_if_message_given_message(self):
445         # Annotate.if_message returns an annotated version of the matcher if a
446         # message is provided.
447         matcher = Equals(1)
448         expected = Annotate('foo', matcher)
449         annotated = Annotate.if_message('foo', matcher)
450         self.assertThat(
451             annotated,
452             MatchesStructure.fromExample(expected, 'annotation', 'matcher'))
453
454
455 class TestAnnotatedMismatch(TestCase):
456
457     run_tests_with = FullStackRunTest
458
459     def test_forwards_details(self):
460         x = Mismatch('description', {'foo': 'bar'})
461         annotated = AnnotatedMismatch("annotation", x)
462         self.assertEqual(x.get_details(), annotated.get_details())
463
464
465 class TestRaisesInterface(TestCase, TestMatchersInterface):
466
467     matches_matcher = Raises()
468     def boom():
469         raise Exception('foo')
470     matches_matches = [boom]
471     matches_mismatches = [lambda:None]
472
473     # Tricky to get function objects to render constantly, and the interfaces
474     # helper uses assertEqual rather than (for instance) DocTestMatches.
475     str_examples = []
476
477     describe_examples = []
478
479
480 class TestRaisesExceptionMatcherInterface(TestCase, TestMatchersInterface):
481
482     matches_matcher = Raises(
483         exception_matcher=MatchesException(Exception('foo')))
484     def boom_bar():
485         raise Exception('bar')
486     def boom_foo():
487         raise Exception('foo')
488     matches_matches = [boom_foo]
489     matches_mismatches = [lambda:None, boom_bar]
490
491     # Tricky to get function objects to render constantly, and the interfaces
492     # helper uses assertEqual rather than (for instance) DocTestMatches.
493     str_examples = []
494
495     describe_examples = []
496
497
498 class TestRaisesBaseTypes(TestCase):
499
500     run_tests_with = FullStackRunTest
501
502     def raiser(self):
503         raise KeyboardInterrupt('foo')
504
505     def test_KeyboardInterrupt_matched(self):
506         # When KeyboardInterrupt is matched, it is swallowed.
507         matcher = Raises(MatchesException(KeyboardInterrupt))
508         self.assertThat(self.raiser, matcher)
509
510     def test_KeyboardInterrupt_propogates(self):
511         # The default 'it raised' propogates KeyboardInterrupt.
512         match_keyb = Raises(MatchesException(KeyboardInterrupt))
513         def raise_keyb_from_match():
514             matcher = Raises()
515             matcher.match(self.raiser)
516         self.assertThat(raise_keyb_from_match, match_keyb)
517
518     def test_KeyboardInterrupt_match_Exception_propogates(self):
519         # If the raised exception isn't matched, and it is not a subclass of
520         # Exception, it is propogated.
521         match_keyb = Raises(MatchesException(KeyboardInterrupt))
522         def raise_keyb_from_match():
523             if sys.version_info > (2, 5):
524                 matcher = Raises(MatchesException(Exception))
525             else:
526                 # On Python 2.4 KeyboardInterrupt is a StandardError subclass
527                 # but should propogate from less generic exception matchers
528                 matcher = Raises(MatchesException(EnvironmentError))
529             matcher.match(self.raiser)
530         self.assertThat(raise_keyb_from_match, match_keyb)
531
532
533 class TestRaisesConvenience(TestCase):
534
535     run_tests_with = FullStackRunTest
536
537     def test_exc_type(self):
538         self.assertThat(lambda: 1/0, raises(ZeroDivisionError))
539
540     def test_exc_value(self):
541         e = RuntimeError("You lose!")
542         def raiser():
543             raise e
544         self.assertThat(raiser, raises(e))
545
546
547 class DoesNotStartWithTests(TestCase):
548
549     run_tests_with = FullStackRunTest
550
551     def test_describe(self):
552         mismatch = DoesNotStartWith("fo", "bo")
553         self.assertEqual("'fo' does not start with 'bo'.", mismatch.describe())
554
555
556 class StartsWithTests(TestCase):
557
558     run_tests_with = FullStackRunTest
559
560     def test_str(self):
561         matcher = StartsWith("bar")
562         self.assertEqual("Starts with 'bar'.", str(matcher))
563
564     def test_match(self):
565         matcher = StartsWith("bar")
566         self.assertIs(None, matcher.match("barf"))
567
568     def test_mismatch_returns_does_not_start_with(self):
569         matcher = StartsWith("bar")
570         self.assertIsInstance(matcher.match("foo"), DoesNotStartWith)
571
572     def test_mismatch_sets_matchee(self):
573         matcher = StartsWith("bar")
574         mismatch = matcher.match("foo")
575         self.assertEqual("foo", mismatch.matchee)
576
577     def test_mismatch_sets_expected(self):
578         matcher = StartsWith("bar")
579         mismatch = matcher.match("foo")
580         self.assertEqual("bar", mismatch.expected)
581
582
583 class DoesNotEndWithTests(TestCase):
584
585     run_tests_with = FullStackRunTest
586
587     def test_describe(self):
588         mismatch = DoesNotEndWith("fo", "bo")
589         self.assertEqual("'fo' does not end with 'bo'.", mismatch.describe())
590
591
592 class EndsWithTests(TestCase):
593
594     run_tests_with = FullStackRunTest
595
596     def test_str(self):
597         matcher = EndsWith("bar")
598         self.assertEqual("Ends with 'bar'.", str(matcher))
599
600     def test_match(self):
601         matcher = EndsWith("arf")
602         self.assertIs(None, matcher.match("barf"))
603
604     def test_mismatch_returns_does_not_end_with(self):
605         matcher = EndsWith("bar")
606         self.assertIsInstance(matcher.match("foo"), DoesNotEndWith)
607
608     def test_mismatch_sets_matchee(self):
609         matcher = EndsWith("bar")
610         mismatch = matcher.match("foo")
611         self.assertEqual("foo", mismatch.matchee)
612
613     def test_mismatch_sets_expected(self):
614         matcher = EndsWith("bar")
615         mismatch = matcher.match("foo")
616         self.assertEqual("bar", mismatch.expected)
617
618
619 def run_doctest(obj, name):
620     p = doctest.DocTestParser()
621     t = p.get_doctest(
622         obj.__doc__, sys.modules[obj.__module__].__dict__, name, '', 0)
623     r = doctest.DocTestRunner()
624     output = StringIO()
625     r.run(t, out=output.write)
626     return r.failures, output.getvalue()
627
628
629 class TestMatchesListwise(TestCase):
630
631     run_tests_with = FullStackRunTest
632
633     def test_docstring(self):
634         failure_count, output = run_doctest(
635             MatchesListwise, "MatchesListwise")
636         if failure_count:
637             self.fail("Doctest failed with %s" % output)
638
639
640 class TestMatchesStructure(TestCase, TestMatchersInterface):
641
642     class SimpleClass:
643         def __init__(self, x, y):
644             self.x = x
645             self.y = y
646
647     matches_matcher = MatchesStructure(x=Equals(1), y=Equals(2))
648     matches_matches = [SimpleClass(1, 2)]
649     matches_mismatches = [
650         SimpleClass(2, 2),
651         SimpleClass(1, 1),
652         SimpleClass(3, 3),
653         ]
654
655     str_examples = [
656         ("MatchesStructure(x=Equals(1))", MatchesStructure(x=Equals(1))),
657         ("MatchesStructure(y=Equals(2))", MatchesStructure(y=Equals(2))),
658         ("MatchesStructure(x=Equals(1), y=Equals(2))",
659          MatchesStructure(x=Equals(1), y=Equals(2))),
660         ]
661
662     describe_examples = [
663         ("""\
664 Differences: [
665 3 != 1: x
666 ]""", SimpleClass(1, 2), MatchesStructure(x=Equals(3), y=Equals(2))),
667         ("""\
668 Differences: [
669 3 != 2: y
670 ]""", SimpleClass(1, 2), MatchesStructure(x=Equals(1), y=Equals(3))),
671         ("""\
672 Differences: [
673 0 != 1: x
674 0 != 2: y
675 ]""", SimpleClass(1, 2), MatchesStructure(x=Equals(0), y=Equals(0))),
676         ]
677
678     def test_fromExample(self):
679         self.assertThat(
680             self.SimpleClass(1, 2),
681             MatchesStructure.fromExample(self.SimpleClass(1, 3), 'x'))
682
683     def test_byEquality(self):
684         self.assertThat(
685             self.SimpleClass(1, 2),
686             MatchesStructure.byEquality(x=1))
687
688     def test_withStructure(self):
689         self.assertThat(
690             self.SimpleClass(1, 2),
691             MatchesStructure.byMatcher(LessThan, x=2))
692
693     def test_update(self):
694         self.assertThat(
695             self.SimpleClass(1, 2),
696             MatchesStructure(x=NotEquals(1)).update(x=Equals(1)))
697
698     def test_update_none(self):
699         self.assertThat(
700             self.SimpleClass(1, 2),
701             MatchesStructure(x=Equals(1), z=NotEquals(42)).update(
702                 z=None))
703
704
705 class TestMatchesRegex(TestCase, TestMatchersInterface):
706
707     matches_matcher = MatchesRegex('a|b')
708     matches_matches = ['a', 'b']
709     matches_mismatches = ['c']
710
711     str_examples = [
712         ("MatchesRegex('a|b')", MatchesRegex('a|b')),
713         ("MatchesRegex('a|b', re.M)", MatchesRegex('a|b', re.M)),
714         ("MatchesRegex('a|b', re.I|re.M)", MatchesRegex('a|b', re.I|re.M)),
715         ]
716
717     describe_examples = [
718         ("'c' does not match /a|b/", 'c', MatchesRegex('a|b')),
719         ("'c' does not match /a\d/", 'c', MatchesRegex(r'a\d')),
720         ]
721
722
723 class TestMatchesSetwise(TestCase):
724
725     run_tests_with = FullStackRunTest
726
727     def assertMismatchWithDescriptionMatching(self, value, matcher,
728                                               description_matcher):
729         mismatch = matcher.match(value)
730         if mismatch is None:
731             self.fail("%s matched %s" % (matcher, value))
732         actual_description = mismatch.describe()
733         self.assertThat(
734             actual_description,
735             Annotate(
736                 "%s matching %s" % (matcher, value),
737                 description_matcher))
738
739     def test_matches(self):
740         self.assertIs(
741             None, MatchesSetwise(Equals(1), Equals(2)).match([2, 1]))
742
743     def test_mismatches(self):
744         self.assertMismatchWithDescriptionMatching(
745             [2, 3], MatchesSetwise(Equals(1), Equals(2)),
746             MatchesRegex('.*There was 1 mismatch$', re.S))
747
748     def test_too_many_matchers(self):
749         self.assertMismatchWithDescriptionMatching(
750             [2, 3], MatchesSetwise(Equals(1), Equals(2), Equals(3)),
751             Equals('There was 1 matcher left over: Equals(1)'))
752
753     def test_too_many_values(self):
754         self.assertMismatchWithDescriptionMatching(
755             [1, 2, 3], MatchesSetwise(Equals(1), Equals(2)),
756             Equals('There was 1 value left over: [3]'))
757
758     def test_two_too_many_matchers(self):
759         self.assertMismatchWithDescriptionMatching(
760             [3], MatchesSetwise(Equals(1), Equals(2), Equals(3)),
761             MatchesRegex(
762                 'There were 2 matchers left over: Equals\([12]\), '
763                 'Equals\([12]\)'))
764
765     def test_two_too_many_values(self):
766         self.assertMismatchWithDescriptionMatching(
767             [1, 2, 3, 4], MatchesSetwise(Equals(1), Equals(2)),
768             MatchesRegex(
769                 'There were 2 values left over: \[[34], [34]\]'))
770
771     def test_mismatch_and_too_many_matchers(self):
772         self.assertMismatchWithDescriptionMatching(
773             [2, 3], MatchesSetwise(Equals(0), Equals(1), Equals(2)),
774             MatchesRegex(
775                 '.*There was 1 mismatch and 1 extra matcher: Equals\([01]\)',
776                 re.S))
777
778     def test_mismatch_and_too_many_values(self):
779         self.assertMismatchWithDescriptionMatching(
780             [2, 3, 4], MatchesSetwise(Equals(1), Equals(2)),
781             MatchesRegex(
782                 '.*There was 1 mismatch and 1 extra value: \[[34]\]',
783                 re.S))
784
785     def test_mismatch_and_two_too_many_matchers(self):
786         self.assertMismatchWithDescriptionMatching(
787             [3, 4], MatchesSetwise(
788                 Equals(0), Equals(1), Equals(2), Equals(3)),
789             MatchesRegex(
790                 '.*There was 1 mismatch and 2 extra matchers: '
791                 'Equals\([012]\), Equals\([012]\)', re.S))
792
793     def test_mismatch_and_two_too_many_values(self):
794         self.assertMismatchWithDescriptionMatching(
795             [2, 3, 4, 5], MatchesSetwise(Equals(1), Equals(2)),
796             MatchesRegex(
797                 '.*There was 1 mismatch and 2 extra values: \[[145], [145]\]',
798                 re.S))
799
800
801 class TestAfterPreprocessing(TestCase, TestMatchersInterface):
802
803     def parity(x):
804         return x % 2
805
806     matches_matcher = AfterPreprocessing(parity, Equals(1))
807     matches_matches = [3, 5]
808     matches_mismatches = [2]
809
810     str_examples = [
811         ("AfterPreprocessing(<function parity>, Equals(1))",
812          AfterPreprocessing(parity, Equals(1))),
813         ]
814
815     describe_examples = [
816         ("1 != 0: after <function parity> on 2", 2,
817          AfterPreprocessing(parity, Equals(1))),
818         ("1 != 0", 2,
819          AfterPreprocessing(parity, Equals(1), annotate=False)),
820         ]
821
822
823 class TestMismatchDecorator(TestCase):
824
825     run_tests_with = FullStackRunTest
826
827     def test_forwards_description(self):
828         x = Mismatch("description", {'foo': 'bar'})
829         decorated = MismatchDecorator(x)
830         self.assertEqual(x.describe(), decorated.describe())
831
832     def test_forwards_details(self):
833         x = Mismatch("description", {'foo': 'bar'})
834         decorated = MismatchDecorator(x)
835         self.assertEqual(x.get_details(), decorated.get_details())
836
837     def test_repr(self):
838         x = Mismatch("description", {'foo': 'bar'})
839         decorated = MismatchDecorator(x)
840         self.assertEqual(
841             '<testtools.matchers.MismatchDecorator(%r)>' % (x,),
842             repr(decorated))
843
844
845 class TestAllMatch(TestCase, TestMatchersInterface):
846
847     matches_matcher = AllMatch(LessThan(10))
848     matches_matches = [
849         [9, 9, 9],
850         (9, 9),
851         iter([9, 9, 9, 9, 9]),
852         ]
853     matches_mismatches = [
854         [11, 9, 9],
855         iter([9, 12, 9, 11]),
856         ]
857
858     str_examples = [
859         ("AllMatch(LessThan(12))", AllMatch(LessThan(12))),
860         ]
861
862     describe_examples = [
863         ('Differences: [\n'
864          '10 is not > 11\n'
865          '10 is not > 10\n'
866          ']',
867          [11, 9, 10],
868          AllMatch(LessThan(10))),
869         ]
870
871
872 def test_suite():
873     from unittest import TestLoader
874     return TestLoader().loadTestsFromName(__name__)