Debian Codegraph @

Lib/unittest/case.py

raw
1 """Test case implementation"""
2
3 import sys
4 import functools
5 import difflib
6 import pprint
7 import re
8 import warnings
9 import collections
10 import contextlib
11 import traceback
12 import time
13 import types
14
15 from . import result
16 from .util import (strclass, safe_repr, _count_diff_all_purpose,
17 _count_diff_hashable, _common_shorten_repr)
18
19 __unittest = True
20
21 _subtest_msg_sentinel = object()
22
23 DIFF_OMITTED = ('\nDiff is %s characters long. '
24 'Set self.maxDiff to None to see it.')
25
26 class SkipTest(Exception):
27 """
28 Raise this exception in a test to skip it.
29
30 Usually you can use TestCase.skipTest() or one of the skipping decorators
31 instead of raising this directly.
32 """
33
34 class _ShouldStop(Exception):
35 """
36 The test should stop.
37 """
38
39 class _UnexpectedSuccess(Exception):
40 """
41 The test was supposed to fail, but it didn't!
42 """
43
44
45 class _Outcome(object):
46 def __init__(self, result=None):
47 self.expecting_failure = False
48 self.result = result
49 self.result_supports_subtests = hasattr(result, "addSubTest")
50 self.success = True
51 self.expectedFailure = None
52
53 @contextlib.contextmanager
54 def testPartExecutor(self, test_case, subTest=False):
55 old_success = self.success
56 self.success = True
57 try:
58 yield
59 except KeyboardInterrupt:
60 raise
61 except SkipTest as e:
62 self.success = False
63 _addSkip(self.result, test_case, str(e))
64 except _ShouldStop:
65 pass
66 except:
67 exc_info = sys.exc_info()
68 if self.expecting_failure:
69 self.expectedFailure = exc_info
70 else:
71 self.success = False
72 if subTest:
73 self.result.addSubTest(test_case.test_case, test_case, exc_info)
74 else:
75 _addError(self.result, test_case, exc_info)
76 # explicitly break a reference cycle:
77 # exc_info -> frame -> exc_info
78 exc_info = None
79 else:
80 if subTest and self.success:
81 self.result.addSubTest(test_case.test_case, test_case, None)
82 finally:
83 self.success = self.success and old_success
84
85
86 def _addSkip(result, test_case, reason):
87 addSkip = getattr(result, 'addSkip', None)
88 if addSkip is not None:
89 addSkip(test_case, reason)
90 else:
91 warnings.warn("TestResult has no addSkip method, skips not reported",
92 RuntimeWarning, 2)
93 result.addSuccess(test_case)
94
95 def _addError(result, test, exc_info):
96 if result is not None and exc_info is not None:
97 if issubclass(exc_info[0], test.failureException):
98 result.addFailure(test, exc_info)
99 else:
100 result.addError(test, exc_info)
101
102 def _id(obj):
103 return obj
104
105
106 def _enter_context(cm, addcleanup):
107 # We look up the special methods on the type to match the with
108 # statement.
109 cls = type(cm)
110 try:
111 enter = cls.__enter__
112 exit = cls.__exit__
113 except AttributeError:
114 msg = (f"'{cls.__module__}.{cls.__qualname__}' object does "
115 "not support the context manager protocol")
116 try:
117 cls.__aenter__
118 cls.__aexit__
119 except AttributeError:
120 pass
121 else:
122 msg += (" but it supports the asynchronous context manager "
123 "protocol. Did you mean to use enterAsyncContext()?")
124 raise TypeError(msg) from None
125 result = enter(cm)
126 addcleanup(exit, cm, None, None, None)
127 return result
128
129
130 _module_cleanups = []
131 def addModuleCleanup(function, /, *args, **kwargs):
132 """Same as addCleanup, except the cleanup items are called even if
133 setUpModule fails (unlike tearDownModule)."""
134 _module_cleanups.append((function, args, kwargs))
135
136 def enterModuleContext(cm):
137 """Same as enterContext, but module-wide."""
138 return _enter_context(cm, addModuleCleanup)
139
140
141 def doModuleCleanups():
142 """Execute all module cleanup functions. Normally called for you after
143 tearDownModule."""
144 exceptions = []
145 while _module_cleanups:
146 function, args, kwargs = _module_cleanups.pop()
147 try:
148 function(*args, **kwargs)
149 except Exception as exc:
150 exceptions.append(exc)
151 if exceptions:
152 # Swallows all but first exception. If a multi-exception handler
153 # gets written we should use that here instead.
154 raise exceptions[0]
155
156
157 def skip(reason):
158 """
159 Unconditionally skip a test.
160 """
161 def decorator(test_item):
162 if not isinstance(test_item, type):
163 @functools.wraps(test_item)
164 def skip_wrapper(*args, **kwargs):
165 raise SkipTest(reason)
166 test_item = skip_wrapper
167
168 test_item.__unittest_skip__ = True
169 test_item.__unittest_skip_why__ = reason
170 return test_item
171 if isinstance(reason, types.FunctionType):
172 test_item = reason
173 reason = ''
174 return decorator(test_item)
175 return decorator
176
177 def skipIf(condition, reason):
178 """
179 Skip a test if the condition is true.
180 """
181 if condition:
182 return skip(reason)
183 return _id
184
185 def skipUnless(condition, reason):
186 """
187 Skip a test unless the condition is true.
188 """
189 if not condition:
190 return skip(reason)
191 return _id
192
193 def expectedFailure(test_item):
194 test_item.__unittest_expecting_failure__ = True
195 return test_item
196
197 def _is_subtype(expected, basetype):
198 if isinstance(expected, tuple):
199 return all(_is_subtype(e, basetype) for e in expected)
200 return isinstance(expected, type) and issubclass(expected, basetype)
201
202 class _BaseTestCaseContext:
203
204 def __init__(self, test_case):
205 self.test_case = test_case
206
207 def _raiseFailure(self, standardMsg):
208 msg = self.test_case._formatMessage(self.msg, standardMsg)
209 raise self.test_case.failureException(msg)
210
211 class _AssertRaisesBaseContext(_BaseTestCaseContext):
212
213 def __init__(self, expected, test_case, expected_regex=None):
214 _BaseTestCaseContext.__init__(self, test_case)
215 self.expected = expected
216 self.test_case = test_case
217 if expected_regex is not None:
218 expected_regex = re.compile(expected_regex)
219 self.expected_regex = expected_regex
220 self.obj_name = None
221 self.msg = None
222
223 def handle(self, name, args, kwargs):
224 """
225 If args is empty, assertRaises/Warns is being used as a
226 context manager, so check for a 'msg' kwarg and return self.
227 If args is not empty, call a callable passing positional and keyword
228 arguments.
229 """
230 try:
231 if not _is_subtype(self.expected, self._base_type):
232 raise TypeError('%s() arg 1 must be %s' %
233 (name, self._base_type_str))
234 if not args:
235 self.msg = kwargs.pop('msg', None)
236 if kwargs:
237 raise TypeError('%r is an invalid keyword argument for '
238 'this function' % (next(iter(kwargs)),))
239 return self
240
241 callable_obj, *args = args
242 try:
243 self.obj_name = callable_obj.__name__
244 except AttributeError:
245 self.obj_name = str(callable_obj)
246 with self:
247 callable_obj(*args, **kwargs)
248 finally:
249 # bpo-23890: manually break a reference cycle
250 self = None
251
252
253 class _AssertRaisesContext(_AssertRaisesBaseContext):
254 """A context manager used to implement TestCase.assertRaises* methods."""
255
256 _base_type = BaseException
257 _base_type_str = 'an exception type or tuple of exception types'
258
259 def __enter__(self):
260 return self
261
262 def __exit__(self, exc_type, exc_value, tb):
263 if exc_type is None:
264 try:
265 exc_name = self.expected.__name__
266 except AttributeError:
267 exc_name = str(self.expected)
268 if self.obj_name:
269 self._raiseFailure("{} not raised by {}".format(exc_name,
270 self.obj_name))
271 else:
272 self._raiseFailure("{} not raised".format(exc_name))
273 else:
274 traceback.clear_frames(tb)
275 if not issubclass(exc_type, self.expected):
276 # let unexpected exceptions pass through
277 return False
278 # store exception, without traceback, for later retrieval
279 self.exception = exc_value.with_traceback(None)
280 if self.expected_regex is None:
281 return True
282
283 expected_regex = self.expected_regex
284 if not expected_regex.search(str(exc_value)):
285 self._raiseFailure('"{}" does not match "{}"'.format(
286 expected_regex.pattern, str(exc_value)))
287 return True
288
289 __class_getitem__ = classmethod(types.GenericAlias)
290
291
292 class _AssertWarnsContext(_AssertRaisesBaseContext):
293 """A context manager used to implement TestCase.assertWarns* methods."""
294
295 _base_type = Warning
296 _base_type_str = 'a warning type or tuple of warning types'
297
298 def __enter__(self):
299 # The __warningregistry__'s need to be in a pristine state for tests
300 # to work properly.
301 for v in list(sys.modules.values()):
302 if getattr(v, '__warningregistry__', None):
303 v.__warningregistry__ = {}
304 self.warnings_manager = warnings.catch_warnings(record=True)
305 self.warnings = self.warnings_manager.__enter__()
306 warnings.simplefilter("always", self.expected)
307 return self
308
309 def __exit__(self, exc_type, exc_value, tb):
310 self.warnings_manager.__exit__(exc_type, exc_value, tb)
311 if exc_type is not None:
312 # let unexpected exceptions pass through
313 return
314 try:
315 exc_name = self.expected.__name__
316 except AttributeError:
317 exc_name = str(self.expected)
318 first_matching = None
319 for m in self.warnings:
320 w = m.message
321 if not isinstance(w, self.expected):
322 continue
323 if first_matching is None:
324 first_matching = w
325 if (self.expected_regex is not None and
326 not self.expected_regex.search(str(w))):
327 continue
328 # store warning for later retrieval
329 self.warning = w
330 self.filename = m.filename
331 self.lineno = m.lineno
332 return
333 # Now we simply try to choose a helpful failure message
334 if first_matching is not None:
335 self._raiseFailure('"{}" does not match "{}"'.format(
336 self.expected_regex.pattern, str(first_matching)))
337 if self.obj_name:
338 self._raiseFailure("{} not triggered by {}".format(exc_name,
339 self.obj_name))
340 else:
341 self._raiseFailure("{} not triggered".format(exc_name))
342
343
344 class _AssertNotWarnsContext(_AssertWarnsContext):
345
346 def __exit__(self, exc_type, exc_value, tb):
347 self.warnings_manager.__exit__(exc_type, exc_value, tb)
348 if exc_type is not None:
349 # let unexpected exceptions pass through
350 return
351 try:
352 exc_name = self.expected.__name__
353 except AttributeError:
354 exc_name = str(self.expected)
355 for m in self.warnings:
356 w = m.message
357 if isinstance(w, self.expected):
358 self._raiseFailure(f"{exc_name} triggered")
359
360
361 class _OrderedChainMap(collections.ChainMap):
362 def __iter__(self):
363 seen = set()
364 for mapping in self.maps:
365 for k in mapping:
366 if k not in seen:
367 seen.add(k)
368 yield k
369
370
371 class TestCase(object):
372 """A class whose instances are single test cases.
373
374 By default, the test code itself should be placed in a method named
375 'runTest'.
376
377 If the fixture may be used for many test cases, create as
378 many test methods as are needed. When instantiating such a TestCase
379 subclass, specify in the constructor arguments the name of the test method
380 that the instance is to execute.
381
382 Test authors should subclass TestCase for their own tests. Construction
383 and deconstruction of the test's environment ('fixture') can be
384 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
385
386 If it is necessary to override the __init__ method, the base class
387 __init__ method must always be called. It is important that subclasses
388 should not change the signature of their __init__ method, since instances
389 of the classes are instantiated automatically by parts of the framework
390 in order to be run.
391
392 When subclassing TestCase, you can set these attributes:
393 * failureException: determines which exception will be raised when
394 the instance's assertion methods fail; test methods raising this
395 exception will be deemed to have 'failed' rather than 'errored'.
396 * longMessage: determines whether long messages (including repr of
397 objects used in assert methods) will be printed on failure in *addition*
398 to any explicit message passed.
399 * maxDiff: sets the maximum length of a diff in failure messages
400 by assert methods using difflib. It is looked up as an instance
401 attribute so can be configured by individual tests if required.
402 """
403
404 failureException = AssertionError
405
406 longMessage = True
407
408 maxDiff = 80*8
409
410 # If a string is longer than _diffThreshold, use normal comparison instead
411 # of difflib. See #11763.
412 _diffThreshold = 2**16
413
414 def __init_subclass__(cls, *args, **kwargs):
415 # Attribute used by TestSuite for classSetUp
416 cls._classSetupFailed = False
417 cls._class_cleanups = []
418 super().__init_subclass__(*args, **kwargs)
419
420 def __init__(self, methodName='runTest'):
421 """Create an instance of the class that will use the named test
422 method when executed. Raises a ValueError if the instance does
423 not have a method with the specified name.
424 """
425 self._testMethodName = methodName
426 self._outcome = None
427 self._testMethodDoc = 'No test'
428 try:
429 testMethod = getattr(self, methodName)
430 except AttributeError:
431 if methodName != 'runTest':
432 # we allow instantiation with no explicit method name
433 # but not an *incorrect* or missing method name
434 raise ValueError("no such test method in %s: %s" %
435 (self.__class__, methodName))
436 else:
437 self._testMethodDoc = testMethod.__doc__
438 self._cleanups = []
439 self._subtest = None
440
441 # Map types to custom assertEqual functions that will compare
442 # instances of said type in more detail to generate a more useful
443 # error message.
444 self._type_equality_funcs = {}
445 self.addTypeEqualityFunc(dict, 'assertDictEqual')
446 self.addTypeEqualityFunc(list, 'assertListEqual')
447 self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
448 self.addTypeEqualityFunc(set, 'assertSetEqual')
449 self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
450 self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
451
452 def addTypeEqualityFunc(self, typeobj, function):
453 """Add a type specific assertEqual style function to compare a type.
454
455 This method is for use by TestCase subclasses that need to register
456 their own type equality functions to provide nicer error messages.
457
458 Args:
459 typeobj: The data type to call this function on when both values
460 are of the same type in assertEqual().
461 function: The callable taking two arguments and an optional
462 msg= argument that raises self.failureException with a
463 useful error message when the two arguments are not equal.
464 """
465 self._type_equality_funcs[typeobj] = function
466
467 def addCleanup(self, function, /, *args, **kwargs):
468 """Add a function, with arguments, to be called when the test is
469 completed. Functions added are called on a LIFO basis and are
470 called after tearDown on test failure or success.
471
472 Cleanup items are called even if setUp fails (unlike tearDown)."""
473 self._cleanups.append((function, args, kwargs))
474
475 def enterContext(self, cm):
476 """Enters the supplied context manager.
477
478 If successful, also adds its __exit__ method as a cleanup
479 function and returns the result of the __enter__ method.
480 """
481 return _enter_context(cm, self.addCleanup)
482
483 @classmethod
484 def addClassCleanup(cls, function, /, *args, **kwargs):
485 """Same as addCleanup, except the cleanup items are called even if
486 setUpClass fails (unlike tearDownClass)."""
487 cls._class_cleanups.append((function, args, kwargs))
488
489 @classmethod
490 def enterClassContext(cls, cm):
491 """Same as enterContext, but class-wide."""
492 return _enter_context(cm, cls.addClassCleanup)
493
494 def setUp(self):
495 "Hook method for setting up the test fixture before exercising it."
496 pass
497
498 def tearDown(self):
499 "Hook method for deconstructing the test fixture after testing it."
500 pass
501
502 @classmethod
503 def setUpClass(cls):
504 "Hook method for setting up class fixture before running tests in the class."
505
506 @classmethod
507 def tearDownClass(cls):
508 "Hook method for deconstructing the class fixture after running all tests in the class."
509
510 def countTestCases(self):
511 return 1
512
513 def defaultTestResult(self):
514 return result.TestResult()
515
516 def shortDescription(self):
517 """Returns a one-line description of the test, or None if no
518 description has been provided.
519
520 The default implementation of this method returns the first line of
521 the specified test method's docstring.
522 """
523 doc = self._testMethodDoc
524 return doc.strip().split("\n")[0].strip() if doc else None
525
526
527 def id(self):
528 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
529
530 def __eq__(self, other):
531 if type(self) is not type(other):
532 return NotImplemented
533
534 return self._testMethodName == other._testMethodName
535
536 def __hash__(self):
537 return hash((type(self), self._testMethodName))
538
539 def __str__(self):
540 return "%s (%s.%s)" % (self._testMethodName, strclass(self.__class__), self._testMethodName)
541
542 def __repr__(self):
543 return "<%s testMethod=%s>" % \
544 (strclass(self.__class__), self._testMethodName)
545
546 @contextlib.contextmanager
547 def subTest(self, msg=_subtest_msg_sentinel, **params):
548 """Return a context manager that will return the enclosed block
549 of code in a subtest identified by the optional message and
550 keyword parameters. A failure in the subtest marks the test
551 case as failed but resumes execution at the end of the enclosed
552 block, allowing further test code to be executed.
553 """
554 if self._outcome is None or not self._outcome.result_supports_subtests:
555 yield
556 return
557 parent = self._subtest
558 if parent is None:
559 params_map = _OrderedChainMap(params)
560 else:
561 params_map = parent.params.new_child(params)
562 self._subtest = _SubTest(self, msg, params_map)
563 try:
564 with self._outcome.testPartExecutor(self._subtest, subTest=True):
565 yield
566 if not self._outcome.success:
567 result = self._outcome.result
568 if result is not None and result.failfast:
569 raise _ShouldStop
570 elif self._outcome.expectedFailure:
571 # If the test is expecting a failure, we really want to
572 # stop now and register the expected failure.
573 raise _ShouldStop
574 finally:
575 self._subtest = parent
576
577 def _addExpectedFailure(self, result, exc_info):
578 try:
579 addExpectedFailure = result.addExpectedFailure
580 except AttributeError:
581 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
582 RuntimeWarning)
583 result.addSuccess(self)
584 else:
585 addExpectedFailure(self, exc_info)
586
587 def _addUnexpectedSuccess(self, result):
588 try:
589 addUnexpectedSuccess = result.addUnexpectedSuccess
590 except AttributeError:
591 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure",
592 RuntimeWarning)
593 # We need to pass an actual exception and traceback to addFailure,
594 # otherwise the legacy result can choke.
595 try:
596 raise _UnexpectedSuccess from None
597 except _UnexpectedSuccess:
598 result.addFailure(self, sys.exc_info())
599 else:
600 addUnexpectedSuccess(self)
601
602 def _addDuration(self, result, elapsed):
603 try:
604 addDuration = result.addDuration
605 except AttributeError:
606 warnings.warn("TestResult has no addDuration method",
607 RuntimeWarning)
608 else:
609 addDuration(self, elapsed)
610
611 def _callSetUp(self):
612 self.setUp()
613
614 def _callTestMethod(self, method):
615 result = method()
616 if result is not None:
617 import inspect
618 msg = (
619 f'It is deprecated to return a value that is not None '
620 f'from a test case ({method} returned {type(result).__name__!r})'
621 )
622 if inspect.iscoroutine(result):
623 msg += (
624 '. Maybe you forgot to use IsolatedAsyncioTestCase as the base class?'
625 )
626 warnings.warn(msg, DeprecationWarning, stacklevel=3)
627
628 def _callTearDown(self):
629 self.tearDown()
630
631 def _callCleanup(self, function, /, *args, **kwargs):
632 function(*args, **kwargs)
633
634 def run(self, result=None):
635 if result is None:
636 result = self.defaultTestResult()
637 startTestRun = getattr(result, 'startTestRun', None)
638 stopTestRun = getattr(result, 'stopTestRun', None)
639 if startTestRun is not None:
640 startTestRun()
641 else:
642 stopTestRun = None
643
644 result.startTest(self)
645 try:
646 testMethod = getattr(self, self._testMethodName)
647 if (getattr(self.__class__, "__unittest_skip__", False) or
648 getattr(testMethod, "__unittest_skip__", False)):
649 # If the class or method was skipped.
650 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
651 or getattr(testMethod, '__unittest_skip_why__', ''))
652 _addSkip(result, self, skip_why)
653 return result
654
655 expecting_failure = (
656 getattr(self, "__unittest_expecting_failure__", False) or
657 getattr(testMethod, "__unittest_expecting_failure__", False)
658 )
659 outcome = _Outcome(result)
660 start_time = time.perf_counter()
661 try:
662 self._outcome = outcome
663
664 with outcome.testPartExecutor(self):
665 self._callSetUp()
666 if outcome.success:
667 outcome.expecting_failure = expecting_failure
668 with outcome.testPartExecutor(self):
669 self._callTestMethod(testMethod)
670 outcome.expecting_failure = False
671 with outcome.testPartExecutor(self):
672 self._callTearDown()
673 self.doCleanups()
674 self._addDuration(result, (time.perf_counter() - start_time))
675
676 if outcome.success:
677 if expecting_failure:
678 if outcome.expectedFailure:
679 self._addExpectedFailure(result, outcome.expectedFailure)
680 else:
681 self._addUnexpectedSuccess(result)
682 else:
683 result.addSuccess(self)
684 return result
685 finally:
686 # explicitly break reference cycle:
687 # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure
688 outcome.expectedFailure = None
689 outcome = None
690
691 # clear the outcome, no more needed
692 self._outcome = None
693
694 finally:
695 result.stopTest(self)
696 if stopTestRun is not None:
697 stopTestRun()
698
699 def doCleanups(self):
700 """Execute all cleanup functions. Normally called for you after
701 tearDown."""
702 outcome = self._outcome or _Outcome()
703 while self._cleanups:
704 function, args, kwargs = self._cleanups.pop()
705 with outcome.testPartExecutor(self):
706 self._callCleanup(function, *args, **kwargs)
707
708 # return this for backwards compatibility
709 # even though we no longer use it internally
710 return outcome.success
711
712 @classmethod
713 def doClassCleanups(cls):
714 """Execute all class cleanup functions. Normally called for you after
715 tearDownClass."""
716 cls.tearDown_exceptions = []
717 while cls._class_cleanups:
718 function, args, kwargs = cls._class_cleanups.pop()
719 try:
720 function(*args, **kwargs)
721 except Exception:
722 cls.tearDown_exceptions.append(sys.exc_info())
723
724 def __call__(self, *args, **kwds):
725 return self.run(*args, **kwds)
726
727 def debug(self):
728 """Run the test without collecting errors in a TestResult"""
729 testMethod = getattr(self, self._testMethodName)
730 if (getattr(self.__class__, "__unittest_skip__", False) or
731 getattr(testMethod, "__unittest_skip__", False)):
732 # If the class or method was skipped.
733 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
734 or getattr(testMethod, '__unittest_skip_why__', ''))
735 raise SkipTest(skip_why)
736
737 self._callSetUp()
738 self._callTestMethod(testMethod)
739 self._callTearDown()
740 while self._cleanups:
741 function, args, kwargs = self._cleanups.pop()
742 self._callCleanup(function, *args, **kwargs)
743
744 def skipTest(self, reason):
745 """Skip this test."""
746 raise SkipTest(reason)
747
748 def fail(self, msg=None):
749 """Fail immediately, with the given message."""
750 raise self.failureException(msg)
751
752 def assertFalse(self, expr, msg=None):
753 """Check that the expression is false."""
754 if expr:
755 msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
756 raise self.failureException(msg)
757
758 def assertTrue(self, expr, msg=None):
759 """Check that the expression is true."""
760 if not expr:
761 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
762 raise self.failureException(msg)
763
764 def _formatMessage(self, msg, standardMsg):
765 """Honour the longMessage attribute when generating failure messages.
766 If longMessage is False this means:
767 * Use only an explicit message if it is provided
768 * Otherwise use the standard message for the assert
769
770 If longMessage is True:
771 * Use the standard message
772 * If an explicit message is provided, plus ' : ' and the explicit message
773 """
774 if not self.longMessage:
775 return msg or standardMsg
776 if msg is None:
777 return standardMsg
778 try:
779 # don't switch to '{}' formatting in Python 2.X
780 # it changes the way unicode input is handled
781 return '%s : %s' % (standardMsg, msg)
782 except UnicodeDecodeError:
783 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
784
785 def assertRaises(self, expected_exception, *args, **kwargs):
786 """Fail unless an exception of class expected_exception is raised
787 by the callable when invoked with specified positional and
788 keyword arguments. If a different type of exception is
789 raised, it will not be caught, and the test case will be
790 deemed to have suffered an error, exactly as for an
791 unexpected exception.
792
793 If called with the callable and arguments omitted, will return a
794 context object used like this::
795
796 with self.assertRaises(SomeException):
797 do_something()
798
799 An optional keyword argument 'msg' can be provided when assertRaises
800 is used as a context object.
801
802 The context manager keeps a reference to the exception as
803 the 'exception' attribute. This allows you to inspect the
804 exception after the assertion::
805
806 with self.assertRaises(SomeException) as cm:
807 do_something()
808 the_exception = cm.exception
809 self.assertEqual(the_exception.error_code, 3)
810 """
811 context = _AssertRaisesContext(expected_exception, self)
812 try:
813 return context.handle('assertRaises', args, kwargs)
814 finally:
815 # bpo-23890: manually break a reference cycle
816 context = None
817
818 def assertWarns(self, expected_warning, *args, **kwargs):
819 """Fail unless a warning of class warnClass is triggered
820 by the callable when invoked with specified positional and
821 keyword arguments. If a different type of warning is
822 triggered, it will not be handled: depending on the other
823 warning filtering rules in effect, it might be silenced, printed
824 out, or raised as an exception.
825
826 If called with the callable and arguments omitted, will return a
827 context object used like this::
828
829 with self.assertWarns(SomeWarning):
830 do_something()
831
832 An optional keyword argument 'msg' can be provided when assertWarns
833 is used as a context object.
834
835 The context manager keeps a reference to the first matching
836 warning as the 'warning' attribute; similarly, the 'filename'
837 and 'lineno' attributes give you information about the line
838 of Python code from which the warning was triggered.
839 This allows you to inspect the warning after the assertion::
840
841 with self.assertWarns(SomeWarning) as cm:
842 do_something()
843 the_warning = cm.warning
844 self.assertEqual(the_warning.some_attribute, 147)
845 """
846 context = _AssertWarnsContext(expected_warning, self)
847 return context.handle('assertWarns', args, kwargs)
848
849 def _assertNotWarns(self, expected_warning, *args, **kwargs):
850 """The opposite of assertWarns. Private due to low demand."""
851 context = _AssertNotWarnsContext(expected_warning, self)
852 return context.handle('_assertNotWarns', args, kwargs)
853
854 def assertLogs(self, logger=None, level=None):
855 """Fail unless a log message of level *level* or higher is emitted
856 on *logger_name* or its children. If omitted, *level* defaults to
857 INFO and *logger* defaults to the root logger.
858
859 This method must be used as a context manager, and will yield
860 a recording object with two attributes: `output` and `records`.
861 At the end of the context manager, the `output` attribute will
862 be a list of the matching formatted log messages and the
863 `records` attribute will be a list of the corresponding LogRecord
864 objects.
865
866 Example::
867
868 with self.assertLogs('foo', level='INFO') as cm:
869 logging.getLogger('foo').info('first message')
870 logging.getLogger('foo.bar').error('second message')
871 self.assertEqual(cm.output, ['INFO:foo:first message',
872 'ERROR:foo.bar:second message'])
873 """
874 # Lazy import to avoid importing logging if it is not needed.
875 from ._log import _AssertLogsContext
876 return _AssertLogsContext(self, logger, level, no_logs=False)
877
878 def assertNoLogs(self, logger=None, level=None):
879 """ Fail unless no log messages of level *level* or higher are emitted
880 on *logger_name* or its children.
881
882 This method must be used as a context manager.
883 """
884 from ._log import _AssertLogsContext
885 return _AssertLogsContext(self, logger, level, no_logs=True)
886
887 def _getAssertEqualityFunc(self, first, second):
888 """Get a detailed comparison function for the types of the two args.
889
890 Returns: A callable accepting (first, second, msg=None) that will
891 raise a failure exception if first != second with a useful human
892 readable error message for those types.
893 """
894 #
895 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
896 # and vice versa. I opted for the conservative approach in case
897 # subclasses are not intended to be compared in detail to their super
898 # class instances using a type equality func. This means testing
899 # subtypes won't automagically use the detailed comparison. Callers
900 # should use their type specific assertSpamEqual method to compare
901 # subclasses if the detailed comparison is desired and appropriate.
902 # See the discussion in http://bugs.python.org/issue2578.
903 #
904 if type(first) is type(second):
905 asserter = self._type_equality_funcs.get(type(first))
906 if asserter is not None:
907 if isinstance(asserter, str):
908 asserter = getattr(self, asserter)
909 return asserter
910
911 return self._baseAssertEqual
912
913 def _baseAssertEqual(self, first, second, msg=None):
914 """The default assertEqual implementation, not type specific."""
915 if not first == second:
916 standardMsg = '%s != %s' % _common_shorten_repr(first, second)
917 msg = self._formatMessage(msg, standardMsg)
918 raise self.failureException(msg)
919
920 def assertEqual(self, first, second, msg=None):
921 """Fail if the two objects are unequal as determined by the '=='
922 operator.
923 """
924 assertion_func = self._getAssertEqualityFunc(first, second)
925 assertion_func(first, second, msg=msg)
926
927 def assertNotEqual(self, first, second, msg=None):
928 """Fail if the two objects are equal as determined by the '!='
929 operator.
930 """
931 if not first != second:
932 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
933 safe_repr(second)))
934 raise self.failureException(msg)
935
936 def assertAlmostEqual(self, first, second, places=None, msg=None,
937 delta=None):
938 """Fail if the two objects are unequal as determined by their
939 difference rounded to the given number of decimal places
940 (default 7) and comparing to zero, or by comparing that the
941 difference between the two objects is more than the given
942 delta.
943
944 Note that decimal places (from zero) are usually not the same
945 as significant digits (measured from the most significant digit).
946
947 If the two objects compare equal then they will automatically
948 compare almost equal.
949 """
950 if first == second:
951 # shortcut
952 return
953 if delta is not None and places is not None:
954 raise TypeError("specify delta or places not both")
955
956 diff = abs(first - second)
957 if delta is not None:
958 if diff <= delta:
959 return
960
961 standardMsg = '%s != %s within %s delta (%s difference)' % (
962 safe_repr(first),
963 safe_repr(second),
964 safe_repr(delta),
965 safe_repr(diff))
966 else:
967 if places is None:
968 places = 7
969
970 if round(diff, places) == 0:
971 return
972
973 standardMsg = '%s != %s within %r places (%s difference)' % (
974 safe_repr(first),
975 safe_repr(second),
976 places,
977 safe_repr(diff))
978 msg = self._formatMessage(msg, standardMsg)
979 raise self.failureException(msg)
980
981 def assertNotAlmostEqual(self, first, second, places=None, msg=None,
982 delta=None):
983 """Fail if the two objects are equal as determined by their
984 difference rounded to the given number of decimal places
985 (default 7) and comparing to zero, or by comparing that the
986 difference between the two objects is less than the given delta.
987
988 Note that decimal places (from zero) are usually not the same
989 as significant digits (measured from the most significant digit).
990
991 Objects that are equal automatically fail.
992 """
993 if delta is not None and places is not None:
994 raise TypeError("specify delta or places not both")
995 diff = abs(first - second)
996 if delta is not None:
997 if not (first == second) and diff > delta:
998 return
999 standardMsg = '%s == %s within %s delta (%s difference)' % (
1000 safe_repr(first),
1001 safe_repr(second),
1002 safe_repr(delta),
1003 safe_repr(diff))
1004 else:
1005 if places is None:
1006 places = 7
1007 if not (first == second) and round(diff, places) != 0:
1008 return
1009 standardMsg = '%s == %s within %r places' % (safe_repr(first),
1010 safe_repr(second),
1011 places)
1012
1013 msg = self._formatMessage(msg, standardMsg)
1014 raise self.failureException(msg)
1015
1016 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
1017 """An equality assertion for ordered sequences (like lists and tuples).
1018
1019 For the purposes of this function, a valid ordered sequence type is one
1020 which can be indexed, has a length, and has an equality operator.
1021
1022 Args:
1023 seq1: The first sequence to compare.
1024 seq2: The second sequence to compare.
1025 seq_type: The expected datatype of the sequences, or None if no
1026 datatype should be enforced.
1027 msg: Optional message to use on failure instead of a list of
1028 differences.
1029 """
1030 if seq_type is not None:
1031 seq_type_name = seq_type.__name__
1032 if not isinstance(seq1, seq_type):
1033 raise self.failureException('First sequence is not a %s: %s'
1034 % (seq_type_name, safe_repr(seq1)))
1035 if not isinstance(seq2, seq_type):
1036 raise self.failureException('Second sequence is not a %s: %s'
1037 % (seq_type_name, safe_repr(seq2)))
1038 else:
1039 seq_type_name = "sequence"
1040
1041 differing = None
1042 try:
1043 len1 = len(seq1)
1044 except (TypeError, NotImplementedError):
1045 differing = 'First %s has no length. Non-sequence?' % (
1046 seq_type_name)
1047
1048 if differing is None:
1049 try:
1050 len2 = len(seq2)
1051 except (TypeError, NotImplementedError):
1052 differing = 'Second %s has no length. Non-sequence?' % (
1053 seq_type_name)
1054
1055 if differing is None:
1056 if seq1 == seq2:
1057 return
1058
1059 differing = '%ss differ: %s != %s\n' % (
1060 (seq_type_name.capitalize(),) +
1061 _common_shorten_repr(seq1, seq2))
1062
1063 for i in range(min(len1, len2)):
1064 try:
1065 item1 = seq1[i]
1066 except (TypeError, IndexError, NotImplementedError):
1067 differing += ('\nUnable to index element %d of first %s\n' %
1068 (i, seq_type_name))
1069 break
1070
1071 try:
1072 item2 = seq2[i]
1073 except (TypeError, IndexError, NotImplementedError):
1074 differing += ('\nUnable to index element %d of second %s\n' %
1075 (i, seq_type_name))
1076 break
1077
1078 if item1 != item2:
1079 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
1080 ((i,) + _common_shorten_repr(item1, item2)))
1081 break
1082 else:
1083 if (len1 == len2 and seq_type is None and
1084 type(seq1) != type(seq2)):
1085 # The sequences are the same, but have differing types.
1086 return
1087
1088 if len1 > len2:
1089 differing += ('\nFirst %s contains %d additional '
1090 'elements.\n' % (seq_type_name, len1 - len2))
1091 try:
1092 differing += ('First extra element %d:\n%s\n' %
1093 (len2, safe_repr(seq1[len2])))
1094 except (TypeError, IndexError, NotImplementedError):
1095 differing += ('Unable to index element %d '
1096 'of first %s\n' % (len2, seq_type_name))
1097 elif len1 < len2:
1098 differing += ('\nSecond %s contains %d additional '
1099 'elements.\n' % (seq_type_name, len2 - len1))
1100 try:
1101 differing += ('First extra element %d:\n%s\n' %
1102 (len1, safe_repr(seq2[len1])))
1103 except (TypeError, IndexError, NotImplementedError):
1104 differing += ('Unable to index element %d '
1105 'of second %s\n' % (len1, seq_type_name))
1106 standardMsg = differing
1107 diffMsg = '\n' + '\n'.join(
1108 difflib.ndiff(pprint.pformat(seq1).splitlines(),
1109 pprint.pformat(seq2).splitlines()))
1110
1111 standardMsg = self._truncateMessage(standardMsg, diffMsg)
1112 msg = self._formatMessage(msg, standardMsg)
1113 self.fail(msg)
1114
1115 def _truncateMessage(self, message, diff):
1116 max_diff = self.maxDiff
1117 if max_diff is None or len(diff) <= max_diff:
1118 return message + diff
1119 return message + (DIFF_OMITTED % len(diff))
1120
1121 def assertListEqual(self, list1, list2, msg=None):
1122 """A list-specific equality assertion.
1123
1124 Args:
1125 list1: The first list to compare.
1126 list2: The second list to compare.
1127 msg: Optional message to use on failure instead of a list of
1128 differences.
1129
1130 """
1131 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
1132
1133 def assertTupleEqual(self, tuple1, tuple2, msg=None):
1134 """A tuple-specific equality assertion.
1135
1136 Args:
1137 tuple1: The first tuple to compare.
1138 tuple2: The second tuple to compare.
1139 msg: Optional message to use on failure instead of a list of
1140 differences.
1141 """
1142 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
1143
1144 def assertSetEqual(self, set1, set2, msg=None):
1145 """A set-specific equality assertion.
1146
1147 Args:
1148 set1: The first set to compare.
1149 set2: The second set to compare.
1150 msg: Optional message to use on failure instead of a list of
1151 differences.
1152
1153 assertSetEqual uses ducktyping to support different types of sets, and
1154 is optimized for sets specifically (parameters must support a
1155 difference method).
1156 """
1157 try:
1158 difference1 = set1.difference(set2)
1159 except TypeError as e:
1160 self.fail('invalid type when attempting set difference: %s' % e)
1161 except AttributeError as e:
1162 self.fail('first argument does not support set difference: %s' % e)
1163
1164 try:
1165 difference2 = set2.difference(set1)
1166 except TypeError as e:
1167 self.fail('invalid type when attempting set difference: %s' % e)
1168 except AttributeError as e:
1169 self.fail('second argument does not support set difference: %s' % e)
1170
1171 if not (difference1 or difference2):
1172 return
1173
1174 lines = []
1175 if difference1:
1176 lines.append('Items in the first set but not the second:')
1177 for item in difference1:
1178 lines.append(repr(item))
1179 if difference2:
1180 lines.append('Items in the second set but not the first:')
1181 for item in difference2:
1182 lines.append(repr(item))
1183
1184 standardMsg = '\n'.join(lines)
1185 self.fail(self._formatMessage(msg, standardMsg))
1186
1187 def assertIn(self, member, container, msg=None):
1188 """Just like self.assertTrue(a in b), but with a nicer default message."""
1189 if member not in container:
1190 standardMsg = '%s not found in %s' % (safe_repr(member),
1191 safe_repr(container))
1192 self.fail(self._formatMessage(msg, standardMsg))
1193
1194 def assertNotIn(self, member, container, msg=None):
1195 """Just like self.assertTrue(a not in b), but with a nicer default message."""
1196 if member in container:
1197 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
1198 safe_repr(container))
1199 self.fail(self._formatMessage(msg, standardMsg))
1200
1201 def assertIs(self, expr1, expr2, msg=None):
1202 """Just like self.assertTrue(a is b), but with a nicer default message."""
1203 if expr1 is not expr2:
1204 standardMsg = '%s is not %s' % (safe_repr(expr1),
1205 safe_repr(expr2))
1206 self.fail(self._formatMessage(msg, standardMsg))
1207
1208 def assertIsNot(self, expr1, expr2, msg=None):
1209 """Just like self.assertTrue(a is not b), but with a nicer default message."""
1210 if expr1 is expr2:
1211 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
1212 self.fail(self._formatMessage(msg, standardMsg))
1213
1214 def assertDictEqual(self, d1, d2, msg=None):
1215 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
1216 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
1217
1218 if d1 != d2:
1219 standardMsg = '%s != %s' % _common_shorten_repr(d1, d2)
1220 diff = ('\n' + '\n'.join(difflib.ndiff(
1221 pprint.pformat(d1).splitlines(),
1222 pprint.pformat(d2).splitlines())))
1223 standardMsg = self._truncateMessage(standardMsg, diff)
1224 self.fail(self._formatMessage(msg, standardMsg))
1225
1226 def assertCountEqual(self, first, second, msg=None):
1227 """Asserts that two iterables have the same elements, the same number of
1228 times, without regard to order.
1229
1230 self.assertEqual(Counter(list(first)),
1231 Counter(list(second)))
1232
1233 Example:
1234 - [0, 1, 1] and [1, 0, 1] compare equal.
1235 - [0, 0, 1] and [0, 1] compare unequal.
1236
1237 """
1238 first_seq, second_seq = list(first), list(second)
1239 try:
1240 first = collections.Counter(first_seq)
1241 second = collections.Counter(second_seq)
1242 except TypeError:
1243 # Handle case with unhashable elements
1244 differences = _count_diff_all_purpose(first_seq, second_seq)
1245 else:
1246 if first == second:
1247 return
1248 differences = _count_diff_hashable(first_seq, second_seq)
1249
1250 if differences:
1251 standardMsg = 'Element counts were not equal:\n'
1252 lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
1253 diffMsg = '\n'.join(lines)
1254 standardMsg = self._truncateMessage(standardMsg, diffMsg)
1255 msg = self._formatMessage(msg, standardMsg)
1256 self.fail(msg)
1257
1258 def assertMultiLineEqual(self, first, second, msg=None):
1259 """Assert that two multi-line strings are equal."""
1260 self.assertIsInstance(first, str, "First argument is not a string")
1261 self.assertIsInstance(second, str, "Second argument is not a string")
1262
1263 if first != second:
1264 # Don't use difflib if the strings are too long
1265 if (len(first) > self._diffThreshold or
1266 len(second) > self._diffThreshold):
1267 self._baseAssertEqual(first, second, msg)
1268
1269 # Append \n to both strings if either is missing the \n.
1270 # This allows the final ndiff to show the \n difference. The
1271 # exception here is if the string is empty, in which case no
1272 # \n should be added
1273 first_presplit = first
1274 second_presplit = second
1275 if first and second:
1276 if first[-1] != '\n' or second[-1] != '\n':
1277 first_presplit += '\n'
1278 second_presplit += '\n'
1279 elif second and second[-1] != '\n':
1280 second_presplit += '\n'
1281 elif first and first[-1] != '\n':
1282 first_presplit += '\n'
1283
1284 firstlines = first_presplit.splitlines(keepends=True)
1285 secondlines = second_presplit.splitlines(keepends=True)
1286
1287 # Generate the message and diff, then raise the exception
1288 standardMsg = '%s != %s' % _common_shorten_repr(first, second)
1289 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
1290 standardMsg = self._truncateMessage(standardMsg, diff)
1291 self.fail(self._formatMessage(msg, standardMsg))
1292
1293 def assertLess(self, a, b, msg=None):
1294 """Just like self.assertTrue(a < b), but with a nicer default message."""
1295 if not a < b:
1296 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
1297 self.fail(self._formatMessage(msg, standardMsg))
1298
1299 def assertLessEqual(self, a, b, msg=None):
1300 """Just like self.assertTrue(a <= b), but with a nicer default message."""
1301 if not a <= b:
1302 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
1303 self.fail(self._formatMessage(msg, standardMsg))
1304
1305 def assertGreater(self, a, b, msg=None):
1306 """Just like self.assertTrue(a > b), but with a nicer default message."""
1307 if not a > b:
1308 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
1309 self.fail(self._formatMessage(msg, standardMsg))
1310
1311 def assertGreaterEqual(self, a, b, msg=None):
1312 """Just like self.assertTrue(a >= b), but with a nicer default message."""
1313 if not a >= b:
1314 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
1315 self.fail(self._formatMessage(msg, standardMsg))
1316
1317 def assertIsNone(self, obj, msg=None):
1318 """Same as self.assertTrue(obj is None), with a nicer default message."""
1319 if obj is not None:
1320 standardMsg = '%s is not None' % (safe_repr(obj),)
1321 self.fail(self._formatMessage(msg, standardMsg))
1322
1323 def assertIsNotNone(self, obj, msg=None):
1324 """Included for symmetry with assertIsNone."""
1325 if obj is None:
1326 standardMsg = 'unexpectedly None'
1327 self.fail(self._formatMessage(msg, standardMsg))
1328
1329 def assertIsInstance(self, obj, cls, msg=None):
1330 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
1331 default message."""
1332 if not isinstance(obj, cls):
1333 if isinstance(cls, tuple):
1334 standardMsg = f'{safe_repr(obj)} is not an instance of any of {cls!r}'
1335 else:
1336 standardMsg = f'{safe_repr(obj)} is not an instance of {cls!r}'
1337 self.fail(self._formatMessage(msg, standardMsg))
1338
1339 def assertNotIsInstance(self, obj, cls, msg=None):
1340 """Included for symmetry with assertIsInstance."""
1341 if isinstance(obj, cls):
1342 if isinstance(cls, tuple):
1343 for x in cls:
1344 if isinstance(obj, x):
1345 cls = x
1346 break
1347 standardMsg = f'{safe_repr(obj)} is an instance of {cls!r}'
1348 self.fail(self._formatMessage(msg, standardMsg))
1349
1350 def assertIsSubclass(self, cls, superclass, msg=None):
1351 try:
1352 if issubclass(cls, superclass):
1353 return
1354 except TypeError:
1355 if not isinstance(cls, type):
1356 self.fail(self._formatMessage(msg, f'{cls!r} is not a class'))
1357 raise
1358 if isinstance(superclass, tuple):
1359 standardMsg = f'{cls!r} is not a subclass of any of {superclass!r}'
1360 else:
1361 standardMsg = f'{cls!r} is not a subclass of {superclass!r}'
1362 self.fail(self._formatMessage(msg, standardMsg))
1363
1364 def assertNotIsSubclass(self, cls, superclass, msg=None):
1365 try:
1366 if not issubclass(cls, superclass):
1367 return
1368 except TypeError:
1369 if not isinstance(cls, type):
1370 self.fail(self._formatMessage(msg, f'{cls!r} is not a class'))
1371 raise
1372 if isinstance(superclass, tuple):
1373 for x in superclass:
1374 if issubclass(cls, x):
1375 superclass = x
1376 break
1377 standardMsg = f'{cls!r} is a subclass of {superclass!r}'
1378 self.fail(self._formatMessage(msg, standardMsg))
1379
1380 def assertHasAttr(self, obj, name, msg=None):
1381 if not hasattr(obj, name):
1382 if isinstance(obj, types.ModuleType):
1383 standardMsg = f'module {obj.__name__!r} has no attribute {name!r}'
1384 elif isinstance(obj, type):
1385 standardMsg = f'type object {obj.__name__!r} has no attribute {name!r}'
1386 else:
1387 standardMsg = f'{type(obj).__name__!r} object has no attribute {name!r}'
1388 self.fail(self._formatMessage(msg, standardMsg))
1389
1390 def assertNotHasAttr(self, obj, name, msg=None):
1391 if hasattr(obj, name):
1392 if isinstance(obj, types.ModuleType):
1393 standardMsg = f'module {obj.__name__!r} has unexpected attribute {name!r}'
1394 elif isinstance(obj, type):
1395 standardMsg = f'type object {obj.__name__!r} has unexpected attribute {name!r}'
1396 else:
1397 standardMsg = f'{type(obj).__name__!r} object has unexpected attribute {name!r}'
1398 self.fail(self._formatMessage(msg, standardMsg))
1399
1400 def assertRaisesRegex(self, expected_exception, expected_regex,
1401 *args, **kwargs):
1402 """Asserts that the message in a raised exception matches a regex.
1403
1404 Args:
1405 expected_exception: Exception class expected to be raised.
1406 expected_regex: Regex (re.Pattern object or string) expected
1407 to be found in error message.
1408 args: Function to be called and extra positional args.
1409 kwargs: Extra kwargs.
1410 msg: Optional message used in case of failure. Can only be used
1411 when assertRaisesRegex is used as a context manager.
1412 """
1413 context = _AssertRaisesContext(expected_exception, self, expected_regex)
1414 return context.handle('assertRaisesRegex', args, kwargs)
1415
1416 def assertWarnsRegex(self, expected_warning, expected_regex,
1417 *args, **kwargs):
1418 """Asserts that the message in a triggered warning matches a regexp.
1419 Basic functioning is similar to assertWarns() with the addition
1420 that only warnings whose messages also match the regular expression
1421 are considered successful matches.
1422
1423 Args:
1424 expected_warning: Warning class expected to be triggered.
1425 expected_regex: Regex (re.Pattern object or string) expected
1426 to be found in error message.
1427 args: Function to be called and extra positional args.
1428 kwargs: Extra kwargs.
1429 msg: Optional message used in case of failure. Can only be used
1430 when assertWarnsRegex is used as a context manager.
1431 """
1432 context = _AssertWarnsContext(expected_warning, self, expected_regex)
1433 return context.handle('assertWarnsRegex', args, kwargs)
1434
1435 def assertRegex(self, text, expected_regex, msg=None):
1436 """Fail the test unless the text matches the regular expression."""
1437 if isinstance(expected_regex, (str, bytes)):
1438 assert expected_regex, "expected_regex must not be empty."
1439 expected_regex = re.compile(expected_regex)
1440 if not expected_regex.search(text):
1441 standardMsg = "Regex didn't match: %r not found in %r" % (
1442 expected_regex.pattern, text)
1443 # _formatMessage ensures the longMessage option is respected
1444 msg = self._formatMessage(msg, standardMsg)
1445 raise self.failureException(msg)
1446
1447 def assertNotRegex(self, text, unexpected_regex, msg=None):
1448 """Fail the test if the text matches the regular expression."""
1449 if isinstance(unexpected_regex, (str, bytes)):
1450 unexpected_regex = re.compile(unexpected_regex)
1451 match = unexpected_regex.search(text)
1452 if match:
1453 standardMsg = 'Regex matched: %r matches %r in %r' % (
1454 text[match.start() : match.end()],
1455 unexpected_regex.pattern,
1456 text)
1457 # _formatMessage ensures the longMessage option is respected
1458 msg = self._formatMessage(msg, standardMsg)
1459 raise self.failureException(msg)
1460
1461 def _tail_type_check(self, s, tails, msg):
1462 if not isinstance(tails, tuple):
1463 tails = (tails,)
1464 for tail in tails:
1465 if isinstance(tail, str):
1466 if not isinstance(s, str):
1467 self.fail(self._formatMessage(msg,
1468 f'Expected str, not {type(s).__name__}'))
1469 elif isinstance(tail, (bytes, bytearray)):
1470 if not isinstance(s, (bytes, bytearray)):
1471 self.fail(self._formatMessage(msg,
1472 f'Expected bytes, not {type(s).__name__}'))
1473
1474 def assertStartsWith(self, s, prefix, msg=None):
1475 try:
1476 if s.startswith(prefix):
1477 return
1478 except (AttributeError, TypeError):
1479 self._tail_type_check(s, prefix, msg)
1480 raise
1481 a = safe_repr(s, short=True)
1482 b = safe_repr(prefix)
1483 if isinstance(prefix, tuple):
1484 standardMsg = f"{a} doesn't start with any of {b}"
1485 else:
1486 standardMsg = f"{a} doesn't start with {b}"
1487 self.fail(self._formatMessage(msg, standardMsg))
1488
1489 def assertNotStartsWith(self, s, prefix, msg=None):
1490 try:
1491 if not s.startswith(prefix):
1492 return
1493 except (AttributeError, TypeError):
1494 self._tail_type_check(s, prefix, msg)
1495 raise
1496 if isinstance(prefix, tuple):
1497 for x in prefix:
1498 if s.startswith(x):
1499 prefix = x
1500 break
1501 a = safe_repr(s, short=True)
1502 b = safe_repr(prefix)
1503 self.fail(self._formatMessage(msg, f"{a} starts with {b}"))
1504
1505 def assertEndsWith(self, s, suffix, msg=None):
1506 try:
1507 if s.endswith(suffix):
1508 return
1509 except (AttributeError, TypeError):
1510 self._tail_type_check(s, suffix, msg)
1511 raise
1512 a = safe_repr(s, short=True)
1513 b = safe_repr(suffix)
1514 if isinstance(suffix, tuple):
1515 standardMsg = f"{a} doesn't end with any of {b}"
1516 else:
1517 standardMsg = f"{a} doesn't end with {b}"
1518 self.fail(self._formatMessage(msg, standardMsg))
1519
1520 def assertNotEndsWith(self, s, suffix, msg=None):
1521 try:
1522 if not s.endswith(suffix):
1523 return
1524 except (AttributeError, TypeError):
1525 self._tail_type_check(s, suffix, msg)
1526 raise
1527 if isinstance(suffix, tuple):
1528 for x in suffix:
1529 if s.endswith(x):
1530 suffix = x
1531 break
1532 a = safe_repr(s, short=True)
1533 b = safe_repr(suffix)
1534 self.fail(self._formatMessage(msg, f"{a} ends with {b}"))
1535
1536
1537 class FunctionTestCase(TestCase):
1538 """A test case that wraps a test function.
1539
1540 This is useful for slipping pre-existing test functions into the
1541 unittest framework. Optionally, set-up and tidy-up functions can be
1542 supplied. As with TestCase, the tidy-up ('tearDown') function will
1543 always be called if the set-up ('setUp') function ran successfully.
1544 """
1545
1546 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1547 super(FunctionTestCase, self).__init__()
1548 self._setUpFunc = setUp
1549 self._tearDownFunc = tearDown
1550 self._testFunc = testFunc
1551 self._description = description
1552
1553 def setUp(self):
1554 if self._setUpFunc is not None:
1555 self._setUpFunc()
1556
1557 def tearDown(self):
1558 if self._tearDownFunc is not None:
1559 self._tearDownFunc()
1560
1561 def runTest(self):
1562 self._testFunc()
1563
1564 def id(self):
1565 return self._testFunc.__name__
1566
1567 def __eq__(self, other):
1568 if not isinstance(other, self.__class__):
1569 return NotImplemented
1570
1571 return self._setUpFunc == other._setUpFunc and \
1572 self._tearDownFunc == other._tearDownFunc and \
1573 self._testFunc == other._testFunc and \
1574 self._description == other._description
1575
1576 def __hash__(self):
1577 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1578 self._testFunc, self._description))
1579
1580 def __str__(self):
1581 return "%s (%s)" % (strclass(self.__class__),
1582 self._testFunc.__name__)
1583
1584 def __repr__(self):
1585 return "<%s tec=%s>" % (strclass(self.__class__),
1586 self._testFunc)
1587
1588 def shortDescription(self):
1589 if self._description is not None:
1590 return self._description
1591 doc = self._testFunc.__doc__
1592 return doc and doc.split("\n")[0].strip() or None
1593
1594
1595 class _SubTest(TestCase):
1596
1597 def __init__(self, test_case, message, params):
1598 super().__init__()
1599 self._message = message
1600 self.test_case = test_case
1601 self.params = params
1602 self.failureException = test_case.failureException
1603
1604 def runTest(self):
1605 raise NotImplementedError("subtests cannot be run directly")
1606
1607 def _subDescription(self):
1608 parts = []
1609 if self._message is not _subtest_msg_sentinel:
1610 parts.append("[{}]".format(self._message))
1611 if self.params:
1612 params_desc = ', '.join(
1613 "{}={!r}".format(k, v)
1614 for (k, v) in self.params.items())
1615 parts.append("({})".format(params_desc))
1616 return " ".join(parts) or '(<subtest>)'
1617
1618 def id(self):
1619 return "{} {}".format(self.test_case.id(), self._subDescription())
1620
1621 def shortDescription(self):
1622 """Returns a one-line description of the subtest, or None if no
1623 description has been provided.
1624 """
1625 return self.test_case.shortDescription()
1626
1627 def __str__(self):
1628 return "{} {}".format(self.test_case, self._subDescription())