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

Python code coverage for Lib/unittest/test/test_case.py

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