OLD | NEW |
1 """Test case implementation""" | 1 """Test case implementation""" |
2 | 2 |
3 import sys | 3 import sys |
4 import difflib | 4 import difflib |
5 import pprint | 5 import pprint |
6 import re | 6 import re |
7 import unittest | 7 import unittest |
8 import warnings | 8 import warnings |
9 | 9 |
10 from unittest2 import result | 10 from unittest2 import result |
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
52 def skip(reason): | 52 def skip(reason): |
53 """ | 53 """ |
54 Unconditionally skip a test. | 54 Unconditionally skip a test. |
55 """ | 55 """ |
56 def decorator(test_item): | 56 def decorator(test_item): |
57 if not (isinstance(test_item, type) and issubclass(test_item, TestCase))
: | 57 if not (isinstance(test_item, type) and issubclass(test_item, TestCase))
: |
58 @wraps(test_item) | 58 @wraps(test_item) |
59 def skip_wrapper(*args, **kwargs): | 59 def skip_wrapper(*args, **kwargs): |
60 raise SkipTest(reason) | 60 raise SkipTest(reason) |
61 test_item = skip_wrapper | 61 test_item = skip_wrapper |
62 | 62 |
63 test_item.__unittest_skip__ = True | 63 test_item.__unittest_skip__ = True |
64 test_item.__unittest_skip_why__ = reason | 64 test_item.__unittest_skip_why__ = reason |
65 return test_item | 65 return test_item |
66 return decorator | 66 return decorator |
67 | 67 |
68 def skipIf(condition, reason): | 68 def skipIf(condition, reason): |
69 """ | 69 """ |
70 Skip a test if the condition is true. | 70 Skip a test if the condition is true. |
71 """ | 71 """ |
72 if condition: | 72 if condition: |
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
122 expected_regexp = self.expected_regexp | 122 expected_regexp = self.expected_regexp |
123 if isinstance(expected_regexp, basestring): | 123 if isinstance(expected_regexp, basestring): |
124 expected_regexp = re.compile(expected_regexp) | 124 expected_regexp = re.compile(expected_regexp) |
125 if not expected_regexp.search(str(exc_value)): | 125 if not expected_regexp.search(str(exc_value)): |
126 raise self.failureException('"%s" does not match "%s"' % | 126 raise self.failureException('"%s" does not match "%s"' % |
127 (expected_regexp.pattern, str(exc_value))) | 127 (expected_regexp.pattern, str(exc_value))) |
128 return True | 128 return True |
129 | 129 |
130 | 130 |
131 class _TypeEqualityDict(object): | 131 class _TypeEqualityDict(object): |
132 | 132 |
133 def __init__(self, testcase): | 133 def __init__(self, testcase): |
134 self.testcase = testcase | 134 self.testcase = testcase |
135 self._store = {} | 135 self._store = {} |
136 | 136 |
137 def __setitem__(self, key, value): | 137 def __setitem__(self, key, value): |
138 self._store[key] = value | 138 self._store[key] = value |
139 | 139 |
140 def __getitem__(self, key): | 140 def __getitem__(self, key): |
141 value = self._store[key] | 141 value = self._store[key] |
142 if isinstance(value, basestring): | 142 if isinstance(value, basestring): |
143 return getattr(self.testcase, value) | 143 return getattr(self.testcase, value) |
144 return value | 144 return value |
145 | 145 |
146 def get(self, key, default=None): | 146 def get(self, key, default=None): |
147 if key in self._store: | 147 if key in self._store: |
148 return self[key] | 148 return self[key] |
149 return default | 149 return default |
150 | 150 |
151 | 151 |
152 class TestCase(unittest.TestCase): | 152 class TestCase(unittest.TestCase): |
153 """A class whose instances are single test cases. | 153 """A class whose instances are single test cases. |
154 | 154 |
155 By default, the test code itself should be placed in a method named | 155 By default, the test code itself should be placed in a method named |
(...skipping 25 matching lines...) Expand all Loading... |
181 # by assert methods using difflib. It is looked up as an instance attribute | 181 # by assert methods using difflib. It is looked up as an instance attribute |
182 # so can be configured by individual tests if required. | 182 # so can be configured by individual tests if required. |
183 | 183 |
184 maxDiff = 80*8 | 184 maxDiff = 80*8 |
185 | 185 |
186 # This attribute determines whether long messages (including repr of | 186 # This attribute determines whether long messages (including repr of |
187 # objects used in assert methods) will be printed on failure in *addition* | 187 # objects used in assert methods) will be printed on failure in *addition* |
188 # to any explicit message passed. | 188 # to any explicit message passed. |
189 | 189 |
190 longMessage = True | 190 longMessage = True |
191 | 191 |
192 # Attribute used by TestSuite for classSetUp | 192 # Attribute used by TestSuite for classSetUp |
193 | 193 |
194 _classSetupFailed = False | 194 _classSetupFailed = False |
195 | 195 |
196 def __init__(self, methodName='runTest'): | 196 def __init__(self, methodName='runTest'): |
197 """Create an instance of the class that will use the named test | 197 """Create an instance of the class that will use the named test |
198 method when executed. Raises a ValueError if the instance does | 198 method when executed. Raises a ValueError if the instance does |
199 not have a method with the specified name. | 199 not have a method with the specified name. |
200 """ | 200 """ |
201 self._testMethodName = methodName | 201 self._testMethodName = methodName |
202 self._resultForDoCleanups = None | 202 self._resultForDoCleanups = None |
203 try: | 203 try: |
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
237 def addCleanup(self, function, *args, **kwargs): | 237 def addCleanup(self, function, *args, **kwargs): |
238 """Add a function, with arguments, to be called when the test is | 238 """Add a function, with arguments, to be called when the test is |
239 completed. Functions added are called on a LIFO basis and are | 239 completed. Functions added are called on a LIFO basis and are |
240 called after tearDown on test failure or success. | 240 called after tearDown on test failure or success. |
241 | 241 |
242 Cleanup items are called even if setUp fails (unlike tearDown).""" | 242 Cleanup items are called even if setUp fails (unlike tearDown).""" |
243 self._cleanups.append((function, args, kwargs)) | 243 self._cleanups.append((function, args, kwargs)) |
244 | 244 |
245 def setUp(self): | 245 def setUp(self): |
246 "Hook method for setting up the test fixture before exercising it." | 246 "Hook method for setting up the test fixture before exercising it." |
247 | 247 |
248 @classmethod | 248 @classmethod |
249 def setUpClass(cls): | 249 def setUpClass(cls): |
250 "Hook method for setting up class fixture before running tests in the cl
ass." | 250 "Hook method for setting up class fixture before running tests in the cl
ass." |
251 | 251 |
252 @classmethod | 252 @classmethod |
253 def tearDownClass(cls): | 253 def tearDownClass(cls): |
254 "Hook method for deconstructing the class fixture after running all test
s in the class." | 254 "Hook method for deconstructing the class fixture after running all test
s in the class." |
255 | 255 |
256 def tearDown(self): | 256 def tearDown(self): |
257 "Hook method for deconstructing the test fixture after testing it." | 257 "Hook method for deconstructing the test fixture after testing it." |
(...skipping 29 matching lines...) Expand all Loading... |
287 | 287 |
288 def __hash__(self): | 288 def __hash__(self): |
289 return hash((type(self), self._testMethodName)) | 289 return hash((type(self), self._testMethodName)) |
290 | 290 |
291 def __str__(self): | 291 def __str__(self): |
292 return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) | 292 return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) |
293 | 293 |
294 def __repr__(self): | 294 def __repr__(self): |
295 return "<%s testMethod=%s>" % \ | 295 return "<%s testMethod=%s>" % \ |
296 (strclass(self.__class__), self._testMethodName) | 296 (strclass(self.__class__), self._testMethodName) |
297 | 297 |
298 def _addSkip(self, result, reason): | 298 def _addSkip(self, result, reason): |
299 addSkip = getattr(result, 'addSkip', None) | 299 addSkip = getattr(result, 'addSkip', None) |
300 if addSkip is not None: | 300 if addSkip is not None: |
301 addSkip(self, reason) | 301 addSkip(self, reason) |
302 else: | 302 else: |
303 warnings.warn("Use of a TestResult without an addSkip method is depr
ecated", | 303 warnings.warn("Use of a TestResult without an addSkip method is depr
ecated", |
304 DeprecationWarning, 2) | 304 DeprecationWarning, 2) |
305 result.addSuccess(self) | 305 result.addSuccess(self) |
306 | 306 |
307 def run(self, result=None): | 307 def run(self, result=None): |
308 orig_result = result | 308 orig_result = result |
309 if result is None: | 309 if result is None: |
310 result = self.defaultTestResult() | 310 result = self.defaultTestResult() |
311 startTestRun = getattr(result, 'startTestRun', None) | 311 startTestRun = getattr(result, 'startTestRun', None) |
312 if startTestRun is not None: | 312 if startTestRun is not None: |
313 startTestRun() | 313 startTestRun() |
314 | 314 |
315 self._resultForDoCleanups = result | 315 self._resultForDoCleanups = result |
316 result.startTest(self) | 316 result.startTest(self) |
317 | 317 |
318 testMethod = getattr(self, self._testMethodName) | 318 testMethod = getattr(self, self._testMethodName) |
319 | 319 |
320 if (getattr(self.__class__, "__unittest_skip__", False) or | 320 if (getattr(self.__class__, "__unittest_skip__", False) or |
321 getattr(testMethod, "__unittest_skip__", False)): | 321 getattr(testMethod, "__unittest_skip__", False)): |
322 # If the class or method was skipped. | 322 # If the class or method was skipped. |
323 try: | 323 try: |
324 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') | 324 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') |
325 or getattr(testMethod, '__unittest_skip_why__', '')) | 325 or getattr(testMethod, '__unittest_skip_why__', '')) |
326 self._addSkip(result, skip_why) | 326 self._addSkip(result, skip_why) |
327 finally: | 327 finally: |
328 result.stopTest(self) | 328 result.stopTest(self) |
329 return | 329 return |
330 try: | 330 try: |
331 success = False | 331 success = False |
332 try: | 332 try: |
333 self.setUp() | 333 self.setUp() |
334 except SkipTest, e: | 334 except SkipTest, e: |
335 self._addSkip(result, str(e)) | 335 self._addSkip(result, str(e)) |
336 except Exception: | 336 except Exception: |
337 result.addError(self, sys.exc_info()) | 337 result.addError(self, sys.exc_info()) |
338 else: | 338 else: |
339 try: | 339 try: |
340 testMethod() | 340 testMethod() |
341 except self.failureException: | 341 except self.failureException: |
342 result.addFailure(self, sys.exc_info()) | 342 result.addFailure(self, sys.exc_info()) |
343 except _ExpectedFailure, e: | 343 except _ExpectedFailure, e: |
344 addExpectedFailure = getattr(result, 'addExpectedFailure', N
one) | 344 addExpectedFailure = getattr(result, 'addExpectedFailure', N
one) |
345 if addExpectedFailure is not None: | 345 if addExpectedFailure is not None: |
346 addExpectedFailure(self, e.exc_info) | 346 addExpectedFailure(self, e.exc_info) |
347 else: | 347 else: |
348 warnings.warn("Use of a TestResult without an addExpecte
dFailure method is deprecated", | 348 warnings.warn("Use of a TestResult without an addExpecte
dFailure method is deprecated", |
349 DeprecationWarning) | 349 DeprecationWarning) |
350 result.addSuccess(self) | 350 result.addSuccess(self) |
351 except _UnexpectedSuccess: | 351 except _UnexpectedSuccess: |
352 addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess
', None) | 352 addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess
', None) |
353 if addUnexpectedSuccess is not None: | 353 if addUnexpectedSuccess is not None: |
354 addUnexpectedSuccess(self) | 354 addUnexpectedSuccess(self) |
355 else: | 355 else: |
356 warnings.warn("Use of a TestResult without an addUnexpec
tedSuccess method is deprecated", | 356 warnings.warn("Use of a TestResult without an addUnexpec
tedSuccess method is deprecated", |
357 DeprecationWarning) | 357 DeprecationWarning) |
358 result.addFailure(self, sys.exc_info()) | 358 result.addFailure(self, sys.exc_info()) |
359 except SkipTest, e: | 359 except SkipTest, e: |
360 self._addSkip(result, str(e)) | 360 self._addSkip(result, str(e)) |
361 except Exception: | 361 except Exception: |
362 result.addError(self, sys.exc_info()) | 362 result.addError(self, sys.exc_info()) |
363 else: | 363 else: |
364 success = True | 364 success = True |
365 | 365 |
366 try: | 366 try: |
(...skipping 101 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
468 do_something() | 468 do_something() |
469 the_exception = cm.exception | 469 the_exception = cm.exception |
470 self.assertEqual(the_exception.error_code, 3) | 470 self.assertEqual(the_exception.error_code, 3) |
471 """ | 471 """ |
472 if callableObj is None: | 472 if callableObj is None: |
473 return _AssertRaisesContext(excClass, self) | 473 return _AssertRaisesContext(excClass, self) |
474 try: | 474 try: |
475 callableObj(*args, **kwargs) | 475 callableObj(*args, **kwargs) |
476 except excClass: | 476 except excClass: |
477 return | 477 return |
478 | 478 |
479 if hasattr(excClass,'__name__'): | 479 if hasattr(excClass,'__name__'): |
480 excName = excClass.__name__ | 480 excName = excClass.__name__ |
481 else: | 481 else: |
482 excName = str(excClass) | 482 excName = str(excClass) |
483 raise self.failureException, "%s not raised" % excName | 483 raise self.failureException, "%s not raised" % excName |
484 | 484 |
485 def _getAssertEqualityFunc(self, first, second): | 485 def _getAssertEqualityFunc(self, first, second): |
486 """Get a detailed comparison function for the types of the two args. | 486 """Get a detailed comparison function for the types of the two args. |
487 | 487 |
488 Returns: A callable accepting (first, second, msg=None) that will | 488 Returns: A callable accepting (first, second, msg=None) that will |
(...skipping 29 matching lines...) Expand all Loading... |
518 operator. | 518 operator. |
519 """ | 519 """ |
520 assertion_func = self._getAssertEqualityFunc(first, second) | 520 assertion_func = self._getAssertEqualityFunc(first, second) |
521 assertion_func(first, second, msg=msg) | 521 assertion_func(first, second, msg=msg) |
522 | 522 |
523 def assertNotEqual(self, first, second, msg=None): | 523 def assertNotEqual(self, first, second, msg=None): |
524 """Fail if the two objects are equal as determined by the '==' | 524 """Fail if the two objects are equal as determined by the '==' |
525 operator. | 525 operator. |
526 """ | 526 """ |
527 if not first != second: | 527 if not first != second: |
528 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), | 528 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), |
529 safe_repr(second))) | 529 safe_repr(second))) |
530 raise self.failureException(msg) | 530 raise self.failureException(msg) |
531 | 531 |
532 def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None
): | 532 def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None
): |
533 """Fail if the two objects are unequal as determined by their | 533 """Fail if the two objects are unequal as determined by their |
534 difference rounded to the given number of decimal places | 534 difference rounded to the given number of decimal places |
535 (default 7) and comparing to zero, or by comparing that the | 535 (default 7) and comparing to zero, or by comparing that the |
536 between the two objects is more than the given delta. | 536 between the two objects is more than the given delta. |
537 | 537 |
538 Note that decimal places (from zero) are usually not the same | 538 Note that decimal places (from zero) are usually not the same |
539 as significant digits (measured from the most signficant digit). | 539 as significant digits (measured from the most signficant digit). |
540 | 540 |
541 If the two objects compare equal then they will automatically | 541 If the two objects compare equal then they will automatically |
542 compare almost equal. | 542 compare almost equal. |
543 """ | 543 """ |
544 if first == second: | 544 if first == second: |
545 # shortcut | 545 # shortcut |
546 return | 546 return |
547 if delta is not None and places is not None: | 547 if delta is not None and places is not None: |
548 raise TypeError("specify delta or places not both") | 548 raise TypeError("specify delta or places not both") |
549 | 549 |
550 if delta is not None: | 550 if delta is not None: |
551 if abs(first - second) <= delta: | 551 if abs(first - second) <= delta: |
552 return | 552 return |
553 | 553 |
554 standardMsg = '%s != %s within %s delta' % (safe_repr(first), | 554 standardMsg = '%s != %s within %s delta' % (safe_repr(first), |
555 safe_repr(second), | 555 safe_repr(second), |
556 safe_repr(delta)) | 556 safe_repr(delta)) |
557 else: | 557 else: |
558 if places is None: | 558 if places is None: |
559 places = 7 | 559 places = 7 |
560 | 560 |
561 if round(abs(second-first), places) == 0: | 561 if round(abs(second-first), places) == 0: |
562 return | 562 return |
563 | 563 |
564 standardMsg = '%s != %s within %r places' % (safe_repr(first), | 564 standardMsg = '%s != %s within %r places' % (safe_repr(first), |
565 safe_repr(second), | 565 safe_repr(second), |
566 places) | 566 places) |
567 msg = self._formatMessage(msg, standardMsg) | 567 msg = self._formatMessage(msg, standardMsg) |
568 raise self.failureException(msg) | 568 raise self.failureException(msg) |
569 | 569 |
570 def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=N
one): | 570 def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=N
one): |
571 """Fail if the two objects are equal as determined by their | 571 """Fail if the two objects are equal as determined by their |
572 difference rounded to the given number of decimal places | 572 difference rounded to the given number of decimal places |
573 (default 7) and comparing to zero, or by comparing that the | 573 (default 7) and comparing to zero, or by comparing that the |
574 between the two objects is less than the given delta. | 574 between the two objects is less than the given delta. |
575 | 575 |
576 Note that decimal places (from zero) are usually not the same | 576 Note that decimal places (from zero) are usually not the same |
577 as significant digits (measured from the most signficant digit). | 577 as significant digits (measured from the most signficant digit). |
578 | 578 |
579 Objects that are equal automatically fail. | 579 Objects that are equal automatically fail. |
580 """ | 580 """ |
581 if delta is not None and places is not None: | 581 if delta is not None and places is not None: |
582 raise TypeError("specify delta or places not both") | 582 raise TypeError("specify delta or places not both") |
583 if delta is not None: | 583 if delta is not None: |
584 if not (first == second) and abs(first - second) > delta: | 584 if not (first == second) and abs(first - second) > delta: |
585 return | 585 return |
586 standardMsg = '%s == %s within %s delta' % (safe_repr(first), | 586 standardMsg = '%s == %s within %s delta' % (safe_repr(first), |
587 safe_repr(second), | 587 safe_repr(second), |
588 safe_repr(delta)) | 588 safe_repr(delta)) |
589 else: | 589 else: |
590 if places is None: | 590 if places is None: |
591 places = 7 | 591 places = 7 |
592 if not (first == second) and round(abs(second-first), places) != 0: | 592 if not (first == second) and round(abs(second-first), places) != 0: |
593 return | 593 return |
594 standardMsg = '%s == %s within %r places' % (safe_repr(first), | 594 standardMsg = '%s == %s within %r places' % (safe_repr(first), |
595 safe_repr(second), | 595 safe_repr(second), |
596 places) | 596 places) |
597 | 597 |
598 msg = self._formatMessage(msg, standardMsg) | 598 msg = self._formatMessage(msg, standardMsg) |
599 raise self.failureException(msg) | 599 raise self.failureException(msg) |
600 | 600 |
601 # Synonyms for assertion methods | 601 # Synonyms for assertion methods |
602 | 602 |
603 # The plurals are undocumented. Keep them that way to discourage use. | 603 # The plurals are undocumented. Keep them that way to discourage use. |
604 # Do not add more. Do not remove. | 604 # Do not add more. Do not remove. |
(...skipping 196 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
801 lines.append('Items in the second set but not the first:') | 801 lines.append('Items in the second set but not the first:') |
802 for item in difference2: | 802 for item in difference2: |
803 lines.append(repr(item)) | 803 lines.append(repr(item)) |
804 | 804 |
805 standardMsg = '\n'.join(lines) | 805 standardMsg = '\n'.join(lines) |
806 self.fail(self._formatMessage(msg, standardMsg)) | 806 self.fail(self._formatMessage(msg, standardMsg)) |
807 | 807 |
808 def assertIn(self, member, container, msg=None): | 808 def assertIn(self, member, container, msg=None): |
809 """Just like self.assertTrue(a in b), but with a nicer default message."
"" | 809 """Just like self.assertTrue(a in b), but with a nicer default message."
"" |
810 if member not in container: | 810 if member not in container: |
811 standardMsg = '%s not found in %s' % (safe_repr(member), | 811 standardMsg = '%s not found in %s' % (safe_repr(member), |
812 safe_repr(container)) | 812 safe_repr(container)) |
813 self.fail(self._formatMessage(msg, standardMsg)) | 813 self.fail(self._formatMessage(msg, standardMsg)) |
814 | 814 |
815 def assertNotIn(self, member, container, msg=None): | 815 def assertNotIn(self, member, container, msg=None): |
816 """Just like self.assertTrue(a not in b), but with a nicer default messa
ge.""" | 816 """Just like self.assertTrue(a not in b), but with a nicer default messa
ge.""" |
817 if member in container: | 817 if member in container: |
818 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), | 818 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), |
819 safe_repr(container)
) | 819 safe_repr(container)
) |
820 self.fail(self._formatMessage(msg, standardMsg)) | 820 self.fail(self._formatMessage(msg, standardMsg)) |
821 | 821 |
822 def assertIs(self, expr1, expr2, msg=None): | 822 def assertIs(self, expr1, expr2, msg=None): |
823 """Just like self.assertTrue(a is b), but with a nicer default message."
"" | 823 """Just like self.assertTrue(a is b), but with a nicer default message."
"" |
824 if expr1 is not expr2: | 824 if expr1 is not expr2: |
825 standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2)) | 825 standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2)) |
826 self.fail(self._formatMessage(msg, standardMsg)) | 826 self.fail(self._formatMessage(msg, standardMsg)) |
827 | 827 |
828 def assertIsNot(self, expr1, expr2, msg=None): | 828 def assertIsNot(self, expr1, expr2, msg=None): |
(...skipping 16 matching lines...) Expand all Loading... |
845 | 845 |
846 def assertDictContainsSubset(self, expected, actual, msg=None): | 846 def assertDictContainsSubset(self, expected, actual, msg=None): |
847 """Checks whether actual is a superset of expected.""" | 847 """Checks whether actual is a superset of expected.""" |
848 missing = [] | 848 missing = [] |
849 mismatched = [] | 849 mismatched = [] |
850 for key, value in expected.iteritems(): | 850 for key, value in expected.iteritems(): |
851 if key not in actual: | 851 if key not in actual: |
852 missing.append(key) | 852 missing.append(key) |
853 elif value != actual[key]: | 853 elif value != actual[key]: |
854 mismatched.append('%s, expected: %s, actual: %s' % | 854 mismatched.append('%s, expected: %s, actual: %s' % |
855 (safe_repr(key), safe_repr(value), | 855 (safe_repr(key), safe_repr(value), |
856 safe_repr(actual[key]))) | 856 safe_repr(actual[key]))) |
857 | 857 |
858 if not (missing or mismatched): | 858 if not (missing or mismatched): |
859 return | 859 return |
860 | 860 |
861 standardMsg = '' | 861 standardMsg = '' |
862 if missing: | 862 if missing: |
863 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in | 863 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in |
864 missing) | 864 missing) |
865 if mismatched: | 865 if mismatched: |
866 if standardMsg: | 866 if standardMsg: |
867 standardMsg += '; ' | 867 standardMsg += '; ' |
868 standardMsg += 'Mismatched values: %s' % ','.join(mismatched) | 868 standardMsg += 'Mismatched values: %s' % ','.join(mismatched) |
869 | 869 |
870 self.fail(self._formatMessage(msg, standardMsg)) | 870 self.fail(self._formatMessage(msg, standardMsg)) |
871 | 871 |
872 def assertItemsEqual(self, expected_seq, actual_seq, msg=None): | 872 def assertItemsEqual(self, expected_seq, actual_seq, msg=None): |
873 """An unordered sequence specific comparison. It asserts that | 873 """An unordered sequence specific comparison. It asserts that |
874 expected_seq and actual_seq contain the same elements. It is | 874 expected_seq and actual_seq contain the same elements. It is |
875 the equivalent of:: | 875 the equivalent of:: |
876 | 876 |
877 self.assertEqual(sorted(expected_seq), sorted(actual_seq)) | 877 self.assertEqual(sorted(expected_seq), sorted(actual_seq)) |
878 | 878 |
879 Raises with an error message listing which elements of expected_seq | 879 Raises with an error message listing which elements of expected_seq |
880 are missing from actual_seq and vice versa if any. | 880 are missing from actual_seq and vice versa if any. |
881 | 881 |
882 Asserts that each element has the same count in both sequences. | 882 Asserts that each element has the same count in both sequences. |
883 Example: | 883 Example: |
884 - [0, 1, 1] and [1, 0, 1] compare equal. | 884 - [0, 1, 1] and [1, 0, 1] compare equal. |
885 - [0, 0, 1] and [0, 1] compare unequal. | 885 - [0, 0, 1] and [0, 1] compare unequal. |
886 """ | 886 """ |
887 try: | 887 try: |
888 expected = sorted(expected_seq) | 888 expected = sorted(expected_seq) |
889 actual = sorted(actual_seq) | 889 actual = sorted(actual_seq) |
890 except TypeError: | 890 except TypeError: |
891 # Unsortable items (example: set(), complex(), ...) | 891 # Unsortable items (example: set(), complex(), ...) |
892 expected = list(expected_seq) | 892 expected = list(expected_seq) |
893 actual = list(actual_seq) | 893 actual = list(actual_seq) |
894 missing, unexpected = unorderable_list_difference( | 894 missing, unexpected = unorderable_list_difference( |
895 expected, actual, ignore_duplicate=False | 895 expected, actual, ignore_duplicate=False |
896 ) | 896 ) |
897 else: | 897 else: |
898 return self.assertSequenceEqual(expected, actual, msg=msg) | 898 return self.assertSequenceEqual(expected, actual, msg=msg) |
899 | 899 |
900 errors = [] | 900 errors = [] |
901 if missing: | 901 if missing: |
902 errors.append('Expected, but missing:\n %s' % | 902 errors.append('Expected, but missing:\n %s' % |
903 safe_repr(missing)) | 903 safe_repr(missing)) |
904 if unexpected: | 904 if unexpected: |
905 errors.append('Unexpected, but present:\n %s' % | 905 errors.append('Unexpected, but present:\n %s' % |
906 safe_repr(unexpected)) | 906 safe_repr(unexpected)) |
907 if errors: | 907 if errors: |
908 standardMsg = '\n'.join(errors) | 908 standardMsg = '\n'.join(errors) |
909 self.fail(self._formatMessage(msg, standardMsg)) | 909 self.fail(self._formatMessage(msg, standardMsg)) |
910 | 910 |
911 def assertMultiLineEqual(self, first, second, msg=None): | 911 def assertMultiLineEqual(self, first, second, msg=None): |
912 """Assert that two multi-line strings are equal.""" | 912 """Assert that two multi-line strings are equal.""" |
913 self.assert_(isinstance(first, basestring), ( | 913 self.assert_(isinstance(first, basestring), ( |
914 'First argument is not a string')) | 914 'First argument is not a string')) |
915 self.assert_(isinstance(second, basestring), ( | 915 self.assert_(isinstance(second, basestring), ( |
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
987 return _AssertRaisesContext(expected_exception, self, expected_regex
p) | 987 return _AssertRaisesContext(expected_exception, self, expected_regex
p) |
988 try: | 988 try: |
989 callable_obj(*args, **kwargs) | 989 callable_obj(*args, **kwargs) |
990 except expected_exception, exc_value: | 990 except expected_exception, exc_value: |
991 if isinstance(expected_regexp, basestring): | 991 if isinstance(expected_regexp, basestring): |
992 expected_regexp = re.compile(expected_regexp) | 992 expected_regexp = re.compile(expected_regexp) |
993 if not expected_regexp.search(str(exc_value)): | 993 if not expected_regexp.search(str(exc_value)): |
994 raise self.failureException('"%s" does not match "%s"' % | 994 raise self.failureException('"%s" does not match "%s"' % |
995 (expected_regexp.pattern, str(exc_value))) | 995 (expected_regexp.pattern, str(exc_value))) |
996 else: | 996 else: |
997 if hasattr(expected_exception, '__name__'): | 997 if hasattr(expected_exception, '__name__'): |
998 excName = expected_exception.__name__ | 998 excName = expected_exception.__name__ |
999 else: | 999 else: |
1000 excName = str(expected_exception) | 1000 excName = str(expected_exception) |
1001 raise self.failureException, "%s not raised" % excName | 1001 raise self.failureException, "%s not raised" % excName |
1002 | 1002 |
1003 | 1003 |
1004 def assertRegexpMatches(self, text, expected_regexp, msg=None): | 1004 def assertRegexpMatches(self, text, expected_regexp, msg=None): |
1005 """Fail the test unless the text matches the regular expression.""" | 1005 """Fail the test unless the text matches the regular expression.""" |
1006 if isinstance(expected_regexp, basestring): | 1006 if isinstance(expected_regexp, basestring): |
1007 expected_regexp = re.compile(expected_regexp) | 1007 expected_regexp = re.compile(expected_regexp) |
1008 if not expected_regexp.search(text): | 1008 if not expected_regexp.search(text): |
1009 msg = msg or "Regexp didn't match" | 1009 msg = msg or "Regexp didn't match" |
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1075 | 1075 |
1076 def __repr__(self): | 1076 def __repr__(self): |
1077 return "<%s testFunc=%s>" % (strclass(self.__class__), | 1077 return "<%s testFunc=%s>" % (strclass(self.__class__), |
1078 self._testFunc) | 1078 self._testFunc) |
1079 | 1079 |
1080 def shortDescription(self): | 1080 def shortDescription(self): |
1081 if self._description is not None: | 1081 if self._description is not None: |
1082 return self._description | 1082 return self._description |
1083 doc = self._testFunc.__doc__ | 1083 doc = self._testFunc.__doc__ |
1084 return doc and doc.split("\n")[0].strip() or None | 1084 return doc and doc.split("\n")[0].strip() or None |
OLD | NEW |