-
Notifications
You must be signed in to change notification settings - Fork 86
/
test_testcase.py
2056 lines (1753 loc) · 71.3 KB
/
test_testcase.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2008-2015 testtools developers. See LICENSE for details.
"""Tests for extensions to the base test library."""
from doctest import ELLIPSIS
from pprint import pformat
import sys
import _thread
import unittest
from testtools import (
DecorateTestCaseResult,
ErrorHolder,
MultipleExceptions,
PlaceHolder,
TestCase,
clone_test_with_new_id,
content,
skip,
skipIf,
skipUnless,
testcase,
)
from testtools.compat import (
_b,
)
from testtools.content import (
text_content,
TracebackContent,
)
from testtools.matchers import (
Annotate,
ContainsAll,
DocTestMatches,
Equals,
HasLength,
MatchesException,
Raises,
)
from testtools.testcase import (
attr,
Nullary,
WithAttributes,
TestSkipped,
)
from testtools.testresult.doubles import (
Python26TestResult,
Python27TestResult,
ExtendedTestResult,
)
from testtools.tests.helpers import (
an_exc_info,
AsText,
FullStackRunTest,
LoggingResult,
MatchesEvents,
raise_,
)
from testtools.tests.samplecases import (
deterministic_sample_cases_scenarios,
make_case_for_behavior_scenario,
make_test_case,
nondeterministic_sample_cases_scenarios,
)
class TestPlaceHolder(TestCase):
run_test_with = FullStackRunTest
def makePlaceHolder(self, test_id="foo", short_description=None):
return PlaceHolder(test_id, short_description)
def test_id_comes_from_constructor(self):
# The id() of a PlaceHolder is whatever you pass into the constructor.
test = PlaceHolder("test id")
self.assertEqual("test id", test.id())
def test_shortDescription_is_id(self):
# The shortDescription() of a PlaceHolder is the id, by default.
test = PlaceHolder("test id")
self.assertEqual(test.id(), test.shortDescription())
def test_shortDescription_specified(self):
# If a shortDescription is provided to the constructor, then
# shortDescription() returns that instead.
test = PlaceHolder("test id", "description")
self.assertEqual("description", test.shortDescription())
def test_testcase_is_hashable(self):
test = hash(self)
self.assertEqual(unittest.TestCase.__hash__(self), test)
def test_testcase_equals_edgecase(self):
# Not all python objects have a __dict__ attribute
self.assertFalse(self == _thread.RLock())
def test_repr_just_id(self):
# repr(placeholder) shows you how the object was constructed.
test = PlaceHolder("test id")
self.assertEqual(
"<testtools.testcase.PlaceHolder('addSuccess', %s, {})>" % repr(
test.id()), repr(test))
def test_repr_with_description(self):
# repr(placeholder) shows you how the object was constructed.
test = PlaceHolder("test id", "description")
self.assertEqual(
"<testtools.testcase.PlaceHolder('addSuccess', {!r}, {{}}, {!r})>".format(
test.id(), test.shortDescription()), repr(test))
def test_repr_custom_outcome(self):
test = PlaceHolder("test id", outcome='addSkip')
self.assertEqual(
"<testtools.testcase.PlaceHolder('addSkip', %r, {})>" % (
test.id()), repr(test))
def test_counts_as_one_test(self):
# A placeholder test counts as one test.
test = self.makePlaceHolder()
self.assertEqual(1, test.countTestCases())
def test_str_is_id(self):
# str(placeholder) is always the id(). We are not barbarians.
test = self.makePlaceHolder()
self.assertEqual(test.id(), str(test))
def test_runs_as_success(self):
# When run, a PlaceHolder test records a success.
test = self.makePlaceHolder()
log = []
test.run(LoggingResult(log))
self.assertEqual(
[('tags', set(), set()), ('startTest', test), ('addSuccess', test),
('stopTest', test), ('tags', set(), set()),],
log)
def test_supplies_details(self):
details = {'quux':None}
test = PlaceHolder('foo', details=details)
result = ExtendedTestResult()
test.run(result)
self.assertEqual(
[('tags', set(), set()),
('startTest', test),
('addSuccess', test, details),
('stopTest', test),
('tags', set(), set()),
],
result._events)
def test_supplies_timestamps(self):
test = PlaceHolder('foo', details={}, timestamps=["A", "B"])
result = ExtendedTestResult()
test.run(result)
self.assertEqual(
[('time', "A"),
('tags', set(), set()),
('startTest', test),
('time', "B"),
('addSuccess', test),
('stopTest', test),
('tags', set(), set()),
],
result._events)
def test_call_is_run(self):
# A PlaceHolder can be called, in which case it behaves like run.
test = self.makePlaceHolder()
run_log = []
test.run(LoggingResult(run_log))
call_log = []
test(LoggingResult(call_log))
self.assertEqual(run_log, call_log)
def test_runs_without_result(self):
# A PlaceHolder can be run without a result, in which case there's no
# way to actually get at the result.
self.makePlaceHolder().run()
def test_debug(self):
# A PlaceHolder can be debugged.
self.makePlaceHolder().debug()
def test_supports_tags(self):
result = ExtendedTestResult()
tags = {'foo', 'bar'}
case = PlaceHolder("foo", tags=tags)
case.run(result)
self.assertEqual([
('tags', tags, set()),
('startTest', case),
('addSuccess', case),
('stopTest', case),
('tags', set(), tags),
], result._events)
class TestErrorHolder(TestCase):
# Note that these tests exist because ErrorHolder exists - it could be
# deprecated and dropped at this point.
run_test_with = FullStackRunTest
def makeException(self):
try:
raise RuntimeError("danger danger")
except BaseException:
return sys.exc_info()
def makePlaceHolder(self, test_id="foo", error=None,
short_description=None):
if error is None:
error = self.makeException()
return ErrorHolder(test_id, error, short_description)
def test_id_comes_from_constructor(self):
# The id() of a PlaceHolder is whatever you pass into the constructor.
test = ErrorHolder("test id", self.makeException())
self.assertEqual("test id", test.id())
def test_shortDescription_is_id(self):
# The shortDescription() of a PlaceHolder is the id, by default.
test = ErrorHolder("test id", self.makeException())
self.assertEqual(test.id(), test.shortDescription())
def test_shortDescription_specified(self):
# If a shortDescription is provided to the constructor, then
# shortDescription() returns that instead.
test = ErrorHolder("test id", self.makeException(), "description")
self.assertEqual("description", test.shortDescription())
def test_counts_as_one_test(self):
# A placeholder test counts as one test.
test = self.makePlaceHolder()
self.assertEqual(1, test.countTestCases())
def test_str_is_id(self):
# str(placeholder) is always the id(). We are not barbarians.
test = self.makePlaceHolder()
self.assertEqual(test.id(), str(test))
def test_runs_as_error(self):
# When run, an ErrorHolder test records an error.
error = self.makeException()
test = self.makePlaceHolder(error=error)
result = ExtendedTestResult()
log = result._events
test.run(result)
self.assertEqual(
[('tags', set(), set()),
('startTest', test),
('addError', test, test._details),
('stopTest', test),
('tags', set(), set())], log)
def test_call_is_run(self):
# A PlaceHolder can be called, in which case it behaves like run.
test = self.makePlaceHolder()
run_log = []
test.run(LoggingResult(run_log))
call_log = []
test(LoggingResult(call_log))
self.assertEqual(run_log, call_log)
def test_runs_without_result(self):
# A PlaceHolder can be run without a result, in which case there's no
# way to actually get at the result.
self.makePlaceHolder().run()
def test_debug(self):
# A PlaceHolder can be debugged.
self.makePlaceHolder().debug()
class TestEquality(TestCase):
"""Test ``TestCase``'s equality implementation."""
run_test_with = FullStackRunTest
def test_identicalIsEqual(self):
# TestCase's are equal if they are identical.
self.assertEqual(self, self)
def test_nonIdenticalInUnequal(self):
# TestCase's are not equal if they are not identical.
self.assertNotEqual(TestCase(methodName='run'),
TestCase(methodName='skip'))
class TestAssertions(TestCase):
"""Test assertions in TestCase."""
run_test_with = FullStackRunTest
def raiseError(self, exceptionFactory, *args, **kwargs):
raise exceptionFactory(*args, **kwargs)
def test_formatTypes_single(self):
# Given a single class, _formatTypes returns the name.
class Foo:
pass
self.assertEqual('Foo', self._formatTypes(Foo))
def test_formatTypes_multiple(self):
# Given multiple types, _formatTypes returns the names joined by
# commas.
class Foo:
pass
class Bar:
pass
self.assertEqual('Foo, Bar', self._formatTypes([Foo, Bar]))
def test_assertRaises(self):
# assertRaises asserts that a callable raises a particular exception.
self.assertRaises(RuntimeError, self.raiseError, RuntimeError)
def test_assertRaises_exception_w_metaclass(self):
# assertRaises works when called for exceptions with custom metaclasses
class MyExMeta(type):
def __init__(cls, name, bases, dct):
""" Do some dummy metaclass stuff """
dct.update({'answer': 42})
type.__init__(cls, name, bases, dct)
class MyEx(Exception):
__metaclass__ = MyExMeta
self.assertRaises(MyEx, self.raiseError, MyEx)
def test_assertRaises_fails_when_no_error_raised(self):
# assertRaises raises self.failureException when it's passed a
# callable that raises no error.
ret = ('orange', 42)
self.assertFails(
"<function ...<lambda> at ...> returned ('orange', 42)",
self.assertRaises, RuntimeError, lambda: ret)
def test_assertRaises_fails_when_different_error_raised(self):
# assertRaises re-raises an exception that it didn't expect.
self.assertThat(lambda: self.assertRaises(RuntimeError,
self.raiseError, ZeroDivisionError),
Raises(MatchesException(ZeroDivisionError)))
def test_assertRaises_returns_the_raised_exception(self):
# assertRaises returns the exception object that was raised. This is
# useful for testing that exceptions have the right message.
# This contraption stores the raised exception, so we can compare it
# to the return value of assertRaises.
raisedExceptions = []
def raiseError():
try:
raise RuntimeError('Deliberate error')
except RuntimeError:
raisedExceptions.append(sys.exc_info()[1])
raise
exception = self.assertRaises(RuntimeError, raiseError)
self.assertEqual(1, len(raisedExceptions))
self.assertIs(
exception,
raisedExceptions[0],
'{!r} is not {!r}'.format(exception, raisedExceptions[0])
)
def test_assertRaises_with_multiple_exceptions(self):
# assertRaises((ExceptionOne, ExceptionTwo), function) asserts that
# function raises one of ExceptionTwo or ExceptionOne.
expectedExceptions = (RuntimeError, ZeroDivisionError)
self.assertRaises(
expectedExceptions, self.raiseError, expectedExceptions[0])
self.assertRaises(
expectedExceptions, self.raiseError, expectedExceptions[1])
def test_assertRaises_with_multiple_exceptions_failure_mode(self):
# If assertRaises is called expecting one of a group of exceptions and
# a callable that doesn't raise an exception, then fail with an
# appropriate error message.
expectedExceptions = (RuntimeError, ZeroDivisionError)
self.assertRaises(
self.failureException,
self.assertRaises, expectedExceptions, lambda: None)
self.assertFails('<function ...<lambda> at ...> returned None',
self.assertRaises, expectedExceptions, lambda: None)
def test_assertRaises_function_repr_in_exception(self):
# When assertRaises fails, it includes the repr of the invoked
# function in the error message, so it's easy to locate the problem.
def foo():
"""An arbitrary function."""
pass
self.assertThat(
lambda: self.assertRaises(Exception, foo),
Raises(
MatchesException(self.failureException, f'.*{foo!r}.*')))
def test_assertRaisesRegex(self):
# assertRaisesRegex asserts that function raises particular exception
# with particular message.
self.assertRaisesRegex(RuntimeError, r"M\w*e", self.raiseError,
RuntimeError, "Message")
def test_assertRaisesRegex_wrong_error_type(self):
# If function raises an exception of unexpected type,
# assertRaisesRegex re-raises it.
self.assertRaises(ValueError, self.assertRaisesRegex, RuntimeError,
r"M\w*e", self.raiseError, ValueError, "Message")
def test_assertRaisesRegex_wrong_message(self):
# If function raises an exception with unexpected message
# assertRaisesRegex fails.
self.assertFails(
'"Expected" does not match "Observed"',
self.assertRaisesRegex, RuntimeError, "Expected",
self.raiseError, RuntimeError, "Observed")
def assertFails(self, message, function, *args, **kwargs):
"""Assert that function raises a failure with the given message."""
failure = self.assertRaises(
self.failureException, function, *args, **kwargs)
self.assertThat(failure, DocTestMatches(message, ELLIPSIS))
def test_assertIn_success(self):
# assertIn(needle, haystack) asserts that 'needle' is in 'haystack'.
self.assertIn(3, range(10))
self.assertIn('foo', 'foo bar baz')
self.assertIn('foo', 'foo bar baz'.split())
def test_assertIn_failure(self):
# assertIn(needle, haystack) fails the test when 'needle' is not in
# 'haystack'.
self.assertFails('3 not in [0, 1, 2]', self.assertIn, 3, [0, 1, 2])
self.assertFails(
'{!r} not in {!r}'.format('qux', 'foo bar baz'),
self.assertIn, 'qux', 'foo bar baz')
def test_assertIn_failure_with_message(self):
# assertIn(needle, haystack) fails the test when 'needle' is not in
# 'haystack'.
self.assertFails('3 not in [0, 1, 2]: foo bar', self.assertIn, 3,
[0, 1, 2], 'foo bar')
self.assertFails(
'{!r} not in {!r}: foo bar'.format('qux', 'foo bar baz'),
self.assertIn, 'qux', 'foo bar baz', 'foo bar')
def test_assertNotIn_success(self):
# assertNotIn(needle, haystack) asserts that 'needle' is not in
# 'haystack'.
self.assertNotIn(3, [0, 1, 2])
self.assertNotIn('qux', 'foo bar baz')
def test_assertNotIn_failure(self):
# assertNotIn(needle, haystack) fails the test when 'needle' is in
# 'haystack'.
self.assertFails('[1, 2, 3] matches Contains(3)', self.assertNotIn,
3, [1, 2, 3])
self.assertFails(
"'foo bar baz' matches Contains('foo')",
self.assertNotIn, 'foo', 'foo bar baz')
def test_assertNotIn_failure_with_message(self):
# assertNotIn(needle, haystack) fails the test when 'needle' is in
# 'haystack'.
self.assertFails('[1, 2, 3] matches Contains(3): foo bar', self.assertNotIn,
3, [1, 2, 3], 'foo bar')
self.assertFails(
"'foo bar baz' matches Contains('foo'): foo bar",
self.assertNotIn, 'foo', 'foo bar baz', "foo bar")
def test_assertIsInstance(self):
# assertIsInstance asserts that an object is an instance of a class.
class Foo:
"""Simple class for testing assertIsInstance."""
foo = Foo()
self.assertIsInstance(foo, Foo)
def test_assertIsInstance_multiple_classes(self):
# assertIsInstance asserts that an object is an instance of one of a
# group of classes.
class Foo:
"""Simple class for testing assertIsInstance."""
class Bar:
"""Another simple class for testing assertIsInstance."""
foo = Foo()
self.assertIsInstance(foo, (Foo, Bar))
self.assertIsInstance(Bar(), (Foo, Bar))
def test_assertIsInstance_failure(self):
# assertIsInstance(obj, klass) fails the test when obj is not an
# instance of klass.
class Foo:
"""Simple class for testing assertIsInstance."""
self.assertFails(
"'42' is not an instance of %s" % self._formatTypes(Foo),
self.assertIsInstance, 42, Foo)
def test_assertIsInstance_failure_multiple_classes(self):
# assertIsInstance(obj, (klass1, klass2)) fails the test when obj is
# not an instance of klass1 or klass2.
class Foo:
"""Simple class for testing assertIsInstance."""
class Bar:
"""Another simple class for testing assertIsInstance."""
self.assertFails(
"'42' is not an instance of any of (%s)" % self._formatTypes([Foo, Bar]),
self.assertIsInstance, 42, (Foo, Bar))
def test_assertIsInstance_overridden_message(self):
# assertIsInstance(obj, klass, msg) permits a custom message.
self.assertFails("'42' is not an instance of str: foo",
self.assertIsInstance, 42, str, "foo")
def test_assertIs(self):
# assertIs asserts that an object is identical to another object.
self.assertIsNone(None)
some_list = [42]
self.assertIs(some_list, some_list)
some_object = object()
self.assertIs(some_object, some_object)
def test_assertIs_fails(self):
# assertIs raises assertion errors if one object is not identical to
# another.
self.assertFails('42 is not None', self.assertIs, None, 42)
self.assertFails('[42] is not [42]', self.assertIs, [42], [42])
def test_assertIs_fails_with_message(self):
# assertIs raises assertion errors if one object is not identical to
# another, and includes a user-supplied message, if it's provided.
self.assertFails(
'42 is not None: foo bar', self.assertIs, None, 42, 'foo bar')
def test_assertIsNot(self):
# assertIsNot asserts that an object is not identical to another
# object.
self.assertIsNot(None, 42)
self.assertIsNot([42], [42])
self.assertIsNot(object(), object())
def test_assertIsNot_fails(self):
# assertIsNot raises assertion errors if one object is identical to
# another.
self.assertFails('None matches Is(None)', self.assertIsNot, None, None)
some_list = [42]
self.assertFails(
'[42] matches Is([42])', self.assertIsNot, some_list, some_list)
def test_assertIsNot_fails_with_message(self):
# assertIsNot raises assertion errors if one object is identical to
# another, and includes a user-supplied message if it's provided.
self.assertFails(
'None matches Is(None): foo bar', self.assertIsNot, None, None,
"foo bar")
def test_assertThat_matches_clean(self):
class Matcher:
def match(self, foo):
return None
self.assertThat("foo", Matcher())
def test_assertThat_mismatch_raises_description(self):
calls = []
class Mismatch:
def __init__(self, thing):
self.thing = thing
def describe(self):
calls.append(('describe_diff', self.thing))
return "object is not a thing"
def get_details(self):
return {}
class Matcher:
def match(self, thing):
calls.append(('match', thing))
return Mismatch(thing)
def __str__(self):
calls.append(('__str__',))
return "a description"
class Test(TestCase):
def test(self):
self.assertThat("foo", Matcher())
result = Test("test").run()
self.assertEqual([
('match', "foo"),
('describe_diff', "foo"),
], calls)
self.assertFalse(result.wasSuccessful())
def test_assertThat_output(self):
matchee = 'foo'
matcher = Equals('bar')
expected = matcher.match(matchee).describe()
self.assertFails(expected, self.assertThat, matchee, matcher)
def test_assertThat_message_is_annotated(self):
matchee = 'foo'
matcher = Equals('bar')
expected = Annotate('woo', matcher).match(matchee).describe()
self.assertFails(expected, self.assertThat, matchee, matcher, 'woo')
def test_assertThat_verbose_output(self):
matchee = 'foo'
matcher = Equals('bar')
expected = (
'Match failed. Matchee: %r\n'
'Matcher: %s\n'
'Difference: %s\n' % (
matchee,
matcher,
matcher.match(matchee).describe(),
))
self.assertFails(
expected, self.assertThat, matchee, matcher, verbose=True)
def test_expectThat_matches_clean(self):
class Matcher:
def match(self, foo):
return None
self.expectThat("foo", Matcher())
def test_expectThat_mismatch_fails_test(self):
class Test(TestCase):
def test(self):
self.expectThat("foo", Equals("bar"))
result = Test("test").run()
self.assertFalse(result.wasSuccessful())
def test_expectThat_does_not_exit_test(self):
class Test(TestCase):
marker = False
def test(self):
self.expectThat("foo", Equals("bar"))
Test.marker = True
result = Test("test").run()
self.assertFalse(result.wasSuccessful())
self.assertTrue(Test.marker)
def test_expectThat_adds_detail(self):
class Test(TestCase):
def test(self):
self.expectThat("foo", Equals("bar"))
test = Test("test")
test.run()
details = test.getDetails()
self.assertIn('Failed expectation', details)
def test__force_failure_fails_test(self):
class Test(TestCase):
def test_foo(self):
self.force_failure = True
self.remaining_code_run = True
test = Test('test_foo')
result = test.run()
self.assertFalse(result.wasSuccessful())
self.assertTrue(test.remaining_code_run)
def get_error_string(self, e):
"""Get the string showing how 'e' would be formatted in test output.
This is a little bit hacky, since it's designed to give consistent
output regardless of Python version.
In testtools, TestResult._exc_info_to_unicode is the point of dispatch
between various different implementations of methods that format
exceptions, so that's what we have to call. However, that method cares
about stack traces and formats the exception class. We don't care
about either of these, so we take its output and parse it a little.
"""
error = TracebackContent((e.__class__, e, None), self).as_text()
# We aren't at all interested in the traceback.
if error.startswith('Traceback (most recent call last):\n'):
lines = error.splitlines(True)[1:]
for i, line in enumerate(lines):
if not line.startswith(' '):
break
error = ''.join(lines[i:])
# We aren't interested in how the exception type is formatted.
exc_class, error = error.split(': ', 1)
return error
def test_assertThat_verbose_unicode(self):
# When assertThat is given matchees or matchers that contain non-ASCII
# unicode strings, we can still provide a meaningful error.
matchee = '\xa7'
matcher = Equals('a')
expected = (
'Match failed. Matchee: %s\n'
'Matcher: %s\n'
'Difference: %s\n\n' % (
repr(matchee).replace("\\xa7", matchee),
matcher,
matcher.match(matchee).describe(),
))
e = self.assertRaises(
self.failureException, self.assertThat, matchee, matcher,
verbose=True)
self.assertEqual(expected, self.get_error_string(e))
def test_assertEqual_nice_formatting(self):
message = "These things ought not be equal."
a = ['apple', 'banana', 'cherry']
b = {'Thatcher': 'One who mends roofs of straw',
'Major': 'A military officer, ranked below colonel',
'Blair': 'To shout loudly',
'Brown': 'The colour of healthy human faeces'}
expected_error = '\n'.join([
'!=:',
'reference = %s' % pformat(a),
'actual = %s' % pformat(b),
': ' + message,
])
self.assertFails(expected_error, self.assertEqual, a, b, message)
self.assertFails(expected_error, self.assertEquals, a, b, message)
self.assertFails(expected_error, self.failUnlessEqual, a, b, message)
def test_assertEqual_formatting_no_message(self):
a = "cat"
b = "dog"
expected_error = "'cat' != 'dog'"
self.assertFails(expected_error, self.assertEqual, a, b)
self.assertFails(expected_error, self.assertEquals, a, b)
self.assertFails(expected_error, self.failUnlessEqual, a, b)
def test_assertEqual_non_ascii_str_with_newlines(self):
message = "Be careful mixing unicode and bytes"
a = "a\n\xa7\n"
b = "Just a longish string so the more verbose output form is used."
expected_error = '\n'.join([
'!=:',
"reference = '''\\",
'a',
repr('\xa7')[1:-1],
"'''",
f'actual = {b!r}',
': ' + message,
])
self.assertFails(expected_error, self.assertEqual, a, b, message)
def test_assertIsNone(self):
self.assertIsNone(None)
expected_error = '0 is not None'
self.assertFails(expected_error, self.assertIsNone, 0)
def test_assertIsNotNone(self):
self.assertIsNotNone(0)
self.assertIsNotNone("0")
expected_error = 'None matches Is(None)'
self.assertFails(expected_error, self.assertIsNotNone, None)
def test_fail_preserves_traceback_detail(self):
class Test(TestCase):
def test(self):
self.addDetail('traceback', text_content('foo'))
self.fail('bar')
test = Test('test')
result = ExtendedTestResult()
test.run(result)
self.assertEqual({'traceback', 'traceback-1'},
set(result._events[1][2].keys()))
class TestAddCleanup(TestCase):
"""Tests for TestCase.addCleanup."""
run_tests_with = FullStackRunTest
def test_cleanup_run_after_tearDown(self):
# Cleanup functions added with 'addCleanup' are called after tearDown
# runs.
log = []
test = make_test_case(
self.getUniqueString(),
set_up=lambda _: log.append('setUp'),
test_body=lambda _: log.append('runTest'),
tear_down=lambda _: log.append('tearDown'),
cleanups=[lambda _: log.append('cleanup')],
)
test.run()
self.assertThat(
log, Equals(['setUp', 'runTest', 'tearDown', 'cleanup']))
def test_add_cleanup_called_if_setUp_fails(self):
# Cleanup functions added with 'addCleanup' are called even if setUp
# fails. Note that tearDown has a different behavior: it is only
# called when setUp succeeds.
log = []
def broken_set_up(ignored):
log.append('brokenSetUp')
raise RuntimeError('Deliberate broken setUp')
test = make_test_case(
self.getUniqueString(),
set_up=broken_set_up,
test_body=lambda _: log.append('runTest'),
tear_down=lambda _: log.append('tearDown'),
cleanups=[lambda _: log.append('cleanup')],
)
test.run()
self.assertThat(log, Equals(['brokenSetUp', 'cleanup']))
def test_addCleanup_called_in_reverse_order(self):
# Cleanup functions added with 'addCleanup' are called in reverse
# order.
#
# One of the main uses of addCleanup is to dynamically create
# resources that need some sort of explicit tearDown. Often one
# resource will be created in terms of another, e.g.,
# self.first = self.makeFirst()
# self.second = self.makeSecond(self.first)
#
# When this happens, we generally want to clean up the second resource
# before the first one, since the second depends on the first.
log = []
test = make_test_case(
self.getUniqueString(),
set_up=lambda _: log.append('setUp'),
test_body=lambda _: log.append('runTest'),
tear_down=lambda _: log.append('tearDown'),
cleanups=[
lambda _: log.append('first'),
lambda _: log.append('second'),
],
)
test.run()
self.assertThat(
log, Equals(['setUp', 'runTest', 'tearDown', 'second', 'first']))
def test_tearDown_runs_on_cleanup_failure(self):
# tearDown runs even if a cleanup function fails.
log = []
test = make_test_case(
self.getUniqueString(),
set_up=lambda _: log.append('setUp'),
test_body=lambda _: log.append('runTest'),
tear_down=lambda _: log.append('tearDown'),
cleanups=[lambda _: 1/0],
)
test.run()
self.assertThat(log, Equals(['setUp', 'runTest', 'tearDown']))
def test_cleanups_continue_running_after_error(self):
# All cleanups are always run, even if one or two of them fail.
log = []
test = make_test_case(
self.getUniqueString(),
set_up=lambda _: log.append('setUp'),
test_body=lambda _: log.append('runTest'),
tear_down=lambda _: log.append('tearDown'),
cleanups=[
lambda _: log.append('first'),
lambda _: 1/0,
lambda _: log.append('second'),
],
)
test.run()
self.assertThat(
log, Equals(['setUp', 'runTest', 'tearDown', 'second', 'first']))
def test_error_in_cleanups_are_captured(self):
# If a cleanup raises an error, we want to record it and fail the the
# test, even though we go on to run other cleanups.
test = make_test_case(self.getUniqueString(), cleanups=[lambda _: 1/0])
log = []
test.run(ExtendedTestResult(log))
self.assertThat(
log, MatchesEvents(
('startTest', test),
('addError', test, {
'traceback': AsText(ContainsAll([
'Traceback (most recent call last):',
'ZeroDivisionError',
])),
}),
('stopTest', test),
)
)
def test_keyboard_interrupt_not_caught(self):
# If a cleanup raises KeyboardInterrupt, it gets reraised.
test = make_test_case(
self.getUniqueString(), cleanups=[
lambda _: raise_(KeyboardInterrupt())])
self.assertThat(test.run, Raises(MatchesException(KeyboardInterrupt)))
def test_all_errors_from_MultipleExceptions_reported(self):
# When a MultipleExceptions exception is caught, all the errors are
# reported.
def raise_many(ignored):
try:
1/0
except Exception:
exc_info1 = sys.exc_info()
try:
1/0
except Exception:
exc_info2 = sys.exc_info()
raise MultipleExceptions(exc_info1, exc_info2)
test = make_test_case(self.getUniqueString(), cleanups=[raise_many])
log = []
test.run(ExtendedTestResult(log))
self.assertThat(
log, MatchesEvents(
('startTest', test),
('addError', test, {
'traceback': AsText(ContainsAll([
'Traceback (most recent call last):',
'ZeroDivisionError',
])),
'traceback-1': AsText(ContainsAll([
'Traceback (most recent call last):',
'ZeroDivisionError',
])),
}),
('stopTest', test),
)
)
def test_multipleCleanupErrorsReported(self):
# Errors from all failing cleanups are reported as separate backtraces.
test = make_test_case(self.getUniqueString(), cleanups=[
lambda _: 1/0,
lambda _: 1/0,
])
log = []
test.run(ExtendedTestResult(log))
self.assertThat(
log, MatchesEvents(
('startTest', test),
('addError', test, {
'traceback': AsText(ContainsAll([
'Traceback (most recent call last):',
'ZeroDivisionError',
])),
'traceback-1': AsText(ContainsAll([
'Traceback (most recent call last):',
'ZeroDivisionError',
])),
}),
('stopTest', test),
)
)
def test_multipleErrorsCoreAndCleanupReported(self):
# Errors from all failing cleanups are reported, with stopTest,
# startTest inserted.
test = make_test_case(
self.getUniqueString(),
test_body=lambda _: raise_(
RuntimeError('Deliberately broken test')),
cleanups=[
lambda _: 1/0,
lambda _: 1/0,
]
)
log = []
test.run(ExtendedTestResult(log))
self.assertThat(
log, MatchesEvents(
('startTest', test),
('addError', test, {
'traceback': AsText(ContainsAll([
'Traceback (most recent call last):',
'RuntimeError: Deliberately broken test',
])),
'traceback-1': AsText(ContainsAll([
'Traceback (most recent call last):',
'ZeroDivisionError',
])),
'traceback-2': AsText(ContainsAll([
'Traceback (most recent call last):',
'ZeroDivisionError',
])),
}),
('stopTest', test),
)
)
class TestRunTestUsage(TestCase):
def test_last_resort_in_place(self):