ยปCore Development>Code coverage>Lib/unittest/case.py

Python code coverage for Lib/unittest/case.py

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