1 | n/a | import contextlib |
---|
2 | n/a | import difflib |
---|
3 | n/a | import pprint |
---|
4 | n/a | import pickle |
---|
5 | n/a | import re |
---|
6 | n/a | import sys |
---|
7 | n/a | import logging |
---|
8 | n/a | import warnings |
---|
9 | n/a | import weakref |
---|
10 | n/a | import inspect |
---|
11 | n/a | |
---|
12 | n/a | from copy import deepcopy |
---|
13 | n/a | from test import support |
---|
14 | n/a | |
---|
15 | n/a | import unittest |
---|
16 | n/a | |
---|
17 | n/a | from unittest.test.support import ( |
---|
18 | n/a | TestEquality, TestHashing, LoggingResult, LegacyLoggingResult, |
---|
19 | n/a | ResultWithNoStartTestRunStopTestRun |
---|
20 | n/a | ) |
---|
21 | n/a | from test.support import captured_stderr |
---|
22 | n/a | |
---|
23 | n/a | |
---|
24 | n/a | log_foo = logging.getLogger('foo') |
---|
25 | n/a | log_foobar = logging.getLogger('foo.bar') |
---|
26 | n/a | log_quux = logging.getLogger('quux') |
---|
27 | n/a | |
---|
28 | n/a | |
---|
29 | n/a | class Test(object): |
---|
30 | n/a | "Keep these TestCase classes out of the main namespace" |
---|
31 | n/a | |
---|
32 | n/a | class Foo(unittest.TestCase): |
---|
33 | n/a | def runTest(self): pass |
---|
34 | n/a | def test1(self): pass |
---|
35 | n/a | |
---|
36 | n/a | class Bar(Foo): |
---|
37 | n/a | def test2(self): pass |
---|
38 | n/a | |
---|
39 | n/a | class LoggingTestCase(unittest.TestCase): |
---|
40 | n/a | """A test case which logs its calls.""" |
---|
41 | n/a | |
---|
42 | n/a | def __init__(self, events): |
---|
43 | n/a | super(Test.LoggingTestCase, self).__init__('test') |
---|
44 | n/a | self.events = events |
---|
45 | n/a | |
---|
46 | n/a | def setUp(self): |
---|
47 | n/a | self.events.append('setUp') |
---|
48 | n/a | |
---|
49 | n/a | def test(self): |
---|
50 | n/a | self.events.append('test') |
---|
51 | n/a | |
---|
52 | n/a | def tearDown(self): |
---|
53 | n/a | self.events.append('tearDown') |
---|
54 | n/a | |
---|
55 | n/a | |
---|
56 | n/a | class Test_TestCase(unittest.TestCase, TestEquality, TestHashing): |
---|
57 | n/a | |
---|
58 | n/a | ### Set up attributes used by inherited tests |
---|
59 | n/a | ################################################################ |
---|
60 | n/a | |
---|
61 | n/a | # Used by TestHashing.test_hash and TestEquality.test_eq |
---|
62 | n/a | eq_pairs = [(Test.Foo('test1'), Test.Foo('test1'))] |
---|
63 | n/a | |
---|
64 | n/a | # Used by TestEquality.test_ne |
---|
65 | n/a | ne_pairs = [(Test.Foo('test1'), Test.Foo('runTest')), |
---|
66 | n/a | (Test.Foo('test1'), Test.Bar('test1')), |
---|
67 | n/a | (Test.Foo('test1'), Test.Bar('test2'))] |
---|
68 | n/a | |
---|
69 | n/a | ################################################################ |
---|
70 | n/a | ### /Set up attributes used by inherited tests |
---|
71 | n/a | |
---|
72 | n/a | |
---|
73 | n/a | # "class TestCase([methodName])" |
---|
74 | n/a | # ... |
---|
75 | n/a | # "Each instance of TestCase will run a single test method: the |
---|
76 | n/a | # method named methodName." |
---|
77 | n/a | # ... |
---|
78 | n/a | # "methodName defaults to "runTest"." |
---|
79 | n/a | # |
---|
80 | n/a | # Make sure it really is optional, and that it defaults to the proper |
---|
81 | n/a | # thing. |
---|
82 | n/a | def test_init__no_test_name(self): |
---|
83 | n/a | class Test(unittest.TestCase): |
---|
84 | n/a | def runTest(self): raise MyException() |
---|
85 | n/a | def test(self): pass |
---|
86 | n/a | |
---|
87 | n/a | self.assertEqual(Test().id()[-13:], '.Test.runTest') |
---|
88 | n/a | |
---|
89 | n/a | # test that TestCase can be instantiated with no args |
---|
90 | n/a | # primarily for use at the interactive interpreter |
---|
91 | n/a | test = unittest.TestCase() |
---|
92 | n/a | test.assertEqual(3, 3) |
---|
93 | n/a | with test.assertRaises(test.failureException): |
---|
94 | n/a | test.assertEqual(3, 2) |
---|
95 | n/a | |
---|
96 | n/a | with self.assertRaises(AttributeError): |
---|
97 | n/a | test.run() |
---|
98 | n/a | |
---|
99 | n/a | # "class TestCase([methodName])" |
---|
100 | n/a | # ... |
---|
101 | n/a | # "Each instance of TestCase will run a single test method: the |
---|
102 | n/a | # method named methodName." |
---|
103 | n/a | def test_init__test_name__valid(self): |
---|
104 | n/a | class Test(unittest.TestCase): |
---|
105 | n/a | def runTest(self): raise MyException() |
---|
106 | n/a | def test(self): pass |
---|
107 | n/a | |
---|
108 | n/a | self.assertEqual(Test('test').id()[-10:], '.Test.test') |
---|
109 | n/a | |
---|
110 | n/a | # "class TestCase([methodName])" |
---|
111 | n/a | # ... |
---|
112 | n/a | # "Each instance of TestCase will run a single test method: the |
---|
113 | n/a | # method named methodName." |
---|
114 | n/a | def test_init__test_name__invalid(self): |
---|
115 | n/a | class Test(unittest.TestCase): |
---|
116 | n/a | def runTest(self): raise MyException() |
---|
117 | n/a | def test(self): pass |
---|
118 | n/a | |
---|
119 | n/a | try: |
---|
120 | n/a | Test('testfoo') |
---|
121 | n/a | except ValueError: |
---|
122 | n/a | pass |
---|
123 | n/a | else: |
---|
124 | n/a | self.fail("Failed to raise ValueError") |
---|
125 | n/a | |
---|
126 | n/a | # "Return the number of tests represented by the this test object. For |
---|
127 | n/a | # TestCase instances, this will always be 1" |
---|
128 | n/a | def test_countTestCases(self): |
---|
129 | n/a | class Foo(unittest.TestCase): |
---|
130 | n/a | def test(self): pass |
---|
131 | n/a | |
---|
132 | n/a | self.assertEqual(Foo('test').countTestCases(), 1) |
---|
133 | n/a | |
---|
134 | n/a | # "Return the default type of test result object to be used to run this |
---|
135 | n/a | # test. For TestCase instances, this will always be |
---|
136 | n/a | # unittest.TestResult; subclasses of TestCase should |
---|
137 | n/a | # override this as necessary." |
---|
138 | n/a | def test_defaultTestResult(self): |
---|
139 | n/a | class Foo(unittest.TestCase): |
---|
140 | n/a | def runTest(self): |
---|
141 | n/a | pass |
---|
142 | n/a | |
---|
143 | n/a | result = Foo().defaultTestResult() |
---|
144 | n/a | self.assertEqual(type(result), unittest.TestResult) |
---|
145 | n/a | |
---|
146 | n/a | # "When a setUp() method is defined, the test runner will run that method |
---|
147 | n/a | # prior to each test. Likewise, if a tearDown() method is defined, the |
---|
148 | n/a | # test runner will invoke that method after each test. In the example, |
---|
149 | n/a | # setUp() was used to create a fresh sequence for each test." |
---|
150 | n/a | # |
---|
151 | n/a | # Make sure the proper call order is maintained, even if setUp() raises |
---|
152 | n/a | # an exception. |
---|
153 | n/a | def test_run_call_order__error_in_setUp(self): |
---|
154 | n/a | events = [] |
---|
155 | n/a | result = LoggingResult(events) |
---|
156 | n/a | |
---|
157 | n/a | class Foo(Test.LoggingTestCase): |
---|
158 | n/a | def setUp(self): |
---|
159 | n/a | super(Foo, self).setUp() |
---|
160 | n/a | raise RuntimeError('raised by Foo.setUp') |
---|
161 | n/a | |
---|
162 | n/a | Foo(events).run(result) |
---|
163 | n/a | expected = ['startTest', 'setUp', 'addError', 'stopTest'] |
---|
164 | n/a | self.assertEqual(events, expected) |
---|
165 | n/a | |
---|
166 | n/a | # "With a temporary result stopTestRun is called when setUp errors. |
---|
167 | n/a | def test_run_call_order__error_in_setUp_default_result(self): |
---|
168 | n/a | events = [] |
---|
169 | n/a | |
---|
170 | n/a | class Foo(Test.LoggingTestCase): |
---|
171 | n/a | def defaultTestResult(self): |
---|
172 | n/a | return LoggingResult(self.events) |
---|
173 | n/a | |
---|
174 | n/a | def setUp(self): |
---|
175 | n/a | super(Foo, self).setUp() |
---|
176 | n/a | raise RuntimeError('raised by Foo.setUp') |
---|
177 | n/a | |
---|
178 | n/a | Foo(events).run() |
---|
179 | n/a | expected = ['startTestRun', 'startTest', 'setUp', 'addError', |
---|
180 | n/a | 'stopTest', 'stopTestRun'] |
---|
181 | n/a | self.assertEqual(events, expected) |
---|
182 | n/a | |
---|
183 | n/a | # "When a setUp() method is defined, the test runner will run that method |
---|
184 | n/a | # prior to each test. Likewise, if a tearDown() method is defined, the |
---|
185 | n/a | # test runner will invoke that method after each test. In the example, |
---|
186 | n/a | # setUp() was used to create a fresh sequence for each test." |
---|
187 | n/a | # |
---|
188 | n/a | # Make sure the proper call order is maintained, even if the test raises |
---|
189 | n/a | # an error (as opposed to a failure). |
---|
190 | n/a | def test_run_call_order__error_in_test(self): |
---|
191 | n/a | events = [] |
---|
192 | n/a | result = LoggingResult(events) |
---|
193 | n/a | |
---|
194 | n/a | class Foo(Test.LoggingTestCase): |
---|
195 | n/a | def test(self): |
---|
196 | n/a | super(Foo, self).test() |
---|
197 | n/a | raise RuntimeError('raised by Foo.test') |
---|
198 | n/a | |
---|
199 | n/a | expected = ['startTest', 'setUp', 'test', 'tearDown', |
---|
200 | n/a | 'addError', 'stopTest'] |
---|
201 | n/a | Foo(events).run(result) |
---|
202 | n/a | self.assertEqual(events, expected) |
---|
203 | n/a | |
---|
204 | n/a | # "With a default result, an error in the test still results in stopTestRun |
---|
205 | n/a | # being called." |
---|
206 | n/a | def test_run_call_order__error_in_test_default_result(self): |
---|
207 | n/a | events = [] |
---|
208 | n/a | |
---|
209 | n/a | class Foo(Test.LoggingTestCase): |
---|
210 | n/a | def defaultTestResult(self): |
---|
211 | n/a | return LoggingResult(self.events) |
---|
212 | n/a | |
---|
213 | n/a | def test(self): |
---|
214 | n/a | super(Foo, self).test() |
---|
215 | n/a | raise RuntimeError('raised by Foo.test') |
---|
216 | n/a | |
---|
217 | n/a | expected = ['startTestRun', 'startTest', 'setUp', 'test', |
---|
218 | n/a | 'tearDown', 'addError', 'stopTest', 'stopTestRun'] |
---|
219 | n/a | Foo(events).run() |
---|
220 | n/a | self.assertEqual(events, expected) |
---|
221 | n/a | |
---|
222 | n/a | # "When a setUp() method is defined, the test runner will run that method |
---|
223 | n/a | # prior to each test. Likewise, if a tearDown() method is defined, the |
---|
224 | n/a | # test runner will invoke that method after each test. In the example, |
---|
225 | n/a | # setUp() was used to create a fresh sequence for each test." |
---|
226 | n/a | # |
---|
227 | n/a | # Make sure the proper call order is maintained, even if the test signals |
---|
228 | n/a | # a failure (as opposed to an error). |
---|
229 | n/a | def test_run_call_order__failure_in_test(self): |
---|
230 | n/a | events = [] |
---|
231 | n/a | result = LoggingResult(events) |
---|
232 | n/a | |
---|
233 | n/a | class Foo(Test.LoggingTestCase): |
---|
234 | n/a | def test(self): |
---|
235 | n/a | super(Foo, self).test() |
---|
236 | n/a | self.fail('raised by Foo.test') |
---|
237 | n/a | |
---|
238 | n/a | expected = ['startTest', 'setUp', 'test', 'tearDown', |
---|
239 | n/a | 'addFailure', 'stopTest'] |
---|
240 | n/a | Foo(events).run(result) |
---|
241 | n/a | self.assertEqual(events, expected) |
---|
242 | n/a | |
---|
243 | n/a | # "When a test fails with a default result stopTestRun is still called." |
---|
244 | n/a | def test_run_call_order__failure_in_test_default_result(self): |
---|
245 | n/a | |
---|
246 | n/a | class Foo(Test.LoggingTestCase): |
---|
247 | n/a | def defaultTestResult(self): |
---|
248 | n/a | return LoggingResult(self.events) |
---|
249 | n/a | def test(self): |
---|
250 | n/a | super(Foo, self).test() |
---|
251 | n/a | self.fail('raised by Foo.test') |
---|
252 | n/a | |
---|
253 | n/a | expected = ['startTestRun', 'startTest', 'setUp', 'test', |
---|
254 | n/a | 'tearDown', 'addFailure', 'stopTest', 'stopTestRun'] |
---|
255 | n/a | events = [] |
---|
256 | n/a | Foo(events).run() |
---|
257 | n/a | self.assertEqual(events, expected) |
---|
258 | n/a | |
---|
259 | n/a | # "When a setUp() method is defined, the test runner will run that method |
---|
260 | n/a | # prior to each test. Likewise, if a tearDown() method is defined, the |
---|
261 | n/a | # test runner will invoke that method after each test. In the example, |
---|
262 | n/a | # setUp() was used to create a fresh sequence for each test." |
---|
263 | n/a | # |
---|
264 | n/a | # Make sure the proper call order is maintained, even if tearDown() raises |
---|
265 | n/a | # an exception. |
---|
266 | n/a | def test_run_call_order__error_in_tearDown(self): |
---|
267 | n/a | events = [] |
---|
268 | n/a | result = LoggingResult(events) |
---|
269 | n/a | |
---|
270 | n/a | class Foo(Test.LoggingTestCase): |
---|
271 | n/a | def tearDown(self): |
---|
272 | n/a | super(Foo, self).tearDown() |
---|
273 | n/a | raise RuntimeError('raised by Foo.tearDown') |
---|
274 | n/a | |
---|
275 | n/a | Foo(events).run(result) |
---|
276 | n/a | expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', |
---|
277 | n/a | 'stopTest'] |
---|
278 | n/a | self.assertEqual(events, expected) |
---|
279 | n/a | |
---|
280 | n/a | # "When tearDown errors with a default result stopTestRun is still called." |
---|
281 | n/a | def test_run_call_order__error_in_tearDown_default_result(self): |
---|
282 | n/a | |
---|
283 | n/a | class Foo(Test.LoggingTestCase): |
---|
284 | n/a | def defaultTestResult(self): |
---|
285 | n/a | return LoggingResult(self.events) |
---|
286 | n/a | def tearDown(self): |
---|
287 | n/a | super(Foo, self).tearDown() |
---|
288 | n/a | raise RuntimeError('raised by Foo.tearDown') |
---|
289 | n/a | |
---|
290 | n/a | events = [] |
---|
291 | n/a | Foo(events).run() |
---|
292 | n/a | expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', |
---|
293 | n/a | 'addError', 'stopTest', 'stopTestRun'] |
---|
294 | n/a | self.assertEqual(events, expected) |
---|
295 | n/a | |
---|
296 | n/a | # "TestCase.run() still works when the defaultTestResult is a TestResult |
---|
297 | n/a | # that does not support startTestRun and stopTestRun. |
---|
298 | n/a | def test_run_call_order_default_result(self): |
---|
299 | n/a | |
---|
300 | n/a | class Foo(unittest.TestCase): |
---|
301 | n/a | def defaultTestResult(self): |
---|
302 | n/a | return ResultWithNoStartTestRunStopTestRun() |
---|
303 | n/a | def test(self): |
---|
304 | n/a | pass |
---|
305 | n/a | |
---|
306 | n/a | Foo('test').run() |
---|
307 | n/a | |
---|
308 | n/a | def _check_call_order__subtests(self, result, events, expected_events): |
---|
309 | n/a | class Foo(Test.LoggingTestCase): |
---|
310 | n/a | def test(self): |
---|
311 | n/a | super(Foo, self).test() |
---|
312 | n/a | for i in [1, 2, 3]: |
---|
313 | n/a | with self.subTest(i=i): |
---|
314 | n/a | if i == 1: |
---|
315 | n/a | self.fail('failure') |
---|
316 | n/a | for j in [2, 3]: |
---|
317 | n/a | with self.subTest(j=j): |
---|
318 | n/a | if i * j == 6: |
---|
319 | n/a | raise RuntimeError('raised by Foo.test') |
---|
320 | n/a | 1 / 0 |
---|
321 | n/a | |
---|
322 | n/a | # Order is the following: |
---|
323 | n/a | # i=1 => subtest failure |
---|
324 | n/a | # i=2, j=2 => subtest success |
---|
325 | n/a | # i=2, j=3 => subtest error |
---|
326 | n/a | # i=3, j=2 => subtest error |
---|
327 | n/a | # i=3, j=3 => subtest success |
---|
328 | n/a | # toplevel => error |
---|
329 | n/a | Foo(events).run(result) |
---|
330 | n/a | self.assertEqual(events, expected_events) |
---|
331 | n/a | |
---|
332 | n/a | def test_run_call_order__subtests(self): |
---|
333 | n/a | events = [] |
---|
334 | n/a | result = LoggingResult(events) |
---|
335 | n/a | expected = ['startTest', 'setUp', 'test', 'tearDown', |
---|
336 | n/a | 'addSubTestFailure', 'addSubTestSuccess', |
---|
337 | n/a | 'addSubTestFailure', 'addSubTestFailure', |
---|
338 | n/a | 'addSubTestSuccess', 'addError', 'stopTest'] |
---|
339 | n/a | self._check_call_order__subtests(result, events, expected) |
---|
340 | n/a | |
---|
341 | n/a | def test_run_call_order__subtests_legacy(self): |
---|
342 | n/a | # With a legacy result object (without an addSubTest method), |
---|
343 | n/a | # text execution stops after the first subtest failure. |
---|
344 | n/a | events = [] |
---|
345 | n/a | result = LegacyLoggingResult(events) |
---|
346 | n/a | expected = ['startTest', 'setUp', 'test', 'tearDown', |
---|
347 | n/a | 'addFailure', 'stopTest'] |
---|
348 | n/a | self._check_call_order__subtests(result, events, expected) |
---|
349 | n/a | |
---|
350 | n/a | def _check_call_order__subtests_success(self, result, events, expected_events): |
---|
351 | n/a | class Foo(Test.LoggingTestCase): |
---|
352 | n/a | def test(self): |
---|
353 | n/a | super(Foo, self).test() |
---|
354 | n/a | for i in [1, 2]: |
---|
355 | n/a | with self.subTest(i=i): |
---|
356 | n/a | for j in [2, 3]: |
---|
357 | n/a | with self.subTest(j=j): |
---|
358 | n/a | pass |
---|
359 | n/a | |
---|
360 | n/a | Foo(events).run(result) |
---|
361 | n/a | self.assertEqual(events, expected_events) |
---|
362 | n/a | |
---|
363 | n/a | def test_run_call_order__subtests_success(self): |
---|
364 | n/a | events = [] |
---|
365 | n/a | result = LoggingResult(events) |
---|
366 | n/a | # The 6 subtest successes are individually recorded, in addition |
---|
367 | n/a | # to the whole test success. |
---|
368 | n/a | expected = (['startTest', 'setUp', 'test', 'tearDown'] |
---|
369 | n/a | + 6 * ['addSubTestSuccess'] |
---|
370 | n/a | + ['addSuccess', 'stopTest']) |
---|
371 | n/a | self._check_call_order__subtests_success(result, events, expected) |
---|
372 | n/a | |
---|
373 | n/a | def test_run_call_order__subtests_success_legacy(self): |
---|
374 | n/a | # With a legacy result, only the whole test success is recorded. |
---|
375 | n/a | events = [] |
---|
376 | n/a | result = LegacyLoggingResult(events) |
---|
377 | n/a | expected = ['startTest', 'setUp', 'test', 'tearDown', |
---|
378 | n/a | 'addSuccess', 'stopTest'] |
---|
379 | n/a | self._check_call_order__subtests_success(result, events, expected) |
---|
380 | n/a | |
---|
381 | n/a | def test_run_call_order__subtests_failfast(self): |
---|
382 | n/a | events = [] |
---|
383 | n/a | result = LoggingResult(events) |
---|
384 | n/a | result.failfast = True |
---|
385 | n/a | |
---|
386 | n/a | class Foo(Test.LoggingTestCase): |
---|
387 | n/a | def test(self): |
---|
388 | n/a | super(Foo, self).test() |
---|
389 | n/a | with self.subTest(i=1): |
---|
390 | n/a | self.fail('failure') |
---|
391 | n/a | with self.subTest(i=2): |
---|
392 | n/a | self.fail('failure') |
---|
393 | n/a | self.fail('failure') |
---|
394 | n/a | |
---|
395 | n/a | expected = ['startTest', 'setUp', 'test', 'tearDown', |
---|
396 | n/a | 'addSubTestFailure', 'stopTest'] |
---|
397 | n/a | Foo(events).run(result) |
---|
398 | n/a | self.assertEqual(events, expected) |
---|
399 | n/a | |
---|
400 | n/a | def test_subtests_failfast(self): |
---|
401 | n/a | # Ensure proper test flow with subtests and failfast (issue #22894) |
---|
402 | n/a | events = [] |
---|
403 | n/a | |
---|
404 | n/a | class Foo(unittest.TestCase): |
---|
405 | n/a | def test_a(self): |
---|
406 | n/a | with self.subTest(): |
---|
407 | n/a | events.append('a1') |
---|
408 | n/a | events.append('a2') |
---|
409 | n/a | |
---|
410 | n/a | def test_b(self): |
---|
411 | n/a | with self.subTest(): |
---|
412 | n/a | events.append('b1') |
---|
413 | n/a | with self.subTest(): |
---|
414 | n/a | self.fail('failure') |
---|
415 | n/a | events.append('b2') |
---|
416 | n/a | |
---|
417 | n/a | def test_c(self): |
---|
418 | n/a | events.append('c') |
---|
419 | n/a | |
---|
420 | n/a | result = unittest.TestResult() |
---|
421 | n/a | result.failfast = True |
---|
422 | n/a | suite = unittest.makeSuite(Foo) |
---|
423 | n/a | suite.run(result) |
---|
424 | n/a | |
---|
425 | n/a | expected = ['a1', 'a2', 'b1'] |
---|
426 | n/a | self.assertEqual(events, expected) |
---|
427 | n/a | |
---|
428 | n/a | # "This class attribute gives the exception raised by the test() method. |
---|
429 | n/a | # If a test framework needs to use a specialized exception, possibly to |
---|
430 | n/a | # carry additional information, it must subclass this exception in |
---|
431 | n/a | # order to ``play fair'' with the framework. The initial value of this |
---|
432 | n/a | # attribute is AssertionError" |
---|
433 | n/a | def test_failureException__default(self): |
---|
434 | n/a | class Foo(unittest.TestCase): |
---|
435 | n/a | def test(self): |
---|
436 | n/a | pass |
---|
437 | n/a | |
---|
438 | n/a | self.assertIs(Foo('test').failureException, AssertionError) |
---|
439 | n/a | |
---|
440 | n/a | # "This class attribute gives the exception raised by the test() method. |
---|
441 | n/a | # If a test framework needs to use a specialized exception, possibly to |
---|
442 | n/a | # carry additional information, it must subclass this exception in |
---|
443 | n/a | # order to ``play fair'' with the framework." |
---|
444 | n/a | # |
---|
445 | n/a | # Make sure TestCase.run() respects the designated failureException |
---|
446 | n/a | def test_failureException__subclassing__explicit_raise(self): |
---|
447 | n/a | events = [] |
---|
448 | n/a | result = LoggingResult(events) |
---|
449 | n/a | |
---|
450 | n/a | class Foo(unittest.TestCase): |
---|
451 | n/a | def test(self): |
---|
452 | n/a | raise RuntimeError() |
---|
453 | n/a | |
---|
454 | n/a | failureException = RuntimeError |
---|
455 | n/a | |
---|
456 | n/a | self.assertIs(Foo('test').failureException, RuntimeError) |
---|
457 | n/a | |
---|
458 | n/a | |
---|
459 | n/a | Foo('test').run(result) |
---|
460 | n/a | expected = ['startTest', 'addFailure', 'stopTest'] |
---|
461 | n/a | self.assertEqual(events, expected) |
---|
462 | n/a | |
---|
463 | n/a | # "This class attribute gives the exception raised by the test() method. |
---|
464 | n/a | # If a test framework needs to use a specialized exception, possibly to |
---|
465 | n/a | # carry additional information, it must subclass this exception in |
---|
466 | n/a | # order to ``play fair'' with the framework." |
---|
467 | n/a | # |
---|
468 | n/a | # Make sure TestCase.run() respects the designated failureException |
---|
469 | n/a | def test_failureException__subclassing__implicit_raise(self): |
---|
470 | n/a | events = [] |
---|
471 | n/a | result = LoggingResult(events) |
---|
472 | n/a | |
---|
473 | n/a | class Foo(unittest.TestCase): |
---|
474 | n/a | def test(self): |
---|
475 | n/a | self.fail("foo") |
---|
476 | n/a | |
---|
477 | n/a | failureException = RuntimeError |
---|
478 | n/a | |
---|
479 | n/a | self.assertIs(Foo('test').failureException, RuntimeError) |
---|
480 | n/a | |
---|
481 | n/a | |
---|
482 | n/a | Foo('test').run(result) |
---|
483 | n/a | expected = ['startTest', 'addFailure', 'stopTest'] |
---|
484 | n/a | self.assertEqual(events, expected) |
---|
485 | n/a | |
---|
486 | n/a | # "The default implementation does nothing." |
---|
487 | n/a | def test_setUp(self): |
---|
488 | n/a | class Foo(unittest.TestCase): |
---|
489 | n/a | def runTest(self): |
---|
490 | n/a | pass |
---|
491 | n/a | |
---|
492 | n/a | # ... and nothing should happen |
---|
493 | n/a | Foo().setUp() |
---|
494 | n/a | |
---|
495 | n/a | # "The default implementation does nothing." |
---|
496 | n/a | def test_tearDown(self): |
---|
497 | n/a | class Foo(unittest.TestCase): |
---|
498 | n/a | def runTest(self): |
---|
499 | n/a | pass |
---|
500 | n/a | |
---|
501 | n/a | # ... and nothing should happen |
---|
502 | n/a | Foo().tearDown() |
---|
503 | n/a | |
---|
504 | n/a | # "Return a string identifying the specific test case." |
---|
505 | n/a | # |
---|
506 | n/a | # Because of the vague nature of the docs, I'm not going to lock this |
---|
507 | n/a | # test down too much. Really all that can be asserted is that the id() |
---|
508 | n/a | # will be a string (either 8-byte or unicode -- again, because the docs |
---|
509 | n/a | # just say "string") |
---|
510 | n/a | def test_id(self): |
---|
511 | n/a | class Foo(unittest.TestCase): |
---|
512 | n/a | def runTest(self): |
---|
513 | n/a | pass |
---|
514 | n/a | |
---|
515 | n/a | self.assertIsInstance(Foo().id(), str) |
---|
516 | n/a | |
---|
517 | n/a | |
---|
518 | n/a | # "If result is omitted or None, a temporary result object is created, |
---|
519 | n/a | # used, and is made available to the caller. As TestCase owns the |
---|
520 | n/a | # temporary result startTestRun and stopTestRun are called. |
---|
521 | n/a | |
---|
522 | n/a | def test_run__uses_defaultTestResult(self): |
---|
523 | n/a | events = [] |
---|
524 | n/a | defaultResult = LoggingResult(events) |
---|
525 | n/a | |
---|
526 | n/a | class Foo(unittest.TestCase): |
---|
527 | n/a | def test(self): |
---|
528 | n/a | events.append('test') |
---|
529 | n/a | |
---|
530 | n/a | def defaultTestResult(self): |
---|
531 | n/a | return defaultResult |
---|
532 | n/a | |
---|
533 | n/a | # Make run() find a result object on its own |
---|
534 | n/a | result = Foo('test').run() |
---|
535 | n/a | |
---|
536 | n/a | self.assertIs(result, defaultResult) |
---|
537 | n/a | expected = ['startTestRun', 'startTest', 'test', 'addSuccess', |
---|
538 | n/a | 'stopTest', 'stopTestRun'] |
---|
539 | n/a | self.assertEqual(events, expected) |
---|
540 | n/a | |
---|
541 | n/a | |
---|
542 | n/a | # "The result object is returned to run's caller" |
---|
543 | n/a | def test_run__returns_given_result(self): |
---|
544 | n/a | |
---|
545 | n/a | class Foo(unittest.TestCase): |
---|
546 | n/a | def test(self): |
---|
547 | n/a | pass |
---|
548 | n/a | |
---|
549 | n/a | result = unittest.TestResult() |
---|
550 | n/a | |
---|
551 | n/a | retval = Foo('test').run(result) |
---|
552 | n/a | self.assertIs(retval, result) |
---|
553 | n/a | |
---|
554 | n/a | |
---|
555 | n/a | # "The same effect [as method run] may be had by simply calling the |
---|
556 | n/a | # TestCase instance." |
---|
557 | n/a | def test_call__invoking_an_instance_delegates_to_run(self): |
---|
558 | n/a | resultIn = unittest.TestResult() |
---|
559 | n/a | resultOut = unittest.TestResult() |
---|
560 | n/a | |
---|
561 | n/a | class Foo(unittest.TestCase): |
---|
562 | n/a | def test(self): |
---|
563 | n/a | pass |
---|
564 | n/a | |
---|
565 | n/a | def run(self, result): |
---|
566 | n/a | self.assertIs(result, resultIn) |
---|
567 | n/a | return resultOut |
---|
568 | n/a | |
---|
569 | n/a | retval = Foo('test')(resultIn) |
---|
570 | n/a | |
---|
571 | n/a | self.assertIs(retval, resultOut) |
---|
572 | n/a | |
---|
573 | n/a | |
---|
574 | n/a | def testShortDescriptionWithoutDocstring(self): |
---|
575 | n/a | self.assertIsNone(self.shortDescription()) |
---|
576 | n/a | |
---|
577 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |
---|
578 | n/a | "Docstrings are omitted with -O2 and above") |
---|
579 | n/a | def testShortDescriptionWithOneLineDocstring(self): |
---|
580 | n/a | """Tests shortDescription() for a method with a docstring.""" |
---|
581 | n/a | self.assertEqual( |
---|
582 | n/a | self.shortDescription(), |
---|
583 | n/a | 'Tests shortDescription() for a method with a docstring.') |
---|
584 | n/a | |
---|
585 | n/a | @unittest.skipIf(sys.flags.optimize >= 2, |
---|
586 | n/a | "Docstrings are omitted with -O2 and above") |
---|
587 | n/a | def testShortDescriptionWithMultiLineDocstring(self): |
---|
588 | n/a | """Tests shortDescription() for a method with a longer docstring. |
---|
589 | n/a | |
---|
590 | n/a | This method ensures that only the first line of a docstring is |
---|
591 | n/a | returned used in the short description, no matter how long the |
---|
592 | n/a | whole thing is. |
---|
593 | n/a | """ |
---|
594 | n/a | self.assertEqual( |
---|
595 | n/a | self.shortDescription(), |
---|
596 | n/a | 'Tests shortDescription() for a method with a longer ' |
---|
597 | n/a | 'docstring.') |
---|
598 | n/a | |
---|
599 | n/a | def testAddTypeEqualityFunc(self): |
---|
600 | n/a | class SadSnake(object): |
---|
601 | n/a | """Dummy class for test_addTypeEqualityFunc.""" |
---|
602 | n/a | s1, s2 = SadSnake(), SadSnake() |
---|
603 | n/a | self.assertFalse(s1 == s2) |
---|
604 | n/a | def AllSnakesCreatedEqual(a, b, msg=None): |
---|
605 | n/a | return type(a) == type(b) == SadSnake |
---|
606 | n/a | self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual) |
---|
607 | n/a | self.assertEqual(s1, s2) |
---|
608 | n/a | # No this doesn't clean up and remove the SadSnake equality func |
---|
609 | n/a | # from this TestCase instance but since its a local nothing else |
---|
610 | n/a | # will ever notice that. |
---|
611 | n/a | |
---|
612 | n/a | def testAssertIs(self): |
---|
613 | n/a | thing = object() |
---|
614 | n/a | self.assertIs(thing, thing) |
---|
615 | n/a | self.assertRaises(self.failureException, self.assertIs, thing, object()) |
---|
616 | n/a | |
---|
617 | n/a | def testAssertIsNot(self): |
---|
618 | n/a | thing = object() |
---|
619 | n/a | self.assertIsNot(thing, object()) |
---|
620 | n/a | self.assertRaises(self.failureException, self.assertIsNot, thing, thing) |
---|
621 | n/a | |
---|
622 | n/a | def testAssertIsInstance(self): |
---|
623 | n/a | thing = [] |
---|
624 | n/a | self.assertIsInstance(thing, list) |
---|
625 | n/a | self.assertRaises(self.failureException, self.assertIsInstance, |
---|
626 | n/a | thing, dict) |
---|
627 | n/a | |
---|
628 | n/a | def testAssertNotIsInstance(self): |
---|
629 | n/a | thing = [] |
---|
630 | n/a | self.assertNotIsInstance(thing, dict) |
---|
631 | n/a | self.assertRaises(self.failureException, self.assertNotIsInstance, |
---|
632 | n/a | thing, list) |
---|
633 | n/a | |
---|
634 | n/a | def testAssertIn(self): |
---|
635 | n/a | animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'} |
---|
636 | n/a | |
---|
637 | n/a | self.assertIn('a', 'abc') |
---|
638 | n/a | self.assertIn(2, [1, 2, 3]) |
---|
639 | n/a | self.assertIn('monkey', animals) |
---|
640 | n/a | |
---|
641 | n/a | self.assertNotIn('d', 'abc') |
---|
642 | n/a | self.assertNotIn(0, [1, 2, 3]) |
---|
643 | n/a | self.assertNotIn('otter', animals) |
---|
644 | n/a | |
---|
645 | n/a | self.assertRaises(self.failureException, self.assertIn, 'x', 'abc') |
---|
646 | n/a | self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3]) |
---|
647 | n/a | self.assertRaises(self.failureException, self.assertIn, 'elephant', |
---|
648 | n/a | animals) |
---|
649 | n/a | |
---|
650 | n/a | self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc') |
---|
651 | n/a | self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3]) |
---|
652 | n/a | self.assertRaises(self.failureException, self.assertNotIn, 'cow', |
---|
653 | n/a | animals) |
---|
654 | n/a | |
---|
655 | n/a | def testAssertDictContainsSubset(self): |
---|
656 | n/a | with warnings.catch_warnings(): |
---|
657 | n/a | warnings.simplefilter("ignore", DeprecationWarning) |
---|
658 | n/a | |
---|
659 | n/a | self.assertDictContainsSubset({}, {}) |
---|
660 | n/a | self.assertDictContainsSubset({}, {'a': 1}) |
---|
661 | n/a | self.assertDictContainsSubset({'a': 1}, {'a': 1}) |
---|
662 | n/a | self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2}) |
---|
663 | n/a | self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2}) |
---|
664 | n/a | |
---|
665 | n/a | with self.assertRaises(self.failureException): |
---|
666 | n/a | self.assertDictContainsSubset({1: "one"}, {}) |
---|
667 | n/a | |
---|
668 | n/a | with self.assertRaises(self.failureException): |
---|
669 | n/a | self.assertDictContainsSubset({'a': 2}, {'a': 1}) |
---|
670 | n/a | |
---|
671 | n/a | with self.assertRaises(self.failureException): |
---|
672 | n/a | self.assertDictContainsSubset({'c': 1}, {'a': 1}) |
---|
673 | n/a | |
---|
674 | n/a | with self.assertRaises(self.failureException): |
---|
675 | n/a | self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) |
---|
676 | n/a | |
---|
677 | n/a | with self.assertRaises(self.failureException): |
---|
678 | n/a | self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) |
---|
679 | n/a | |
---|
680 | n/a | one = ''.join(chr(i) for i in range(255)) |
---|
681 | n/a | # this used to cause a UnicodeDecodeError constructing the failure msg |
---|
682 | n/a | with self.assertRaises(self.failureException): |
---|
683 | n/a | self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'}) |
---|
684 | n/a | |
---|
685 | n/a | def testAssertEqual(self): |
---|
686 | n/a | equal_pairs = [ |
---|
687 | n/a | ((), ()), |
---|
688 | n/a | ({}, {}), |
---|
689 | n/a | ([], []), |
---|
690 | n/a | (set(), set()), |
---|
691 | n/a | (frozenset(), frozenset())] |
---|
692 | n/a | for a, b in equal_pairs: |
---|
693 | n/a | # This mess of try excepts is to test the assertEqual behavior |
---|
694 | n/a | # itself. |
---|
695 | n/a | try: |
---|
696 | n/a | self.assertEqual(a, b) |
---|
697 | n/a | except self.failureException: |
---|
698 | n/a | self.fail('assertEqual(%r, %r) failed' % (a, b)) |
---|
699 | n/a | try: |
---|
700 | n/a | self.assertEqual(a, b, msg='foo') |
---|
701 | n/a | except self.failureException: |
---|
702 | n/a | self.fail('assertEqual(%r, %r) with msg= failed' % (a, b)) |
---|
703 | n/a | try: |
---|
704 | n/a | self.assertEqual(a, b, 'foo') |
---|
705 | n/a | except self.failureException: |
---|
706 | n/a | self.fail('assertEqual(%r, %r) with third parameter failed' % |
---|
707 | n/a | (a, b)) |
---|
708 | n/a | |
---|
709 | n/a | unequal_pairs = [ |
---|
710 | n/a | ((), []), |
---|
711 | n/a | ({}, set()), |
---|
712 | n/a | (set([4,1]), frozenset([4,2])), |
---|
713 | n/a | (frozenset([4,5]), set([2,3])), |
---|
714 | n/a | (set([3,4]), set([5,4]))] |
---|
715 | n/a | for a, b in unequal_pairs: |
---|
716 | n/a | self.assertRaises(self.failureException, self.assertEqual, a, b) |
---|
717 | n/a | self.assertRaises(self.failureException, self.assertEqual, a, b, |
---|
718 | n/a | 'foo') |
---|
719 | n/a | self.assertRaises(self.failureException, self.assertEqual, a, b, |
---|
720 | n/a | msg='foo') |
---|
721 | n/a | |
---|
722 | n/a | def testEquality(self): |
---|
723 | n/a | self.assertListEqual([], []) |
---|
724 | n/a | self.assertTupleEqual((), ()) |
---|
725 | n/a | self.assertSequenceEqual([], ()) |
---|
726 | n/a | |
---|
727 | n/a | a = [0, 'a', []] |
---|
728 | n/a | b = [] |
---|
729 | n/a | self.assertRaises(unittest.TestCase.failureException, |
---|
730 | n/a | self.assertListEqual, a, b) |
---|
731 | n/a | self.assertRaises(unittest.TestCase.failureException, |
---|
732 | n/a | self.assertListEqual, tuple(a), tuple(b)) |
---|
733 | n/a | self.assertRaises(unittest.TestCase.failureException, |
---|
734 | n/a | self.assertSequenceEqual, a, tuple(b)) |
---|
735 | n/a | |
---|
736 | n/a | b.extend(a) |
---|
737 | n/a | self.assertListEqual(a, b) |
---|
738 | n/a | self.assertTupleEqual(tuple(a), tuple(b)) |
---|
739 | n/a | self.assertSequenceEqual(a, tuple(b)) |
---|
740 | n/a | self.assertSequenceEqual(tuple(a), b) |
---|
741 | n/a | |
---|
742 | n/a | self.assertRaises(self.failureException, self.assertListEqual, |
---|
743 | n/a | a, tuple(b)) |
---|
744 | n/a | self.assertRaises(self.failureException, self.assertTupleEqual, |
---|
745 | n/a | tuple(a), b) |
---|
746 | n/a | self.assertRaises(self.failureException, self.assertListEqual, None, b) |
---|
747 | n/a | self.assertRaises(self.failureException, self.assertTupleEqual, None, |
---|
748 | n/a | tuple(b)) |
---|
749 | n/a | self.assertRaises(self.failureException, self.assertSequenceEqual, |
---|
750 | n/a | None, tuple(b)) |
---|
751 | n/a | self.assertRaises(self.failureException, self.assertListEqual, 1, 1) |
---|
752 | n/a | self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1) |
---|
753 | n/a | self.assertRaises(self.failureException, self.assertSequenceEqual, |
---|
754 | n/a | 1, 1) |
---|
755 | n/a | |
---|
756 | n/a | self.assertDictEqual({}, {}) |
---|
757 | n/a | |
---|
758 | n/a | c = { 'x': 1 } |
---|
759 | n/a | d = {} |
---|
760 | n/a | self.assertRaises(unittest.TestCase.failureException, |
---|
761 | n/a | self.assertDictEqual, c, d) |
---|
762 | n/a | |
---|
763 | n/a | d.update(c) |
---|
764 | n/a | self.assertDictEqual(c, d) |
---|
765 | n/a | |
---|
766 | n/a | d['x'] = 0 |
---|
767 | n/a | self.assertRaises(unittest.TestCase.failureException, |
---|
768 | n/a | self.assertDictEqual, c, d, 'These are unequal') |
---|
769 | n/a | |
---|
770 | n/a | self.assertRaises(self.failureException, self.assertDictEqual, None, d) |
---|
771 | n/a | self.assertRaises(self.failureException, self.assertDictEqual, [], d) |
---|
772 | n/a | self.assertRaises(self.failureException, self.assertDictEqual, 1, 1) |
---|
773 | n/a | |
---|
774 | n/a | def testAssertSequenceEqualMaxDiff(self): |
---|
775 | n/a | self.assertEqual(self.maxDiff, 80*8) |
---|
776 | n/a | seq1 = 'a' + 'x' * 80**2 |
---|
777 | n/a | seq2 = 'b' + 'x' * 80**2 |
---|
778 | n/a | diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), |
---|
779 | n/a | pprint.pformat(seq2).splitlines())) |
---|
780 | n/a | # the +1 is the leading \n added by assertSequenceEqual |
---|
781 | n/a | omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,) |
---|
782 | n/a | |
---|
783 | n/a | self.maxDiff = len(diff)//2 |
---|
784 | n/a | try: |
---|
785 | n/a | |
---|
786 | n/a | self.assertSequenceEqual(seq1, seq2) |
---|
787 | n/a | except self.failureException as e: |
---|
788 | n/a | msg = e.args[0] |
---|
789 | n/a | else: |
---|
790 | n/a | self.fail('assertSequenceEqual did not fail.') |
---|
791 | n/a | self.assertLess(len(msg), len(diff)) |
---|
792 | n/a | self.assertIn(omitted, msg) |
---|
793 | n/a | |
---|
794 | n/a | self.maxDiff = len(diff) * 2 |
---|
795 | n/a | try: |
---|
796 | n/a | self.assertSequenceEqual(seq1, seq2) |
---|
797 | n/a | except self.failureException as e: |
---|
798 | n/a | msg = e.args[0] |
---|
799 | n/a | else: |
---|
800 | n/a | self.fail('assertSequenceEqual did not fail.') |
---|
801 | n/a | self.assertGreater(len(msg), len(diff)) |
---|
802 | n/a | self.assertNotIn(omitted, msg) |
---|
803 | n/a | |
---|
804 | n/a | self.maxDiff = None |
---|
805 | n/a | try: |
---|
806 | n/a | self.assertSequenceEqual(seq1, seq2) |
---|
807 | n/a | except self.failureException as e: |
---|
808 | n/a | msg = e.args[0] |
---|
809 | n/a | else: |
---|
810 | n/a | self.fail('assertSequenceEqual did not fail.') |
---|
811 | n/a | self.assertGreater(len(msg), len(diff)) |
---|
812 | n/a | self.assertNotIn(omitted, msg) |
---|
813 | n/a | |
---|
814 | n/a | def testTruncateMessage(self): |
---|
815 | n/a | self.maxDiff = 1 |
---|
816 | n/a | message = self._truncateMessage('foo', 'bar') |
---|
817 | n/a | omitted = unittest.case.DIFF_OMITTED % len('bar') |
---|
818 | n/a | self.assertEqual(message, 'foo' + omitted) |
---|
819 | n/a | |
---|
820 | n/a | self.maxDiff = None |
---|
821 | n/a | message = self._truncateMessage('foo', 'bar') |
---|
822 | n/a | self.assertEqual(message, 'foobar') |
---|
823 | n/a | |
---|
824 | n/a | self.maxDiff = 4 |
---|
825 | n/a | message = self._truncateMessage('foo', 'bar') |
---|
826 | n/a | self.assertEqual(message, 'foobar') |
---|
827 | n/a | |
---|
828 | n/a | def testAssertDictEqualTruncates(self): |
---|
829 | n/a | test = unittest.TestCase('assertEqual') |
---|
830 | n/a | def truncate(msg, diff): |
---|
831 | n/a | return 'foo' |
---|
832 | n/a | test._truncateMessage = truncate |
---|
833 | n/a | try: |
---|
834 | n/a | test.assertDictEqual({}, {1: 0}) |
---|
835 | n/a | except self.failureException as e: |
---|
836 | n/a | self.assertEqual(str(e), 'foo') |
---|
837 | n/a | else: |
---|
838 | n/a | self.fail('assertDictEqual did not fail') |
---|
839 | n/a | |
---|
840 | n/a | def testAssertMultiLineEqualTruncates(self): |
---|
841 | n/a | test = unittest.TestCase('assertEqual') |
---|
842 | n/a | def truncate(msg, diff): |
---|
843 | n/a | return 'foo' |
---|
844 | n/a | test._truncateMessage = truncate |
---|
845 | n/a | try: |
---|
846 | n/a | test.assertMultiLineEqual('foo', 'bar') |
---|
847 | n/a | except self.failureException as e: |
---|
848 | n/a | self.assertEqual(str(e), 'foo') |
---|
849 | n/a | else: |
---|
850 | n/a | self.fail('assertMultiLineEqual did not fail') |
---|
851 | n/a | |
---|
852 | n/a | def testAssertEqual_diffThreshold(self): |
---|
853 | n/a | # check threshold value |
---|
854 | n/a | self.assertEqual(self._diffThreshold, 2**16) |
---|
855 | n/a | # disable madDiff to get diff markers |
---|
856 | n/a | self.maxDiff = None |
---|
857 | n/a | |
---|
858 | n/a | # set a lower threshold value and add a cleanup to restore it |
---|
859 | n/a | old_threshold = self._diffThreshold |
---|
860 | n/a | self._diffThreshold = 2**5 |
---|
861 | n/a | self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) |
---|
862 | n/a | |
---|
863 | n/a | # under the threshold: diff marker (^) in error message |
---|
864 | n/a | s = 'x' * (2**4) |
---|
865 | n/a | with self.assertRaises(self.failureException) as cm: |
---|
866 | n/a | self.assertEqual(s + 'a', s + 'b') |
---|
867 | n/a | self.assertIn('^', str(cm.exception)) |
---|
868 | n/a | self.assertEqual(s + 'a', s + 'a') |
---|
869 | n/a | |
---|
870 | n/a | # over the threshold: diff not used and marker (^) not in error message |
---|
871 | n/a | s = 'x' * (2**6) |
---|
872 | n/a | # if the path that uses difflib is taken, _truncateMessage will be |
---|
873 | n/a | # called -- replace it with explodingTruncation to verify that this |
---|
874 | n/a | # doesn't happen |
---|
875 | n/a | def explodingTruncation(message, diff): |
---|
876 | n/a | raise SystemError('this should not be raised') |
---|
877 | n/a | old_truncate = self._truncateMessage |
---|
878 | n/a | self._truncateMessage = explodingTruncation |
---|
879 | n/a | self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate)) |
---|
880 | n/a | |
---|
881 | n/a | s1, s2 = s + 'a', s + 'b' |
---|
882 | n/a | with self.assertRaises(self.failureException) as cm: |
---|
883 | n/a | self.assertEqual(s1, s2) |
---|
884 | n/a | self.assertNotIn('^', str(cm.exception)) |
---|
885 | n/a | self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2)) |
---|
886 | n/a | self.assertEqual(s + 'a', s + 'a') |
---|
887 | n/a | |
---|
888 | n/a | def testAssertEqual_shorten(self): |
---|
889 | n/a | # set a lower threshold value and add a cleanup to restore it |
---|
890 | n/a | old_threshold = self._diffThreshold |
---|
891 | n/a | self._diffThreshold = 0 |
---|
892 | n/a | self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) |
---|
893 | n/a | |
---|
894 | n/a | s = 'x' * 100 |
---|
895 | n/a | s1, s2 = s + 'a', s + 'b' |
---|
896 | n/a | with self.assertRaises(self.failureException) as cm: |
---|
897 | n/a | self.assertEqual(s1, s2) |
---|
898 | n/a | c = 'xxxx[35 chars]' + 'x' * 61 |
---|
899 | n/a | self.assertEqual(str(cm.exception), "'%sa' != '%sb'" % (c, c)) |
---|
900 | n/a | self.assertEqual(s + 'a', s + 'a') |
---|
901 | n/a | |
---|
902 | n/a | p = 'y' * 50 |
---|
903 | n/a | s1, s2 = s + 'a' + p, s + 'b' + p |
---|
904 | n/a | with self.assertRaises(self.failureException) as cm: |
---|
905 | n/a | self.assertEqual(s1, s2) |
---|
906 | n/a | c = 'xxxx[85 chars]xxxxxxxxxxx' |
---|
907 | n/a | self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, p, c, p)) |
---|
908 | n/a | |
---|
909 | n/a | p = 'y' * 100 |
---|
910 | n/a | s1, s2 = s + 'a' + p, s + 'b' + p |
---|
911 | n/a | with self.assertRaises(self.failureException) as cm: |
---|
912 | n/a | self.assertEqual(s1, s2) |
---|
913 | n/a | c = 'xxxx[91 chars]xxxxx' |
---|
914 | n/a | d = 'y' * 40 + '[56 chars]yyyy' |
---|
915 | n/a | self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, d, c, d)) |
---|
916 | n/a | |
---|
917 | n/a | def testAssertCountEqual(self): |
---|
918 | n/a | a = object() |
---|
919 | n/a | self.assertCountEqual([1, 2, 3], [3, 2, 1]) |
---|
920 | n/a | self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) |
---|
921 | n/a | self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2)) |
---|
922 | n/a | self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"]) |
---|
923 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
924 | n/a | [1, 2] + [3] * 100, [1] * 100 + [2, 3]) |
---|
925 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
926 | n/a | [1, "2", "a", "a"], ["a", "2", True, 1]) |
---|
927 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
928 | n/a | [10], [10, 11]) |
---|
929 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
930 | n/a | [10, 11], [10]) |
---|
931 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
932 | n/a | [10, 11, 10], [10, 11]) |
---|
933 | n/a | |
---|
934 | n/a | # Test that sequences of unhashable objects can be tested for sameness: |
---|
935 | n/a | self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]]) |
---|
936 | n/a | # Test that iterator of unhashable objects can be tested for sameness: |
---|
937 | n/a | self.assertCountEqual(iter([1, 2, [], 3, 4]), |
---|
938 | n/a | iter([1, 2, [], 3, 4])) |
---|
939 | n/a | |
---|
940 | n/a | # hashable types, but not orderable |
---|
941 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
942 | n/a | [], [divmod, 'x', 1, 5j, 2j, frozenset()]) |
---|
943 | n/a | # comparing dicts |
---|
944 | n/a | self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}]) |
---|
945 | n/a | # comparing heterogenous non-hashable sequences |
---|
946 | n/a | self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1]) |
---|
947 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
948 | n/a | [], [divmod, [], 'x', 1, 5j, 2j, set()]) |
---|
949 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
950 | n/a | [[1]], [[2]]) |
---|
951 | n/a | |
---|
952 | n/a | # Same elements, but not same sequence length |
---|
953 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
954 | n/a | [1, 1, 2], [2, 1]) |
---|
955 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
956 | n/a | [1, 1, "2", "a", "a"], ["2", "2", True, "a"]) |
---|
957 | n/a | self.assertRaises(self.failureException, self.assertCountEqual, |
---|
958 | n/a | [1, {'b': 2}, None, True], [{'b': 2}, True, None]) |
---|
959 | n/a | |
---|
960 | n/a | # Same elements which don't reliably compare, in |
---|
961 | n/a | # different order, see issue 10242 |
---|
962 | n/a | a = [{2,4}, {1,2}] |
---|
963 | n/a | b = a[::-1] |
---|
964 | n/a | self.assertCountEqual(a, b) |
---|
965 | n/a | |
---|
966 | n/a | # test utility functions supporting assertCountEqual() |
---|
967 | n/a | |
---|
968 | n/a | diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce')) |
---|
969 | n/a | expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} |
---|
970 | n/a | self.assertEqual(diffs, expected) |
---|
971 | n/a | |
---|
972 | n/a | diffs = unittest.util._count_diff_all_purpose([[]], []) |
---|
973 | n/a | self.assertEqual(diffs, [(1, 0, [])]) |
---|
974 | n/a | |
---|
975 | n/a | diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce')) |
---|
976 | n/a | expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} |
---|
977 | n/a | self.assertEqual(diffs, expected) |
---|
978 | n/a | |
---|
979 | n/a | def testAssertSetEqual(self): |
---|
980 | n/a | set1 = set() |
---|
981 | n/a | set2 = set() |
---|
982 | n/a | self.assertSetEqual(set1, set2) |
---|
983 | n/a | |
---|
984 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, None, set2) |
---|
985 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, [], set2) |
---|
986 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set1, None) |
---|
987 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set1, []) |
---|
988 | n/a | |
---|
989 | n/a | set1 = set(['a']) |
---|
990 | n/a | set2 = set() |
---|
991 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
---|
992 | n/a | |
---|
993 | n/a | set1 = set(['a']) |
---|
994 | n/a | set2 = set(['a']) |
---|
995 | n/a | self.assertSetEqual(set1, set2) |
---|
996 | n/a | |
---|
997 | n/a | set1 = set(['a']) |
---|
998 | n/a | set2 = set(['a', 'b']) |
---|
999 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
---|
1000 | n/a | |
---|
1001 | n/a | set1 = set(['a']) |
---|
1002 | n/a | set2 = frozenset(['a', 'b']) |
---|
1003 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
---|
1004 | n/a | |
---|
1005 | n/a | set1 = set(['a', 'b']) |
---|
1006 | n/a | set2 = frozenset(['a', 'b']) |
---|
1007 | n/a | self.assertSetEqual(set1, set2) |
---|
1008 | n/a | |
---|
1009 | n/a | set1 = set() |
---|
1010 | n/a | set2 = "foo" |
---|
1011 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
---|
1012 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set2, set1) |
---|
1013 | n/a | |
---|
1014 | n/a | # make sure any string formatting is tuple-safe |
---|
1015 | n/a | set1 = set([(0, 1), (2, 3)]) |
---|
1016 | n/a | set2 = set([(4, 5)]) |
---|
1017 | n/a | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
---|
1018 | n/a | |
---|
1019 | n/a | def testInequality(self): |
---|
1020 | n/a | # Try ints |
---|
1021 | n/a | self.assertGreater(2, 1) |
---|
1022 | n/a | self.assertGreaterEqual(2, 1) |
---|
1023 | n/a | self.assertGreaterEqual(1, 1) |
---|
1024 | n/a | self.assertLess(1, 2) |
---|
1025 | n/a | self.assertLessEqual(1, 2) |
---|
1026 | n/a | self.assertLessEqual(1, 1) |
---|
1027 | n/a | self.assertRaises(self.failureException, self.assertGreater, 1, 2) |
---|
1028 | n/a | self.assertRaises(self.failureException, self.assertGreater, 1, 1) |
---|
1029 | n/a | self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2) |
---|
1030 | n/a | self.assertRaises(self.failureException, self.assertLess, 2, 1) |
---|
1031 | n/a | self.assertRaises(self.failureException, self.assertLess, 1, 1) |
---|
1032 | n/a | self.assertRaises(self.failureException, self.assertLessEqual, 2, 1) |
---|
1033 | n/a | |
---|
1034 | n/a | # Try Floats |
---|
1035 | n/a | self.assertGreater(1.1, 1.0) |
---|
1036 | n/a | self.assertGreaterEqual(1.1, 1.0) |
---|
1037 | n/a | self.assertGreaterEqual(1.0, 1.0) |
---|
1038 | n/a | self.assertLess(1.0, 1.1) |
---|
1039 | n/a | self.assertLessEqual(1.0, 1.1) |
---|
1040 | n/a | self.assertLessEqual(1.0, 1.0) |
---|
1041 | n/a | self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1) |
---|
1042 | n/a | self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0) |
---|
1043 | n/a | self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1) |
---|
1044 | n/a | self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0) |
---|
1045 | n/a | self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0) |
---|
1046 | n/a | self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0) |
---|
1047 | n/a | |
---|
1048 | n/a | # Try Strings |
---|
1049 | n/a | self.assertGreater('bug', 'ant') |
---|
1050 | n/a | self.assertGreaterEqual('bug', 'ant') |
---|
1051 | n/a | self.assertGreaterEqual('ant', 'ant') |
---|
1052 | n/a | self.assertLess('ant', 'bug') |
---|
1053 | n/a | self.assertLessEqual('ant', 'bug') |
---|
1054 | n/a | self.assertLessEqual('ant', 'ant') |
---|
1055 | n/a | self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') |
---|
1056 | n/a | self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') |
---|
1057 | n/a | self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug') |
---|
1058 | n/a | self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') |
---|
1059 | n/a | self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') |
---|
1060 | n/a | self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') |
---|
1061 | n/a | |
---|
1062 | n/a | # Try bytes |
---|
1063 | n/a | self.assertGreater(b'bug', b'ant') |
---|
1064 | n/a | self.assertGreaterEqual(b'bug', b'ant') |
---|
1065 | n/a | self.assertGreaterEqual(b'ant', b'ant') |
---|
1066 | n/a | self.assertLess(b'ant', b'bug') |
---|
1067 | n/a | self.assertLessEqual(b'ant', b'bug') |
---|
1068 | n/a | self.assertLessEqual(b'ant', b'ant') |
---|
1069 | n/a | self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug') |
---|
1070 | n/a | self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant') |
---|
1071 | n/a | self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant', |
---|
1072 | n/a | b'bug') |
---|
1073 | n/a | self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant') |
---|
1074 | n/a | self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant') |
---|
1075 | n/a | self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant') |
---|
1076 | n/a | |
---|
1077 | n/a | def testAssertMultiLineEqual(self): |
---|
1078 | n/a | sample_text = """\ |
---|
1079 | n/a | http://www.python.org/doc/2.3/lib/module-unittest.html |
---|
1080 | n/a | test case |
---|
1081 | n/a | A test case is the smallest unit of testing. [...] |
---|
1082 | n/a | """ |
---|
1083 | n/a | revised_sample_text = """\ |
---|
1084 | n/a | http://www.python.org/doc/2.4.1/lib/module-unittest.html |
---|
1085 | n/a | test case |
---|
1086 | n/a | A test case is the smallest unit of testing. [...] You may provide your |
---|
1087 | n/a | own implementation that does not subclass from TestCase, of course. |
---|
1088 | n/a | """ |
---|
1089 | n/a | sample_text_error = """\ |
---|
1090 | n/a | - http://www.python.org/doc/2.3/lib/module-unittest.html |
---|
1091 | n/a | ? ^ |
---|
1092 | n/a | + http://www.python.org/doc/2.4.1/lib/module-unittest.html |
---|
1093 | n/a | ? ^^^ |
---|
1094 | n/a | test case |
---|
1095 | n/a | - A test case is the smallest unit of testing. [...] |
---|
1096 | n/a | + A test case is the smallest unit of testing. [...] You may provide your |
---|
1097 | n/a | ? +++++++++++++++++++++ |
---|
1098 | n/a | + own implementation that does not subclass from TestCase, of course. |
---|
1099 | n/a | """ |
---|
1100 | n/a | self.maxDiff = None |
---|
1101 | n/a | try: |
---|
1102 | n/a | self.assertMultiLineEqual(sample_text, revised_sample_text) |
---|
1103 | n/a | except self.failureException as e: |
---|
1104 | n/a | # need to remove the first line of the error message |
---|
1105 | n/a | error = str(e).split('\n', 1)[1] |
---|
1106 | n/a | self.assertEqual(sample_text_error, error) |
---|
1107 | n/a | |
---|
1108 | n/a | def testAssertEqualSingleLine(self): |
---|
1109 | n/a | sample_text = "laden swallows fly slowly" |
---|
1110 | n/a | revised_sample_text = "unladen swallows fly quickly" |
---|
1111 | n/a | sample_text_error = """\ |
---|
1112 | n/a | - laden swallows fly slowly |
---|
1113 | n/a | ? ^^^^ |
---|
1114 | n/a | + unladen swallows fly quickly |
---|
1115 | n/a | ? ++ ^^^^^ |
---|
1116 | n/a | """ |
---|
1117 | n/a | try: |
---|
1118 | n/a | self.assertEqual(sample_text, revised_sample_text) |
---|
1119 | n/a | except self.failureException as e: |
---|
1120 | n/a | # need to remove the first line of the error message |
---|
1121 | n/a | error = str(e).split('\n', 1)[1] |
---|
1122 | n/a | self.assertEqual(sample_text_error, error) |
---|
1123 | n/a | |
---|
1124 | n/a | def testEqualityBytesWarning(self): |
---|
1125 | n/a | if sys.flags.bytes_warning: |
---|
1126 | n/a | def bytes_warning(): |
---|
1127 | n/a | return self.assertWarnsRegex(BytesWarning, |
---|
1128 | n/a | 'Comparison between bytes and string') |
---|
1129 | n/a | else: |
---|
1130 | n/a | def bytes_warning(): |
---|
1131 | n/a | return contextlib.ExitStack() |
---|
1132 | n/a | |
---|
1133 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1134 | n/a | self.assertEqual('a', b'a') |
---|
1135 | n/a | with bytes_warning(): |
---|
1136 | n/a | self.assertNotEqual('a', b'a') |
---|
1137 | n/a | |
---|
1138 | n/a | a = [0, 'a'] |
---|
1139 | n/a | b = [0, b'a'] |
---|
1140 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1141 | n/a | self.assertListEqual(a, b) |
---|
1142 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1143 | n/a | self.assertTupleEqual(tuple(a), tuple(b)) |
---|
1144 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1145 | n/a | self.assertSequenceEqual(a, tuple(b)) |
---|
1146 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1147 | n/a | self.assertSequenceEqual(tuple(a), b) |
---|
1148 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1149 | n/a | self.assertSequenceEqual('a', b'a') |
---|
1150 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1151 | n/a | self.assertSetEqual(set(a), set(b)) |
---|
1152 | n/a | |
---|
1153 | n/a | with self.assertRaises(self.failureException): |
---|
1154 | n/a | self.assertListEqual(a, tuple(b)) |
---|
1155 | n/a | with self.assertRaises(self.failureException): |
---|
1156 | n/a | self.assertTupleEqual(tuple(a), b) |
---|
1157 | n/a | |
---|
1158 | n/a | a = [0, b'a'] |
---|
1159 | n/a | b = [0] |
---|
1160 | n/a | with self.assertRaises(self.failureException): |
---|
1161 | n/a | self.assertListEqual(a, b) |
---|
1162 | n/a | with self.assertRaises(self.failureException): |
---|
1163 | n/a | self.assertTupleEqual(tuple(a), tuple(b)) |
---|
1164 | n/a | with self.assertRaises(self.failureException): |
---|
1165 | n/a | self.assertSequenceEqual(a, tuple(b)) |
---|
1166 | n/a | with self.assertRaises(self.failureException): |
---|
1167 | n/a | self.assertSequenceEqual(tuple(a), b) |
---|
1168 | n/a | with self.assertRaises(self.failureException): |
---|
1169 | n/a | self.assertSetEqual(set(a), set(b)) |
---|
1170 | n/a | |
---|
1171 | n/a | a = [0] |
---|
1172 | n/a | b = [0, b'a'] |
---|
1173 | n/a | with self.assertRaises(self.failureException): |
---|
1174 | n/a | self.assertListEqual(a, b) |
---|
1175 | n/a | with self.assertRaises(self.failureException): |
---|
1176 | n/a | self.assertTupleEqual(tuple(a), tuple(b)) |
---|
1177 | n/a | with self.assertRaises(self.failureException): |
---|
1178 | n/a | self.assertSequenceEqual(a, tuple(b)) |
---|
1179 | n/a | with self.assertRaises(self.failureException): |
---|
1180 | n/a | self.assertSequenceEqual(tuple(a), b) |
---|
1181 | n/a | with self.assertRaises(self.failureException): |
---|
1182 | n/a | self.assertSetEqual(set(a), set(b)) |
---|
1183 | n/a | |
---|
1184 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1185 | n/a | self.assertDictEqual({'a': 0}, {b'a': 0}) |
---|
1186 | n/a | with self.assertRaises(self.failureException): |
---|
1187 | n/a | self.assertDictEqual({}, {b'a': 0}) |
---|
1188 | n/a | with self.assertRaises(self.failureException): |
---|
1189 | n/a | self.assertDictEqual({b'a': 0}, {}) |
---|
1190 | n/a | |
---|
1191 | n/a | with self.assertRaises(self.failureException): |
---|
1192 | n/a | self.assertCountEqual([b'a', b'a'], [b'a', b'a', b'a']) |
---|
1193 | n/a | with bytes_warning(): |
---|
1194 | n/a | self.assertCountEqual(['a', b'a'], ['a', b'a']) |
---|
1195 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1196 | n/a | self.assertCountEqual(['a', 'a'], [b'a', b'a']) |
---|
1197 | n/a | with bytes_warning(), self.assertRaises(self.failureException): |
---|
1198 | n/a | self.assertCountEqual(['a', 'a', []], [b'a', b'a', []]) |
---|
1199 | n/a | |
---|
1200 | n/a | def testAssertIsNone(self): |
---|
1201 | n/a | self.assertIsNone(None) |
---|
1202 | n/a | self.assertRaises(self.failureException, self.assertIsNone, False) |
---|
1203 | n/a | self.assertIsNotNone('DjZoPloGears on Rails') |
---|
1204 | n/a | self.assertRaises(self.failureException, self.assertIsNotNone, None) |
---|
1205 | n/a | |
---|
1206 | n/a | def testAssertRegex(self): |
---|
1207 | n/a | self.assertRegex('asdfabasdf', r'ab+') |
---|
1208 | n/a | self.assertRaises(self.failureException, self.assertRegex, |
---|
1209 | n/a | 'saaas', r'aaaa') |
---|
1210 | n/a | |
---|
1211 | n/a | def testAssertRaisesCallable(self): |
---|
1212 | n/a | class ExceptionMock(Exception): |
---|
1213 | n/a | pass |
---|
1214 | n/a | def Stub(): |
---|
1215 | n/a | raise ExceptionMock('We expect') |
---|
1216 | n/a | self.assertRaises(ExceptionMock, Stub) |
---|
1217 | n/a | # A tuple of exception classes is accepted |
---|
1218 | n/a | self.assertRaises((ValueError, ExceptionMock), Stub) |
---|
1219 | n/a | # *args and **kwargs also work |
---|
1220 | n/a | self.assertRaises(ValueError, int, '19', base=8) |
---|
1221 | n/a | # Failure when no exception is raised |
---|
1222 | n/a | with self.assertRaises(self.failureException): |
---|
1223 | n/a | self.assertRaises(ExceptionMock, lambda: 0) |
---|
1224 | n/a | # Failure when the function is None |
---|
1225 | n/a | with self.assertWarns(DeprecationWarning): |
---|
1226 | n/a | self.assertRaises(ExceptionMock, None) |
---|
1227 | n/a | # Failure when another exception is raised |
---|
1228 | n/a | with self.assertRaises(ExceptionMock): |
---|
1229 | n/a | self.assertRaises(ValueError, Stub) |
---|
1230 | n/a | |
---|
1231 | n/a | def testAssertRaisesContext(self): |
---|
1232 | n/a | class ExceptionMock(Exception): |
---|
1233 | n/a | pass |
---|
1234 | n/a | def Stub(): |
---|
1235 | n/a | raise ExceptionMock('We expect') |
---|
1236 | n/a | with self.assertRaises(ExceptionMock): |
---|
1237 | n/a | Stub() |
---|
1238 | n/a | # A tuple of exception classes is accepted |
---|
1239 | n/a | with self.assertRaises((ValueError, ExceptionMock)) as cm: |
---|
1240 | n/a | Stub() |
---|
1241 | n/a | # The context manager exposes caught exception |
---|
1242 | n/a | self.assertIsInstance(cm.exception, ExceptionMock) |
---|
1243 | n/a | self.assertEqual(cm.exception.args[0], 'We expect') |
---|
1244 | n/a | # *args and **kwargs also work |
---|
1245 | n/a | with self.assertRaises(ValueError): |
---|
1246 | n/a | int('19', base=8) |
---|
1247 | n/a | # Failure when no exception is raised |
---|
1248 | n/a | with self.assertRaises(self.failureException): |
---|
1249 | n/a | with self.assertRaises(ExceptionMock): |
---|
1250 | n/a | pass |
---|
1251 | n/a | # Custom message |
---|
1252 | n/a | with self.assertRaisesRegex(self.failureException, 'foobar'): |
---|
1253 | n/a | with self.assertRaises(ExceptionMock, msg='foobar'): |
---|
1254 | n/a | pass |
---|
1255 | n/a | # Invalid keyword argument |
---|
1256 | n/a | with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ |
---|
1257 | n/a | self.assertRaises(AssertionError): |
---|
1258 | n/a | with self.assertRaises(ExceptionMock, foobar=42): |
---|
1259 | n/a | pass |
---|
1260 | n/a | # Failure when another exception is raised |
---|
1261 | n/a | with self.assertRaises(ExceptionMock): |
---|
1262 | n/a | self.assertRaises(ValueError, Stub) |
---|
1263 | n/a | |
---|
1264 | n/a | def testAssertRaisesNoExceptionType(self): |
---|
1265 | n/a | with self.assertRaises(TypeError): |
---|
1266 | n/a | self.assertRaises() |
---|
1267 | n/a | with self.assertRaises(TypeError): |
---|
1268 | n/a | self.assertRaises(1) |
---|
1269 | n/a | with self.assertRaises(TypeError): |
---|
1270 | n/a | self.assertRaises(object) |
---|
1271 | n/a | with self.assertRaises(TypeError): |
---|
1272 | n/a | self.assertRaises((ValueError, 1)) |
---|
1273 | n/a | with self.assertRaises(TypeError): |
---|
1274 | n/a | self.assertRaises((ValueError, object)) |
---|
1275 | n/a | |
---|
1276 | n/a | def testAssertRaisesRegex(self): |
---|
1277 | n/a | class ExceptionMock(Exception): |
---|
1278 | n/a | pass |
---|
1279 | n/a | |
---|
1280 | n/a | def Stub(): |
---|
1281 | n/a | raise ExceptionMock('We expect') |
---|
1282 | n/a | |
---|
1283 | n/a | self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub) |
---|
1284 | n/a | self.assertRaisesRegex(ExceptionMock, 'expect$', Stub) |
---|
1285 | n/a | with self.assertWarns(DeprecationWarning): |
---|
1286 | n/a | self.assertRaisesRegex(ExceptionMock, 'expect$', None) |
---|
1287 | n/a | |
---|
1288 | n/a | def testAssertNotRaisesRegex(self): |
---|
1289 | n/a | self.assertRaisesRegex( |
---|
1290 | n/a | self.failureException, '^Exception not raised by <lambda>$', |
---|
1291 | n/a | self.assertRaisesRegex, Exception, re.compile('x'), |
---|
1292 | n/a | lambda: None) |
---|
1293 | n/a | self.assertRaisesRegex( |
---|
1294 | n/a | self.failureException, '^Exception not raised by <lambda>$', |
---|
1295 | n/a | self.assertRaisesRegex, Exception, 'x', |
---|
1296 | n/a | lambda: None) |
---|
1297 | n/a | # Custom message |
---|
1298 | n/a | with self.assertRaisesRegex(self.failureException, 'foobar'): |
---|
1299 | n/a | with self.assertRaisesRegex(Exception, 'expect', msg='foobar'): |
---|
1300 | n/a | pass |
---|
1301 | n/a | # Invalid keyword argument |
---|
1302 | n/a | with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ |
---|
1303 | n/a | self.assertRaises(AssertionError): |
---|
1304 | n/a | with self.assertRaisesRegex(Exception, 'expect', foobar=42): |
---|
1305 | n/a | pass |
---|
1306 | n/a | |
---|
1307 | n/a | def testAssertRaisesRegexInvalidRegex(self): |
---|
1308 | n/a | # Issue 20145. |
---|
1309 | n/a | class MyExc(Exception): |
---|
1310 | n/a | pass |
---|
1311 | n/a | self.assertRaises(TypeError, self.assertRaisesRegex, MyExc, lambda: True) |
---|
1312 | n/a | |
---|
1313 | n/a | def testAssertWarnsRegexInvalidRegex(self): |
---|
1314 | n/a | # Issue 20145. |
---|
1315 | n/a | class MyWarn(Warning): |
---|
1316 | n/a | pass |
---|
1317 | n/a | self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True) |
---|
1318 | n/a | |
---|
1319 | n/a | def testAssertRaisesRegexMismatch(self): |
---|
1320 | n/a | def Stub(): |
---|
1321 | n/a | raise Exception('Unexpected') |
---|
1322 | n/a | |
---|
1323 | n/a | self.assertRaisesRegex( |
---|
1324 | n/a | self.failureException, |
---|
1325 | n/a | r'"\^Expected\$" does not match "Unexpected"', |
---|
1326 | n/a | self.assertRaisesRegex, Exception, '^Expected$', |
---|
1327 | n/a | Stub) |
---|
1328 | n/a | self.assertRaisesRegex( |
---|
1329 | n/a | self.failureException, |
---|
1330 | n/a | r'"\^Expected\$" does not match "Unexpected"', |
---|
1331 | n/a | self.assertRaisesRegex, Exception, |
---|
1332 | n/a | re.compile('^Expected$'), Stub) |
---|
1333 | n/a | |
---|
1334 | n/a | def testAssertRaisesExcValue(self): |
---|
1335 | n/a | class ExceptionMock(Exception): |
---|
1336 | n/a | pass |
---|
1337 | n/a | |
---|
1338 | n/a | def Stub(foo): |
---|
1339 | n/a | raise ExceptionMock(foo) |
---|
1340 | n/a | v = "particular value" |
---|
1341 | n/a | |
---|
1342 | n/a | ctx = self.assertRaises(ExceptionMock) |
---|
1343 | n/a | with ctx: |
---|
1344 | n/a | Stub(v) |
---|
1345 | n/a | e = ctx.exception |
---|
1346 | n/a | self.assertIsInstance(e, ExceptionMock) |
---|
1347 | n/a | self.assertEqual(e.args[0], v) |
---|
1348 | n/a | |
---|
1349 | n/a | def testAssertRaisesRegexNoExceptionType(self): |
---|
1350 | n/a | with self.assertRaises(TypeError): |
---|
1351 | n/a | self.assertRaisesRegex() |
---|
1352 | n/a | with self.assertRaises(TypeError): |
---|
1353 | n/a | self.assertRaisesRegex(ValueError) |
---|
1354 | n/a | with self.assertRaises(TypeError): |
---|
1355 | n/a | self.assertRaisesRegex(1, 'expect') |
---|
1356 | n/a | with self.assertRaises(TypeError): |
---|
1357 | n/a | self.assertRaisesRegex(object, 'expect') |
---|
1358 | n/a | with self.assertRaises(TypeError): |
---|
1359 | n/a | self.assertRaisesRegex((ValueError, 1), 'expect') |
---|
1360 | n/a | with self.assertRaises(TypeError): |
---|
1361 | n/a | self.assertRaisesRegex((ValueError, object), 'expect') |
---|
1362 | n/a | |
---|
1363 | n/a | def testAssertWarnsCallable(self): |
---|
1364 | n/a | def _runtime_warn(): |
---|
1365 | n/a | warnings.warn("foo", RuntimeWarning) |
---|
1366 | n/a | # Success when the right warning is triggered, even several times |
---|
1367 | n/a | self.assertWarns(RuntimeWarning, _runtime_warn) |
---|
1368 | n/a | self.assertWarns(RuntimeWarning, _runtime_warn) |
---|
1369 | n/a | # A tuple of warning classes is accepted |
---|
1370 | n/a | self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn) |
---|
1371 | n/a | # *args and **kwargs also work |
---|
1372 | n/a | self.assertWarns(RuntimeWarning, |
---|
1373 | n/a | warnings.warn, "foo", category=RuntimeWarning) |
---|
1374 | n/a | # Failure when no warning is triggered |
---|
1375 | n/a | with self.assertRaises(self.failureException): |
---|
1376 | n/a | self.assertWarns(RuntimeWarning, lambda: 0) |
---|
1377 | n/a | # Failure when the function is None |
---|
1378 | n/a | with self.assertWarns(DeprecationWarning): |
---|
1379 | n/a | self.assertWarns(RuntimeWarning, None) |
---|
1380 | n/a | # Failure when another warning is triggered |
---|
1381 | n/a | with warnings.catch_warnings(): |
---|
1382 | n/a | # Force default filter (in case tests are run with -We) |
---|
1383 | n/a | warnings.simplefilter("default", RuntimeWarning) |
---|
1384 | n/a | with self.assertRaises(self.failureException): |
---|
1385 | n/a | self.assertWarns(DeprecationWarning, _runtime_warn) |
---|
1386 | n/a | # Filters for other warnings are not modified |
---|
1387 | n/a | with warnings.catch_warnings(): |
---|
1388 | n/a | warnings.simplefilter("error", RuntimeWarning) |
---|
1389 | n/a | with self.assertRaises(RuntimeWarning): |
---|
1390 | n/a | self.assertWarns(DeprecationWarning, _runtime_warn) |
---|
1391 | n/a | |
---|
1392 | n/a | def testAssertWarnsContext(self): |
---|
1393 | n/a | # Believe it or not, it is preferable to duplicate all tests above, |
---|
1394 | n/a | # to make sure the __warningregistry__ $@ is circumvented correctly. |
---|
1395 | n/a | def _runtime_warn(): |
---|
1396 | n/a | warnings.warn("foo", RuntimeWarning) |
---|
1397 | n/a | _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] |
---|
1398 | n/a | with self.assertWarns(RuntimeWarning) as cm: |
---|
1399 | n/a | _runtime_warn() |
---|
1400 | n/a | # A tuple of warning classes is accepted |
---|
1401 | n/a | with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm: |
---|
1402 | n/a | _runtime_warn() |
---|
1403 | n/a | # The context manager exposes various useful attributes |
---|
1404 | n/a | self.assertIsInstance(cm.warning, RuntimeWarning) |
---|
1405 | n/a | self.assertEqual(cm.warning.args[0], "foo") |
---|
1406 | n/a | self.assertIn("test_case.py", cm.filename) |
---|
1407 | n/a | self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) |
---|
1408 | n/a | # Same with several warnings |
---|
1409 | n/a | with self.assertWarns(RuntimeWarning): |
---|
1410 | n/a | _runtime_warn() |
---|
1411 | n/a | _runtime_warn() |
---|
1412 | n/a | with self.assertWarns(RuntimeWarning): |
---|
1413 | n/a | warnings.warn("foo", category=RuntimeWarning) |
---|
1414 | n/a | # Failure when no warning is triggered |
---|
1415 | n/a | with self.assertRaises(self.failureException): |
---|
1416 | n/a | with self.assertWarns(RuntimeWarning): |
---|
1417 | n/a | pass |
---|
1418 | n/a | # Custom message |
---|
1419 | n/a | with self.assertRaisesRegex(self.failureException, 'foobar'): |
---|
1420 | n/a | with self.assertWarns(RuntimeWarning, msg='foobar'): |
---|
1421 | n/a | pass |
---|
1422 | n/a | # Invalid keyword argument |
---|
1423 | n/a | with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ |
---|
1424 | n/a | self.assertRaises(AssertionError): |
---|
1425 | n/a | with self.assertWarns(RuntimeWarning, foobar=42): |
---|
1426 | n/a | pass |
---|
1427 | n/a | # Failure when another warning is triggered |
---|
1428 | n/a | with warnings.catch_warnings(): |
---|
1429 | n/a | # Force default filter (in case tests are run with -We) |
---|
1430 | n/a | warnings.simplefilter("default", RuntimeWarning) |
---|
1431 | n/a | with self.assertRaises(self.failureException): |
---|
1432 | n/a | with self.assertWarns(DeprecationWarning): |
---|
1433 | n/a | _runtime_warn() |
---|
1434 | n/a | # Filters for other warnings are not modified |
---|
1435 | n/a | with warnings.catch_warnings(): |
---|
1436 | n/a | warnings.simplefilter("error", RuntimeWarning) |
---|
1437 | n/a | with self.assertRaises(RuntimeWarning): |
---|
1438 | n/a | with self.assertWarns(DeprecationWarning): |
---|
1439 | n/a | _runtime_warn() |
---|
1440 | n/a | |
---|
1441 | n/a | def testAssertWarnsNoExceptionType(self): |
---|
1442 | n/a | with self.assertRaises(TypeError): |
---|
1443 | n/a | self.assertWarns() |
---|
1444 | n/a | with self.assertRaises(TypeError): |
---|
1445 | n/a | self.assertWarns(1) |
---|
1446 | n/a | with self.assertRaises(TypeError): |
---|
1447 | n/a | self.assertWarns(object) |
---|
1448 | n/a | with self.assertRaises(TypeError): |
---|
1449 | n/a | self.assertWarns((UserWarning, 1)) |
---|
1450 | n/a | with self.assertRaises(TypeError): |
---|
1451 | n/a | self.assertWarns((UserWarning, object)) |
---|
1452 | n/a | with self.assertRaises(TypeError): |
---|
1453 | n/a | self.assertWarns((UserWarning, Exception)) |
---|
1454 | n/a | |
---|
1455 | n/a | def testAssertWarnsRegexCallable(self): |
---|
1456 | n/a | def _runtime_warn(msg): |
---|
1457 | n/a | warnings.warn(msg, RuntimeWarning) |
---|
1458 | n/a | self.assertWarnsRegex(RuntimeWarning, "o+", |
---|
1459 | n/a | _runtime_warn, "foox") |
---|
1460 | n/a | # Failure when no warning is triggered |
---|
1461 | n/a | with self.assertRaises(self.failureException): |
---|
1462 | n/a | self.assertWarnsRegex(RuntimeWarning, "o+", |
---|
1463 | n/a | lambda: 0) |
---|
1464 | n/a | # Failure when the function is None |
---|
1465 | n/a | with self.assertWarns(DeprecationWarning): |
---|
1466 | n/a | self.assertWarnsRegex(RuntimeWarning, "o+", None) |
---|
1467 | n/a | # Failure when another warning is triggered |
---|
1468 | n/a | with warnings.catch_warnings(): |
---|
1469 | n/a | # Force default filter (in case tests are run with -We) |
---|
1470 | n/a | warnings.simplefilter("default", RuntimeWarning) |
---|
1471 | n/a | with self.assertRaises(self.failureException): |
---|
1472 | n/a | self.assertWarnsRegex(DeprecationWarning, "o+", |
---|
1473 | n/a | _runtime_warn, "foox") |
---|
1474 | n/a | # Failure when message doesn't match |
---|
1475 | n/a | with self.assertRaises(self.failureException): |
---|
1476 | n/a | self.assertWarnsRegex(RuntimeWarning, "o+", |
---|
1477 | n/a | _runtime_warn, "barz") |
---|
1478 | n/a | # A little trickier: we ask RuntimeWarnings to be raised, and then |
---|
1479 | n/a | # check for some of them. It is implementation-defined whether |
---|
1480 | n/a | # non-matching RuntimeWarnings are simply re-raised, or produce a |
---|
1481 | n/a | # failureException. |
---|
1482 | n/a | with warnings.catch_warnings(): |
---|
1483 | n/a | warnings.simplefilter("error", RuntimeWarning) |
---|
1484 | n/a | with self.assertRaises((RuntimeWarning, self.failureException)): |
---|
1485 | n/a | self.assertWarnsRegex(RuntimeWarning, "o+", |
---|
1486 | n/a | _runtime_warn, "barz") |
---|
1487 | n/a | |
---|
1488 | n/a | def testAssertWarnsRegexContext(self): |
---|
1489 | n/a | # Same as above, but with assertWarnsRegex as a context manager |
---|
1490 | n/a | def _runtime_warn(msg): |
---|
1491 | n/a | warnings.warn(msg, RuntimeWarning) |
---|
1492 | n/a | _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] |
---|
1493 | n/a | with self.assertWarnsRegex(RuntimeWarning, "o+") as cm: |
---|
1494 | n/a | _runtime_warn("foox") |
---|
1495 | n/a | self.assertIsInstance(cm.warning, RuntimeWarning) |
---|
1496 | n/a | self.assertEqual(cm.warning.args[0], "foox") |
---|
1497 | n/a | self.assertIn("test_case.py", cm.filename) |
---|
1498 | n/a | self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) |
---|
1499 | n/a | # Failure when no warning is triggered |
---|
1500 | n/a | with self.assertRaises(self.failureException): |
---|
1501 | n/a | with self.assertWarnsRegex(RuntimeWarning, "o+"): |
---|
1502 | n/a | pass |
---|
1503 | n/a | # Custom message |
---|
1504 | n/a | with self.assertRaisesRegex(self.failureException, 'foobar'): |
---|
1505 | n/a | with self.assertWarnsRegex(RuntimeWarning, 'o+', msg='foobar'): |
---|
1506 | n/a | pass |
---|
1507 | n/a | # Invalid keyword argument |
---|
1508 | n/a | with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ |
---|
1509 | n/a | self.assertRaises(AssertionError): |
---|
1510 | n/a | with self.assertWarnsRegex(RuntimeWarning, 'o+', foobar=42): |
---|
1511 | n/a | pass |
---|
1512 | n/a | # Failure when another warning is triggered |
---|
1513 | n/a | with warnings.catch_warnings(): |
---|
1514 | n/a | # Force default filter (in case tests are run with -We) |
---|
1515 | n/a | warnings.simplefilter("default", RuntimeWarning) |
---|
1516 | n/a | with self.assertRaises(self.failureException): |
---|
1517 | n/a | with self.assertWarnsRegex(DeprecationWarning, "o+"): |
---|
1518 | n/a | _runtime_warn("foox") |
---|
1519 | n/a | # Failure when message doesn't match |
---|
1520 | n/a | with self.assertRaises(self.failureException): |
---|
1521 | n/a | with self.assertWarnsRegex(RuntimeWarning, "o+"): |
---|
1522 | n/a | _runtime_warn("barz") |
---|
1523 | n/a | # A little trickier: we ask RuntimeWarnings to be raised, and then |
---|
1524 | n/a | # check for some of them. It is implementation-defined whether |
---|
1525 | n/a | # non-matching RuntimeWarnings are simply re-raised, or produce a |
---|
1526 | n/a | # failureException. |
---|
1527 | n/a | with warnings.catch_warnings(): |
---|
1528 | n/a | warnings.simplefilter("error", RuntimeWarning) |
---|
1529 | n/a | with self.assertRaises((RuntimeWarning, self.failureException)): |
---|
1530 | n/a | with self.assertWarnsRegex(RuntimeWarning, "o+"): |
---|
1531 | n/a | _runtime_warn("barz") |
---|
1532 | n/a | |
---|
1533 | n/a | def testAssertWarnsRegexNoExceptionType(self): |
---|
1534 | n/a | with self.assertRaises(TypeError): |
---|
1535 | n/a | self.assertWarnsRegex() |
---|
1536 | n/a | with self.assertRaises(TypeError): |
---|
1537 | n/a | self.assertWarnsRegex(UserWarning) |
---|
1538 | n/a | with self.assertRaises(TypeError): |
---|
1539 | n/a | self.assertWarnsRegex(1, 'expect') |
---|
1540 | n/a | with self.assertRaises(TypeError): |
---|
1541 | n/a | self.assertWarnsRegex(object, 'expect') |
---|
1542 | n/a | with self.assertRaises(TypeError): |
---|
1543 | n/a | self.assertWarnsRegex((UserWarning, 1), 'expect') |
---|
1544 | n/a | with self.assertRaises(TypeError): |
---|
1545 | n/a | self.assertWarnsRegex((UserWarning, object), 'expect') |
---|
1546 | n/a | with self.assertRaises(TypeError): |
---|
1547 | n/a | self.assertWarnsRegex((UserWarning, Exception), 'expect') |
---|
1548 | n/a | |
---|
1549 | n/a | @contextlib.contextmanager |
---|
1550 | n/a | def assertNoStderr(self): |
---|
1551 | n/a | with captured_stderr() as buf: |
---|
1552 | n/a | yield |
---|
1553 | n/a | self.assertEqual(buf.getvalue(), "") |
---|
1554 | n/a | |
---|
1555 | n/a | def assertLogRecords(self, records, matches): |
---|
1556 | n/a | self.assertEqual(len(records), len(matches)) |
---|
1557 | n/a | for rec, match in zip(records, matches): |
---|
1558 | n/a | self.assertIsInstance(rec, logging.LogRecord) |
---|
1559 | n/a | for k, v in match.items(): |
---|
1560 | n/a | self.assertEqual(getattr(rec, k), v) |
---|
1561 | n/a | |
---|
1562 | n/a | def testAssertLogsDefaults(self): |
---|
1563 | n/a | # defaults: root logger, level INFO |
---|
1564 | n/a | with self.assertNoStderr(): |
---|
1565 | n/a | with self.assertLogs() as cm: |
---|
1566 | n/a | log_foo.info("1") |
---|
1567 | n/a | log_foobar.debug("2") |
---|
1568 | n/a | self.assertEqual(cm.output, ["INFO:foo:1"]) |
---|
1569 | n/a | self.assertLogRecords(cm.records, [{'name': 'foo'}]) |
---|
1570 | n/a | |
---|
1571 | n/a | def testAssertLogsTwoMatchingMessages(self): |
---|
1572 | n/a | # Same, but with two matching log messages |
---|
1573 | n/a | with self.assertNoStderr(): |
---|
1574 | n/a | with self.assertLogs() as cm: |
---|
1575 | n/a | log_foo.info("1") |
---|
1576 | n/a | log_foobar.debug("2") |
---|
1577 | n/a | log_quux.warning("3") |
---|
1578 | n/a | self.assertEqual(cm.output, ["INFO:foo:1", "WARNING:quux:3"]) |
---|
1579 | n/a | self.assertLogRecords(cm.records, |
---|
1580 | n/a | [{'name': 'foo'}, {'name': 'quux'}]) |
---|
1581 | n/a | |
---|
1582 | n/a | def checkAssertLogsPerLevel(self, level): |
---|
1583 | n/a | # Check level filtering |
---|
1584 | n/a | with self.assertNoStderr(): |
---|
1585 | n/a | with self.assertLogs(level=level) as cm: |
---|
1586 | n/a | log_foo.warning("1") |
---|
1587 | n/a | log_foobar.error("2") |
---|
1588 | n/a | log_quux.critical("3") |
---|
1589 | n/a | self.assertEqual(cm.output, ["ERROR:foo.bar:2", "CRITICAL:quux:3"]) |
---|
1590 | n/a | self.assertLogRecords(cm.records, |
---|
1591 | n/a | [{'name': 'foo.bar'}, {'name': 'quux'}]) |
---|
1592 | n/a | |
---|
1593 | n/a | def testAssertLogsPerLevel(self): |
---|
1594 | n/a | self.checkAssertLogsPerLevel(logging.ERROR) |
---|
1595 | n/a | self.checkAssertLogsPerLevel('ERROR') |
---|
1596 | n/a | |
---|
1597 | n/a | def checkAssertLogsPerLogger(self, logger): |
---|
1598 | n/a | # Check per-logger filtering |
---|
1599 | n/a | with self.assertNoStderr(): |
---|
1600 | n/a | with self.assertLogs(level='DEBUG') as outer_cm: |
---|
1601 | n/a | with self.assertLogs(logger, level='DEBUG') as cm: |
---|
1602 | n/a | log_foo.info("1") |
---|
1603 | n/a | log_foobar.debug("2") |
---|
1604 | n/a | log_quux.warning("3") |
---|
1605 | n/a | self.assertEqual(cm.output, ["INFO:foo:1", "DEBUG:foo.bar:2"]) |
---|
1606 | n/a | self.assertLogRecords(cm.records, |
---|
1607 | n/a | [{'name': 'foo'}, {'name': 'foo.bar'}]) |
---|
1608 | n/a | # The outer catchall caught the quux log |
---|
1609 | n/a | self.assertEqual(outer_cm.output, ["WARNING:quux:3"]) |
---|
1610 | n/a | |
---|
1611 | n/a | def testAssertLogsPerLogger(self): |
---|
1612 | n/a | self.checkAssertLogsPerLogger(logging.getLogger('foo')) |
---|
1613 | n/a | self.checkAssertLogsPerLogger('foo') |
---|
1614 | n/a | |
---|
1615 | n/a | def testAssertLogsFailureNoLogs(self): |
---|
1616 | n/a | # Failure due to no logs |
---|
1617 | n/a | with self.assertNoStderr(): |
---|
1618 | n/a | with self.assertRaises(self.failureException): |
---|
1619 | n/a | with self.assertLogs(): |
---|
1620 | n/a | pass |
---|
1621 | n/a | |
---|
1622 | n/a | def testAssertLogsFailureLevelTooHigh(self): |
---|
1623 | n/a | # Failure due to level too high |
---|
1624 | n/a | with self.assertNoStderr(): |
---|
1625 | n/a | with self.assertRaises(self.failureException): |
---|
1626 | n/a | with self.assertLogs(level='WARNING'): |
---|
1627 | n/a | log_foo.info("1") |
---|
1628 | n/a | |
---|
1629 | n/a | def testAssertLogsFailureMismatchingLogger(self): |
---|
1630 | n/a | # Failure due to mismatching logger (and the logged message is |
---|
1631 | n/a | # passed through) |
---|
1632 | n/a | with self.assertLogs('quux', level='ERROR'): |
---|
1633 | n/a | with self.assertRaises(self.failureException): |
---|
1634 | n/a | with self.assertLogs('foo'): |
---|
1635 | n/a | log_quux.error("1") |
---|
1636 | n/a | |
---|
1637 | n/a | def testDeprecatedMethodNames(self): |
---|
1638 | n/a | """ |
---|
1639 | n/a | Test that the deprecated methods raise a DeprecationWarning. See #9424. |
---|
1640 | n/a | """ |
---|
1641 | n/a | old = ( |
---|
1642 | n/a | (self.failIfEqual, (3, 5)), |
---|
1643 | n/a | (self.assertNotEquals, (3, 5)), |
---|
1644 | n/a | (self.failUnlessEqual, (3, 3)), |
---|
1645 | n/a | (self.assertEquals, (3, 3)), |
---|
1646 | n/a | (self.failUnlessAlmostEqual, (2.0, 2.0)), |
---|
1647 | n/a | (self.assertAlmostEquals, (2.0, 2.0)), |
---|
1648 | n/a | (self.failIfAlmostEqual, (3.0, 5.0)), |
---|
1649 | n/a | (self.assertNotAlmostEquals, (3.0, 5.0)), |
---|
1650 | n/a | (self.failUnless, (True,)), |
---|
1651 | n/a | (self.assert_, (True,)), |
---|
1652 | n/a | (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')), |
---|
1653 | n/a | (self.failIf, (False,)), |
---|
1654 | n/a | (self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))), |
---|
1655 | n/a | (self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])), |
---|
1656 | n/a | (self.assertRegexpMatches, ('bar', 'bar')), |
---|
1657 | n/a | ) |
---|
1658 | n/a | for meth, args in old: |
---|
1659 | n/a | with self.assertWarns(DeprecationWarning): |
---|
1660 | n/a | meth(*args) |
---|
1661 | n/a | |
---|
1662 | n/a | # disable this test for now. When the version where the fail* methods will |
---|
1663 | n/a | # be removed is decided, re-enable it and update the version |
---|
1664 | n/a | def _testDeprecatedFailMethods(self): |
---|
1665 | n/a | """Test that the deprecated fail* methods get removed in 3.x""" |
---|
1666 | n/a | if sys.version_info[:2] < (3, 3): |
---|
1667 | n/a | return |
---|
1668 | n/a | deprecated_names = [ |
---|
1669 | n/a | 'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual', |
---|
1670 | n/a | 'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf', |
---|
1671 | n/a | 'assertDictContainsSubset', |
---|
1672 | n/a | ] |
---|
1673 | n/a | for deprecated_name in deprecated_names: |
---|
1674 | n/a | with self.assertRaises(AttributeError): |
---|
1675 | n/a | getattr(self, deprecated_name) # remove these in 3.x |
---|
1676 | n/a | |
---|
1677 | n/a | def testDeepcopy(self): |
---|
1678 | n/a | # Issue: 5660 |
---|
1679 | n/a | class TestableTest(unittest.TestCase): |
---|
1680 | n/a | def testNothing(self): |
---|
1681 | n/a | pass |
---|
1682 | n/a | |
---|
1683 | n/a | test = TestableTest('testNothing') |
---|
1684 | n/a | |
---|
1685 | n/a | # This shouldn't blow up |
---|
1686 | n/a | deepcopy(test) |
---|
1687 | n/a | |
---|
1688 | n/a | def testPickle(self): |
---|
1689 | n/a | # Issue 10326 |
---|
1690 | n/a | |
---|
1691 | n/a | # Can't use TestCase classes defined in Test class as |
---|
1692 | n/a | # pickle does not work with inner classes |
---|
1693 | n/a | test = unittest.TestCase('run') |
---|
1694 | n/a | for protocol in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1695 | n/a | |
---|
1696 | n/a | # blew up prior to fix |
---|
1697 | n/a | pickled_test = pickle.dumps(test, protocol=protocol) |
---|
1698 | n/a | unpickled_test = pickle.loads(pickled_test) |
---|
1699 | n/a | self.assertEqual(test, unpickled_test) |
---|
1700 | n/a | |
---|
1701 | n/a | # exercise the TestCase instance in a way that will invoke |
---|
1702 | n/a | # the type equality lookup mechanism |
---|
1703 | n/a | unpickled_test.assertEqual(set(), set()) |
---|
1704 | n/a | |
---|
1705 | n/a | def testKeyboardInterrupt(self): |
---|
1706 | n/a | def _raise(self=None): |
---|
1707 | n/a | raise KeyboardInterrupt |
---|
1708 | n/a | def nothing(self): |
---|
1709 | n/a | pass |
---|
1710 | n/a | |
---|
1711 | n/a | class Test1(unittest.TestCase): |
---|
1712 | n/a | test_something = _raise |
---|
1713 | n/a | |
---|
1714 | n/a | class Test2(unittest.TestCase): |
---|
1715 | n/a | setUp = _raise |
---|
1716 | n/a | test_something = nothing |
---|
1717 | n/a | |
---|
1718 | n/a | class Test3(unittest.TestCase): |
---|
1719 | n/a | test_something = nothing |
---|
1720 | n/a | tearDown = _raise |
---|
1721 | n/a | |
---|
1722 | n/a | class Test4(unittest.TestCase): |
---|
1723 | n/a | def test_something(self): |
---|
1724 | n/a | self.addCleanup(_raise) |
---|
1725 | n/a | |
---|
1726 | n/a | for klass in (Test1, Test2, Test3, Test4): |
---|
1727 | n/a | with self.assertRaises(KeyboardInterrupt): |
---|
1728 | n/a | klass('test_something').run() |
---|
1729 | n/a | |
---|
1730 | n/a | def testSkippingEverywhere(self): |
---|
1731 | n/a | def _skip(self=None): |
---|
1732 | n/a | raise unittest.SkipTest('some reason') |
---|
1733 | n/a | def nothing(self): |
---|
1734 | n/a | pass |
---|
1735 | n/a | |
---|
1736 | n/a | class Test1(unittest.TestCase): |
---|
1737 | n/a | test_something = _skip |
---|
1738 | n/a | |
---|
1739 | n/a | class Test2(unittest.TestCase): |
---|
1740 | n/a | setUp = _skip |
---|
1741 | n/a | test_something = nothing |
---|
1742 | n/a | |
---|
1743 | n/a | class Test3(unittest.TestCase): |
---|
1744 | n/a | test_something = nothing |
---|
1745 | n/a | tearDown = _skip |
---|
1746 | n/a | |
---|
1747 | n/a | class Test4(unittest.TestCase): |
---|
1748 | n/a | def test_something(self): |
---|
1749 | n/a | self.addCleanup(_skip) |
---|
1750 | n/a | |
---|
1751 | n/a | for klass in (Test1, Test2, Test3, Test4): |
---|
1752 | n/a | result = unittest.TestResult() |
---|
1753 | n/a | klass('test_something').run(result) |
---|
1754 | n/a | self.assertEqual(len(result.skipped), 1) |
---|
1755 | n/a | self.assertEqual(result.testsRun, 1) |
---|
1756 | n/a | |
---|
1757 | n/a | def testSystemExit(self): |
---|
1758 | n/a | def _raise(self=None): |
---|
1759 | n/a | raise SystemExit |
---|
1760 | n/a | def nothing(self): |
---|
1761 | n/a | pass |
---|
1762 | n/a | |
---|
1763 | n/a | class Test1(unittest.TestCase): |
---|
1764 | n/a | test_something = _raise |
---|
1765 | n/a | |
---|
1766 | n/a | class Test2(unittest.TestCase): |
---|
1767 | n/a | setUp = _raise |
---|
1768 | n/a | test_something = nothing |
---|
1769 | n/a | |
---|
1770 | n/a | class Test3(unittest.TestCase): |
---|
1771 | n/a | test_something = nothing |
---|
1772 | n/a | tearDown = _raise |
---|
1773 | n/a | |
---|
1774 | n/a | class Test4(unittest.TestCase): |
---|
1775 | n/a | def test_something(self): |
---|
1776 | n/a | self.addCleanup(_raise) |
---|
1777 | n/a | |
---|
1778 | n/a | for klass in (Test1, Test2, Test3, Test4): |
---|
1779 | n/a | result = unittest.TestResult() |
---|
1780 | n/a | klass('test_something').run(result) |
---|
1781 | n/a | self.assertEqual(len(result.errors), 1) |
---|
1782 | n/a | self.assertEqual(result.testsRun, 1) |
---|
1783 | n/a | |
---|
1784 | n/a | @support.cpython_only |
---|
1785 | n/a | def testNoCycles(self): |
---|
1786 | n/a | case = unittest.TestCase() |
---|
1787 | n/a | wr = weakref.ref(case) |
---|
1788 | n/a | with support.disable_gc(): |
---|
1789 | n/a | del case |
---|
1790 | n/a | self.assertFalse(wr()) |
---|
1791 | n/a | |
---|
1792 | n/a | def test_no_exception_leak(self): |
---|
1793 | n/a | # Issue #19880: TestCase.run() should not keep a reference |
---|
1794 | n/a | # to the exception |
---|
1795 | n/a | class MyException(Exception): |
---|
1796 | n/a | ninstance = 0 |
---|
1797 | n/a | |
---|
1798 | n/a | def __init__(self): |
---|
1799 | n/a | MyException.ninstance += 1 |
---|
1800 | n/a | Exception.__init__(self) |
---|
1801 | n/a | |
---|
1802 | n/a | def __del__(self): |
---|
1803 | n/a | MyException.ninstance -= 1 |
---|
1804 | n/a | |
---|
1805 | n/a | class TestCase(unittest.TestCase): |
---|
1806 | n/a | def test1(self): |
---|
1807 | n/a | raise MyException() |
---|
1808 | n/a | |
---|
1809 | n/a | @unittest.expectedFailure |
---|
1810 | n/a | def test2(self): |
---|
1811 | n/a | raise MyException() |
---|
1812 | n/a | |
---|
1813 | n/a | for method_name in ('test1', 'test2'): |
---|
1814 | n/a | testcase = TestCase(method_name) |
---|
1815 | n/a | testcase.run() |
---|
1816 | n/a | self.assertEqual(MyException.ninstance, 0) |
---|
1817 | n/a | |
---|
1818 | n/a | |
---|
1819 | n/a | if __name__ == "__main__": |
---|
1820 | n/a | unittest.main() |
---|