- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathtest_case.py
2002 lines (1712 loc) · 76.6 KB
/
test_case.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
importcontextlib
importdifflib
importpprint
importpickle
importre
importsys
importlogging
importwarnings
importweakref
importinspect
importtypes
fromcopyimportdeepcopy
fromtestimportsupport
importunittest
fromtest.test_unittest.supportimport (
TestEquality, TestHashing, LoggingResult, LegacyLoggingResult,
ResultWithNoStartTestRunStopTestRun
)
fromtest.supportimportcaptured_stderr, gc_collect
log_foo=logging.getLogger('foo')
log_foobar=logging.getLogger('foo.bar')
log_quux=logging.getLogger('quux')
classTest(object):
"Keep these TestCase classes out of the main namespace"
classFoo(unittest.TestCase):
defrunTest(self): pass
deftest1(self): pass
classBar(Foo):
deftest2(self): pass
classLoggingTestCase(unittest.TestCase):
"""A test case which logs its calls."""
def__init__(self, events):
super(Test.LoggingTestCase, self).__init__('test')
self.events=events
defsetUp(self):
self.events.append('setUp')
deftest(self):
self.events.append('test')
deftearDown(self):
self.events.append('tearDown')
classTest_TestCase(unittest.TestCase, TestEquality, TestHashing):
### Set up attributes used by inherited tests
################################################################
# Used by TestHashing.test_hash and TestEquality.test_eq
eq_pairs= [(Test.Foo('test1'), Test.Foo('test1'))]
# Used by TestEquality.test_ne
ne_pairs= [(Test.Foo('test1'), Test.Foo('runTest')),
(Test.Foo('test1'), Test.Bar('test1')),
(Test.Foo('test1'), Test.Bar('test2'))]
################################################################
### /Set up attributes used by inherited tests
# "class TestCase([methodName])"
# ...
# "Each instance of TestCase will run a single test method: the
# method named methodName."
# ...
# "methodName defaults to "runTest"."
#
# Make sure it really is optional, and that it defaults to the proper
# thing.
deftest_init__no_test_name(self):
classTest(unittest.TestCase):
defrunTest(self): raiseMyException()
deftest(self): pass
self.assertEqual(Test().id()[-13:], '.Test.runTest')
# test that TestCase can be instantiated with no args
# primarily for use at the interactive interpreter
test=unittest.TestCase()
test.assertEqual(3, 3)
withtest.assertRaises(test.failureException):
test.assertEqual(3, 2)
withself.assertRaises(AttributeError):
test.run()
# "class TestCase([methodName])"
# ...
# "Each instance of TestCase will run a single test method: the
# method named methodName."
deftest_init__test_name__valid(self):
classTest(unittest.TestCase):
defrunTest(self): raiseMyException()
deftest(self): pass
self.assertEqual(Test('test').id()[-10:], '.Test.test')
# "class TestCase([methodName])"
# ...
# "Each instance of TestCase will run a single test method: the
# method named methodName."
deftest_init__test_name__invalid(self):
classTest(unittest.TestCase):
defrunTest(self): raiseMyException()
deftest(self): pass
try:
Test('testfoo')
exceptValueError:
pass
else:
self.fail("Failed to raise ValueError")
# "Return the number of tests represented by the this test object. For
# TestCase instances, this will always be 1"
deftest_countTestCases(self):
classFoo(unittest.TestCase):
deftest(self): pass
self.assertEqual(Foo('test').countTestCases(), 1)
# "Return the default type of test result object to be used to run this
# test. For TestCase instances, this will always be
# unittest.TestResult; subclasses of TestCase should
# override this as necessary."
deftest_defaultTestResult(self):
classFoo(unittest.TestCase):
defrunTest(self):
pass
result=Foo().defaultTestResult()
self.assertEqual(type(result), unittest.TestResult)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if setUp() raises
# an exception.
deftest_run_call_order__error_in_setUp(self):
events= []
result=LoggingResult(events)
classFoo(Test.LoggingTestCase):
defsetUp(self):
super(Foo, self).setUp()
raiseRuntimeError('raised by Foo.setUp')
Foo(events).run(result)
expected= ['startTest', 'setUp', 'addError', 'stopTest']
self.assertEqual(events, expected)
# "With a temporary result stopTestRun is called when setUp errors.
deftest_run_call_order__error_in_setUp_default_result(self):
events= []
classFoo(Test.LoggingTestCase):
defdefaultTestResult(self):
returnLoggingResult(self.events)
defsetUp(self):
super(Foo, self).setUp()
raiseRuntimeError('raised by Foo.setUp')
Foo(events).run()
expected= ['startTestRun', 'startTest', 'setUp', 'addError',
'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if the test raises
# an error (as opposed to a failure).
deftest_run_call_order__error_in_test(self):
events= []
result=LoggingResult(events)
classFoo(Test.LoggingTestCase):
deftest(self):
super(Foo, self).test()
raiseRuntimeError('raised by Foo.test')
expected= ['startTest', 'setUp', 'test',
'addError', 'tearDown', 'stopTest']
Foo(events).run(result)
self.assertEqual(events, expected)
# "With a default result, an error in the test still results in stopTestRun
# being called."
deftest_run_call_order__error_in_test_default_result(self):
events= []
classFoo(Test.LoggingTestCase):
defdefaultTestResult(self):
returnLoggingResult(self.events)
deftest(self):
super(Foo, self).test()
raiseRuntimeError('raised by Foo.test')
expected= ['startTestRun', 'startTest', 'setUp', 'test',
'addError', 'tearDown', 'stopTest', 'stopTestRun']
Foo(events).run()
self.assertEqual(events, expected)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if the test signals
# a failure (as opposed to an error).
deftest_run_call_order__failure_in_test(self):
events= []
result=LoggingResult(events)
classFoo(Test.LoggingTestCase):
deftest(self):
super(Foo, self).test()
self.fail('raised by Foo.test')
expected= ['startTest', 'setUp', 'test',
'addFailure', 'tearDown', 'stopTest']
Foo(events).run(result)
self.assertEqual(events, expected)
# "When a test fails with a default result stopTestRun is still called."
deftest_run_call_order__failure_in_test_default_result(self):
classFoo(Test.LoggingTestCase):
defdefaultTestResult(self):
returnLoggingResult(self.events)
deftest(self):
super(Foo, self).test()
self.fail('raised by Foo.test')
expected= ['startTestRun', 'startTest', 'setUp', 'test',
'addFailure', 'tearDown', 'stopTest', 'stopTestRun']
events= []
Foo(events).run()
self.assertEqual(events, expected)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if tearDown() raises
# an exception.
deftest_run_call_order__error_in_tearDown(self):
events= []
result=LoggingResult(events)
classFoo(Test.LoggingTestCase):
deftearDown(self):
super(Foo, self).tearDown()
raiseRuntimeError('raised by Foo.tearDown')
Foo(events).run(result)
expected= ['startTest', 'setUp', 'test', 'tearDown', 'addError',
'stopTest']
self.assertEqual(events, expected)
# "When tearDown errors with a default result stopTestRun is still called."
deftest_run_call_order__error_in_tearDown_default_result(self):
classFoo(Test.LoggingTestCase):
defdefaultTestResult(self):
returnLoggingResult(self.events)
deftearDown(self):
super(Foo, self).tearDown()
raiseRuntimeError('raised by Foo.tearDown')
events= []
Foo(events).run()
expected= ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
'addError', 'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
# "TestCase.run() still works when the defaultTestResult is a TestResult
# that does not support startTestRun and stopTestRun.
deftest_run_call_order_default_result(self):
classFoo(unittest.TestCase):
defdefaultTestResult(self):
returnResultWithNoStartTestRunStopTestRun()
deftest(self):
pass
withself.assertWarns(RuntimeWarning):
Foo('test').run()
deftest_deprecation_of_return_val_from_test(self):
# Issue 41322 - deprecate return of value that is not None from a test
classNothing:
def__eq__(self, o):
returnoisNone
classFoo(unittest.TestCase):
deftest1(self):
return1
deftest2(self):
yield1
deftest3(self):
returnNothing()
withself.assertWarns(DeprecationWarning) asw:
Foo('test1').run()
self.assertIn('It is deprecated to return a value that is not None', str(w.warning))
self.assertIn('test1', str(w.warning))
self.assertEqual(w.filename, __file__)
withself.assertWarns(DeprecationWarning) asw:
Foo('test2').run()
self.assertIn('It is deprecated to return a value that is not None', str(w.warning))
self.assertIn('test2', str(w.warning))
self.assertEqual(w.filename, __file__)
withself.assertWarns(DeprecationWarning) asw:
Foo('test3').run()
self.assertIn('It is deprecated to return a value that is not None', str(w.warning))
self.assertIn('test3', str(w.warning))
self.assertEqual(w.filename, __file__)
def_check_call_order__subtests(self, result, events, expected_events):
classFoo(Test.LoggingTestCase):
deftest(self):
super(Foo, self).test()
foriin [1, 2, 3]:
withself.subTest(i=i):
ifi==1:
self.fail('failure')
forjin [2, 3]:
withself.subTest(j=j):
ifi*j==6:
raiseRuntimeError('raised by Foo.test')
1/0
# Order is the following:
# i=1 => subtest failure
# i=2, j=2 => subtest success
# i=2, j=3 => subtest error
# i=3, j=2 => subtest error
# i=3, j=3 => subtest success
# toplevel => error
Foo(events).run(result)
self.assertEqual(events, expected_events)
deftest_run_call_order__subtests(self):
events= []
result=LoggingResult(events)
expected= ['startTest', 'setUp', 'test',
'addSubTestFailure', 'addSubTestSuccess',
'addSubTestFailure', 'addSubTestFailure',
'addSubTestSuccess', 'addError', 'tearDown', 'stopTest']
self._check_call_order__subtests(result, events, expected)
deftest_run_call_order__subtests_legacy(self):
# With a legacy result object (without an addSubTest method),
# text execution stops after the first subtest failure.
events= []
result=LegacyLoggingResult(events)
expected= ['startTest', 'setUp', 'test',
'addFailure', 'tearDown', 'stopTest']
self._check_call_order__subtests(result, events, expected)
def_check_call_order__subtests_success(self, result, events, expected_events):
classFoo(Test.LoggingTestCase):
deftest(self):
super(Foo, self).test()
foriin [1, 2]:
withself.subTest(i=i):
forjin [2, 3]:
withself.subTest(j=j):
pass
Foo(events).run(result)
self.assertEqual(events, expected_events)
deftest_run_call_order__subtests_success(self):
events= []
result=LoggingResult(events)
# The 6 subtest successes are individually recorded, in addition
# to the whole test success.
expected= (['startTest', 'setUp', 'test']
+6* ['addSubTestSuccess']
+ ['tearDown', 'addSuccess', 'stopTest'])
self._check_call_order__subtests_success(result, events, expected)
deftest_run_call_order__subtests_success_legacy(self):
# With a legacy result, only the whole test success is recorded.
events= []
result=LegacyLoggingResult(events)
expected= ['startTest', 'setUp', 'test', 'tearDown',
'addSuccess', 'stopTest']
self._check_call_order__subtests_success(result, events, expected)
deftest_run_call_order__subtests_failfast(self):
events= []
result=LoggingResult(events)
result.failfast=True
classFoo(Test.LoggingTestCase):
deftest(self):
super(Foo, self).test()
withself.subTest(i=1):
self.fail('failure')
withself.subTest(i=2):
self.fail('failure')
self.fail('failure')
expected= ['startTest', 'setUp', 'test',
'addSubTestFailure', 'tearDown', 'stopTest']
Foo(events).run(result)
self.assertEqual(events, expected)
deftest_subtests_failfast(self):
# Ensure proper test flow with subtests and failfast (issue #22894)
events= []
classFoo(unittest.TestCase):
deftest_a(self):
withself.subTest():
events.append('a1')
events.append('a2')
deftest_b(self):
withself.subTest():
events.append('b1')
withself.subTest():
self.fail('failure')
events.append('b2')
deftest_c(self):
events.append('c')
result=unittest.TestResult()
result.failfast=True
suite=unittest.TestLoader().loadTestsFromTestCase(Foo)
suite.run(result)
expected= ['a1', 'a2', 'b1']
self.assertEqual(events, expected)
deftest_subtests_debug(self):
# Test debug() with a test that uses subTest() (bpo-34900)
events= []
classFoo(unittest.TestCase):
deftest_a(self):
events.append('test case')
withself.subTest():
events.append('subtest 1')
Foo('test_a').debug()
self.assertEqual(events, ['test case', 'subtest 1'])
# "This class attribute gives the exception raised by the test() method.
# If a test framework needs to use a specialized exception, possibly to
# carry additional information, it must subclass this exception in
# order to ``play fair'' with the framework. The initial value of this
# attribute is AssertionError"
deftest_failureException__default(self):
classFoo(unittest.TestCase):
deftest(self):
pass
self.assertIs(Foo('test').failureException, AssertionError)
# "This class attribute gives the exception raised by the test() method.
# If a test framework needs to use a specialized exception, possibly to
# carry additional information, it must subclass this exception in
# order to ``play fair'' with the framework."
#
# Make sure TestCase.run() respects the designated failureException
deftest_failureException__subclassing__explicit_raise(self):
events= []
result=LoggingResult(events)
classFoo(unittest.TestCase):
deftest(self):
raiseRuntimeError()
failureException=RuntimeError
self.assertIs(Foo('test').failureException, RuntimeError)
Foo('test').run(result)
expected= ['startTest', 'addFailure', 'stopTest']
self.assertEqual(events, expected)
# "This class attribute gives the exception raised by the test() method.
# If a test framework needs to use a specialized exception, possibly to
# carry additional information, it must subclass this exception in
# order to ``play fair'' with the framework."
#
# Make sure TestCase.run() respects the designated failureException
deftest_failureException__subclassing__implicit_raise(self):
events= []
result=LoggingResult(events)
classFoo(unittest.TestCase):
deftest(self):
self.fail("foo")
failureException=RuntimeError
self.assertIs(Foo('test').failureException, RuntimeError)
Foo('test').run(result)
expected= ['startTest', 'addFailure', 'stopTest']
self.assertEqual(events, expected)
# "The default implementation does nothing."
deftest_setUp(self):
classFoo(unittest.TestCase):
defrunTest(self):
pass
# ... and nothing should happen
Foo().setUp()
# "The default implementation does nothing."
deftest_tearDown(self):
classFoo(unittest.TestCase):
defrunTest(self):
pass
# ... and nothing should happen
Foo().tearDown()
# "Return a string identifying the specific test case."
#
# Because of the vague nature of the docs, I'm not going to lock this
# test down too much. Really all that can be asserted is that the id()
# will be a string (either 8-byte or unicode -- again, because the docs
# just say "string")
deftest_id(self):
classFoo(unittest.TestCase):
defrunTest(self):
pass
self.assertIsInstance(Foo().id(), str)
# "If result is omitted or None, a temporary result object is created,
# used, and is made available to the caller. As TestCase owns the
# temporary result startTestRun and stopTestRun are called.
deftest_run__uses_defaultTestResult(self):
events= []
defaultResult=LoggingResult(events)
classFoo(unittest.TestCase):
deftest(self):
events.append('test')
defdefaultTestResult(self):
returndefaultResult
# Make run() find a result object on its own
result=Foo('test').run()
self.assertIs(result, defaultResult)
expected= ['startTestRun', 'startTest', 'test', 'addSuccess',
'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
# "The result object is returned to run's caller"
deftest_run__returns_given_result(self):
classFoo(unittest.TestCase):
deftest(self):
pass
result=unittest.TestResult()
retval=Foo('test').run(result)
self.assertIs(retval, result)
# "The same effect [as method run] may be had by simply calling the
# TestCase instance."
deftest_call__invoking_an_instance_delegates_to_run(self):
resultIn=unittest.TestResult()
resultOut=unittest.TestResult()
classFoo(unittest.TestCase):
deftest(self):
pass
defrun(self, result):
self.assertIs(result, resultIn)
returnresultOut
retval=Foo('test')(resultIn)
self.assertIs(retval, resultOut)
deftestShortDescriptionWithoutDocstring(self):
self.assertIsNone(self.shortDescription())
@unittest.skipIf(sys.flags.optimize>=2,
"Docstrings are omitted with -O2 and above")
deftestShortDescriptionWithOneLineDocstring(self):
"""Tests shortDescription() for a method with a docstring."""
self.assertEqual(
self.shortDescription(),
'Tests shortDescription() for a method with a docstring.')
@unittest.skipIf(sys.flags.optimize>=2,
"Docstrings are omitted with -O2 and above")
deftestShortDescriptionWithMultiLineDocstring(self):
"""Tests shortDescription() for a method with a longer docstring.
This method ensures that only the first line of a docstring is
returned used in the short description, no matter how long the
whole thing is.
"""
self.assertEqual(
self.shortDescription(),
'Tests shortDescription() for a method with a longer '
'docstring.')
@unittest.skipIf(sys.flags.optimize>=2,
"Docstrings are omitted with -O2 and above")
deftestShortDescriptionWhitespaceTrimming(self):
"""
Tests shortDescription() whitespace is trimmed, so that the first
line of nonwhite-space text becomes the docstring.
"""
self.assertEqual(
self.shortDescription(),
'Tests shortDescription() whitespace is trimmed, so that the first')
deftestAddTypeEqualityFunc(self):
classSadSnake(object):
"""Dummy class for test_addTypeEqualityFunc."""
s1, s2=SadSnake(), SadSnake()
self.assertFalse(s1==s2)
defAllSnakesCreatedEqual(a, b, msg=None):
returntype(a) ==type(b) ==SadSnake
self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
self.assertEqual(s1, s2)
# No this doesn't clean up and remove the SadSnake equality func
# from this TestCase instance but since it's local nothing else
# will ever notice that.
deftestAssertIs(self):
thing=object()
self.assertIs(thing, thing)
self.assertRaises(self.failureException, self.assertIs, thing, object())
deftestAssertIsNot(self):
thing=object()
self.assertIsNot(thing, object())
self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
deftestAssertIsInstance(self):
thing= []
self.assertIsInstance(thing, list)
self.assertRaises(self.failureException, self.assertIsInstance,
thing, dict)
deftestAssertNotIsInstance(self):
thing= []
self.assertNotIsInstance(thing, dict)
self.assertRaises(self.failureException, self.assertNotIsInstance,
thing, list)
deftestAssertIn(self):
animals= {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
self.assertIn('a', 'abc')
self.assertIn(2, [1, 2, 3])
self.assertIn('monkey', animals)
self.assertNotIn('d', 'abc')
self.assertNotIn(0, [1, 2, 3])
self.assertNotIn('otter', animals)
self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
self.assertRaises(self.failureException, self.assertIn, 'elephant',
animals)
self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
self.assertRaises(self.failureException, self.assertNotIn, 'cow',
animals)
deftestAssertEqual(self):
equal_pairs= [
((), ()),
({}, {}),
([], []),
(set(), set()),
(frozenset(), frozenset())]
fora, binequal_pairs:
# This mess of try excepts is to test the assertEqual behavior
# itself.
try:
self.assertEqual(a, b)
exceptself.failureException:
self.fail('assertEqual(%r, %r) failed'% (a, b))
try:
self.assertEqual(a, b, msg='foo')
exceptself.failureException:
self.fail('assertEqual(%r, %r) with msg= failed'% (a, b))
try:
self.assertEqual(a, b, 'foo')
exceptself.failureException:
self.fail('assertEqual(%r, %r) with third parameter failed'%
(a, b))
unequal_pairs= [
((), []),
({}, set()),
(set([4,1]), frozenset([4,2])),
(frozenset([4,5]), set([2,3])),
(set([3,4]), set([5,4]))]
fora, binunequal_pairs:
self.assertRaises(self.failureException, self.assertEqual, a, b)
self.assertRaises(self.failureException, self.assertEqual, a, b,
'foo')
self.assertRaises(self.failureException, self.assertEqual, a, b,
msg='foo')
deftestEquality(self):
self.assertListEqual([], [])
self.assertTupleEqual((), ())
self.assertSequenceEqual([], ())
a= [0, 'a', []]
b= []
self.assertRaises(unittest.TestCase.failureException,
self.assertListEqual, a, b)
self.assertRaises(unittest.TestCase.failureException,
self.assertListEqual, tuple(a), tuple(b))
self.assertRaises(unittest.TestCase.failureException,
self.assertSequenceEqual, a, tuple(b))
b.extend(a)
self.assertListEqual(a, b)
self.assertTupleEqual(tuple(a), tuple(b))
self.assertSequenceEqual(a, tuple(b))
self.assertSequenceEqual(tuple(a), b)
self.assertRaises(self.failureException, self.assertListEqual,
a, tuple(b))
self.assertRaises(self.failureException, self.assertTupleEqual,
tuple(a), b)
self.assertRaises(self.failureException, self.assertListEqual, None, b)
self.assertRaises(self.failureException, self.assertTupleEqual, None,
tuple(b))
self.assertRaises(self.failureException, self.assertSequenceEqual,
None, tuple(b))
self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
self.assertRaises(self.failureException, self.assertSequenceEqual,
1, 1)
self.assertDictEqual({}, {})
c= { 'x': 1 }
d= {}
self.assertRaises(unittest.TestCase.failureException,
self.assertDictEqual, c, d)
d.update(c)
self.assertDictEqual(c, d)
d['x'] =0
self.assertRaises(unittest.TestCase.failureException,
self.assertDictEqual, c, d, 'These are unequal')
self.assertRaises(self.failureException, self.assertDictEqual, None, d)
self.assertRaises(self.failureException, self.assertDictEqual, [], d)
self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
deftestAssertSequenceEqualMaxDiff(self):
self.assertEqual(self.maxDiff, 80*8)
seq1='a'+'x'*80**2
seq2='b'+'x'*80**2
diff='\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
pprint.pformat(seq2).splitlines()))
# the +1 is the leading \n added by assertSequenceEqual
omitted=unittest.case.DIFF_OMITTED% (len(diff) +1,)
self.maxDiff=len(diff)//2
try:
self.assertSequenceEqual(seq1, seq2)
exceptself.failureExceptionase:
msg=e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertLess(len(msg), len(diff))
self.assertIn(omitted, msg)
self.maxDiff=len(diff) *2
try:
self.assertSequenceEqual(seq1, seq2)
exceptself.failureExceptionase:
msg=e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertGreater(len(msg), len(diff))
self.assertNotIn(omitted, msg)
self.maxDiff=None
try:
self.assertSequenceEqual(seq1, seq2)
exceptself.failureExceptionase:
msg=e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertGreater(len(msg), len(diff))
self.assertNotIn(omitted, msg)
deftestTruncateMessage(self):
self.maxDiff=1
message=self._truncateMessage('foo', 'bar')
omitted=unittest.case.DIFF_OMITTED%len('bar')
self.assertEqual(message, 'foo'+omitted)
self.maxDiff=None
message=self._truncateMessage('foo', 'bar')
self.assertEqual(message, 'foobar')
self.maxDiff=4
message=self._truncateMessage('foo', 'bar')
self.assertEqual(message, 'foobar')
deftestAssertDictEqualTruncates(self):
test=unittest.TestCase('assertEqual')
deftruncate(msg, diff):
return'foo'
test._truncateMessage=truncate
try:
test.assertDictEqual({}, {1: 0})
exceptself.failureExceptionase:
self.assertEqual(str(e), 'foo')
else:
self.fail('assertDictEqual did not fail')
deftestAssertMultiLineEqualTruncates(self):
test=unittest.TestCase('assertEqual')
deftruncate(msg, diff):
return'foo'
test._truncateMessage=truncate
try:
test.assertMultiLineEqual('foo', 'bar')
exceptself.failureExceptionase:
self.assertEqual(str(e), 'foo')
else:
self.fail('assertMultiLineEqual did not fail')
deftestAssertEqual_diffThreshold(self):
# check threshold value
self.assertEqual(self._diffThreshold, 2**16)
# disable madDiff to get diff markers
self.maxDiff=None
# set a lower threshold value and add a cleanup to restore it
old_threshold=self._diffThreshold
self._diffThreshold=2**5
self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold))
# under the threshold: diff marker (^) in error message
s='x'* (2**4)
withself.assertRaises(self.failureException) ascm:
self.assertEqual(s+'a', s+'b')
self.assertIn('^', str(cm.exception))
self.assertEqual(s+'a', s+'a')
# over the threshold: diff not used and marker (^) not in error message
s='x'* (2**6)
# if the path that uses difflib is taken, _truncateMessage will be
# called -- replace it with explodingTruncation to verify that this
# doesn't happen
defexplodingTruncation(message, diff):
raiseSystemError('this should not be raised')
old_truncate=self._truncateMessage
self._truncateMessage=explodingTruncation
self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate))
s1, s2=s+'a', s+'b'
withself.assertRaises(self.failureException) ascm:
self.assertEqual(s1, s2)
self.assertNotIn('^', str(cm.exception))
self.assertEqual(str(cm.exception), '%r != %r'% (s1, s2))
self.assertEqual(s+'a', s+'a')
deftestAssertEqual_shorten(self):
# set a lower threshold value and add a cleanup to restore it
old_threshold=self._diffThreshold
self._diffThreshold=0
self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold))
s='x'*100
s1, s2=s+'a', s+'b'
withself.assertRaises(self.failureException) ascm:
self.assertEqual(s1, s2)
c='xxxx[35 chars]'+'x'*61
self.assertEqual(str(cm.exception), "'%sa' != '%sb'"% (c, c))
self.assertEqual(s+'a', s+'a')
p='y'*50
s1, s2=s+'a'+p, s+'b'+p
withself.assertRaises(self.failureException) ascm:
self.assertEqual(s1, s2)
c='xxxx[85 chars]xxxxxxxxxxx'
self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'"% (c, p, c, p))
p='y'*100
s1, s2=s+'a'+p, s+'b'+p
withself.assertRaises(self.failureException) ascm:
self.assertEqual(s1, s2)
c='xxxx[91 chars]xxxxx'
d='y'*40+'[56 chars]yyyy'
self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'"% (c, d, c, d))
deftestAssertCountEqual(self):
a=object()
self.assertCountEqual([1, 2, 3], [3, 2, 1])
self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, 2] + [3] *100, [1] *100+ [2, 3])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, "2", "a", "a"], ["a", "2", True, 1])
self.assertRaises(self.failureException, self.assertCountEqual,
[10], [10, 11])
self.assertRaises(self.failureException, self.assertCountEqual,
[10, 11], [10])
self.assertRaises(self.failureException, self.assertCountEqual,
[10, 11, 10], [10, 11])
# Test that sequences of unhashable objects can be tested for sameness:
self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
# Test that iterator of unhashable objects can be tested for sameness:
self.assertCountEqual(iter([1, 2, [], 3, 4]),
iter([1, 2, [], 3, 4]))
# hashable types, but not orderable
self.assertRaises(self.failureException, self.assertCountEqual,
[], [divmod, 'x', 1, 5j, 2j, frozenset()])
# comparing dicts
self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
# comparing heterogeneous non-hashable sequences
self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
self.assertRaises(self.failureException, self.assertCountEqual,
[], [divmod, [], 'x', 1, 5j, 2j, set()])
self.assertRaises(self.failureException, self.assertCountEqual,
[[1]], [[2]])
# Same elements, but not same sequence length
self.assertRaises(self.failureException, self.assertCountEqual,
[1, 1, 2], [2, 1])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, 1, "2", "a", "a"], ["2", "2", True, "a"])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, {'b': 2}, None, True], [{'b': 2}, True, None])
# Same elements which don't reliably compare, in
# different order, see issue 10242
a= [{2,4}, {1,2}]
b=a[::-1]
self.assertCountEqual(a, b)
# test utility functions supporting assertCountEqual()
diffs=set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce'))
expected= {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')}
self.assertEqual(diffs, expected)
diffs=unittest.util._count_diff_all_purpose([[]], [])