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