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

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

#countcontent
1n/aimport datetime
2n/aimport warnings
3n/aimport weakref
4n/aimport unittest
5n/afrom itertools import product
6n/a
7n/a
8n/aclass Test_Assertions(unittest.TestCase):
9n/a def test_AlmostEqual(self):
10n/a self.assertAlmostEqual(1.00000001, 1.0)
11n/a self.assertNotAlmostEqual(1.0000001, 1.0)
12n/a self.assertRaises(self.failureException,
13n/a self.assertAlmostEqual, 1.0000001, 1.0)
14n/a self.assertRaises(self.failureException,
15n/a self.assertNotAlmostEqual, 1.00000001, 1.0)
16n/a
17n/a self.assertAlmostEqual(1.1, 1.0, places=0)
18n/a self.assertRaises(self.failureException,
19n/a self.assertAlmostEqual, 1.1, 1.0, places=1)
20n/a
21n/a self.assertAlmostEqual(0, .1+.1j, places=0)
22n/a self.assertNotAlmostEqual(0, .1+.1j, places=1)
23n/a self.assertRaises(self.failureException,
24n/a self.assertAlmostEqual, 0, .1+.1j, places=1)
25n/a self.assertRaises(self.failureException,
26n/a self.assertNotAlmostEqual, 0, .1+.1j, places=0)
27n/a
28n/a self.assertAlmostEqual(float('inf'), float('inf'))
29n/a self.assertRaises(self.failureException, self.assertNotAlmostEqual,
30n/a float('inf'), float('inf'))
31n/a
32n/a def test_AmostEqualWithDelta(self):
33n/a self.assertAlmostEqual(1.1, 1.0, delta=0.5)
34n/a self.assertAlmostEqual(1.0, 1.1, delta=0.5)
35n/a self.assertNotAlmostEqual(1.1, 1.0, delta=0.05)
36n/a self.assertNotAlmostEqual(1.0, 1.1, delta=0.05)
37n/a
38n/a self.assertAlmostEqual(1.0, 1.0, delta=0.5)
39n/a self.assertRaises(self.failureException, self.assertNotAlmostEqual,
40n/a 1.0, 1.0, delta=0.5)
41n/a
42n/a self.assertRaises(self.failureException, self.assertAlmostEqual,
43n/a 1.1, 1.0, delta=0.05)
44n/a self.assertRaises(self.failureException, self.assertNotAlmostEqual,
45n/a 1.1, 1.0, delta=0.5)
46n/a
47n/a self.assertRaises(TypeError, self.assertAlmostEqual,
48n/a 1.1, 1.0, places=2, delta=2)
49n/a self.assertRaises(TypeError, self.assertNotAlmostEqual,
50n/a 1.1, 1.0, places=2, delta=2)
51n/a
52n/a first = datetime.datetime.now()
53n/a second = first + datetime.timedelta(seconds=10)
54n/a self.assertAlmostEqual(first, second,
55n/a delta=datetime.timedelta(seconds=20))
56n/a self.assertNotAlmostEqual(first, second,
57n/a delta=datetime.timedelta(seconds=5))
58n/a
59n/a def test_assertRaises(self):
60n/a def _raise(e):
61n/a raise e
62n/a self.assertRaises(KeyError, _raise, KeyError)
63n/a self.assertRaises(KeyError, _raise, KeyError("key"))
64n/a try:
65n/a self.assertRaises(KeyError, lambda: None)
66n/a except self.failureException as e:
67n/a self.assertIn("KeyError not raised", str(e))
68n/a else:
69n/a self.fail("assertRaises() didn't fail")
70n/a try:
71n/a self.assertRaises(KeyError, _raise, ValueError)
72n/a except ValueError:
73n/a pass
74n/a else:
75n/a self.fail("assertRaises() didn't let exception pass through")
76n/a with self.assertRaises(KeyError) as cm:
77n/a try:
78n/a raise KeyError
79n/a except Exception as e:
80n/a exc = e
81n/a raise
82n/a self.assertIs(cm.exception, exc)
83n/a
84n/a with self.assertRaises(KeyError):
85n/a raise KeyError("key")
86n/a try:
87n/a with self.assertRaises(KeyError):
88n/a pass
89n/a except self.failureException as e:
90n/a self.assertIn("KeyError not raised", str(e))
91n/a else:
92n/a self.fail("assertRaises() didn't fail")
93n/a try:
94n/a with self.assertRaises(KeyError):
95n/a raise ValueError
96n/a except ValueError:
97n/a pass
98n/a else:
99n/a self.fail("assertRaises() didn't let exception pass through")
100n/a
101n/a def test_assertRaises_frames_survival(self):
102n/a # Issue #9815: assertRaises should avoid keeping local variables
103n/a # in a traceback alive.
104n/a class A:
105n/a pass
106n/a wr = None
107n/a
108n/a class Foo(unittest.TestCase):
109n/a
110n/a def foo(self):
111n/a nonlocal wr
112n/a a = A()
113n/a wr = weakref.ref(a)
114n/a try:
115n/a raise IOError
116n/a except IOError:
117n/a raise ValueError
118n/a
119n/a def test_functional(self):
120n/a self.assertRaises(ValueError, self.foo)
121n/a
122n/a def test_with(self):
123n/a with self.assertRaises(ValueError):
124n/a self.foo()
125n/a
126n/a Foo("test_functional").run()
127n/a self.assertIsNone(wr())
128n/a Foo("test_with").run()
129n/a self.assertIsNone(wr())
130n/a
131n/a def testAssertNotRegex(self):
132n/a self.assertNotRegex('Ala ma kota', r'r+')
133n/a try:
134n/a self.assertNotRegex('Ala ma kota', r'k.t', 'Message')
135n/a except self.failureException as e:
136n/a self.assertIn('Message', e.args[0])
137n/a else:
138n/a self.fail('assertNotRegex should have failed.')
139n/a
140n/a
141n/aclass TestLongMessage(unittest.TestCase):
142n/a """Test that the individual asserts honour longMessage.
143n/a This actually tests all the message behaviour for
144n/a asserts that use longMessage."""
145n/a
146n/a def setUp(self):
147n/a class TestableTestFalse(unittest.TestCase):
148n/a longMessage = False
149n/a failureException = self.failureException
150n/a
151n/a def testTest(self):
152n/a pass
153n/a
154n/a class TestableTestTrue(unittest.TestCase):
155n/a longMessage = True
156n/a failureException = self.failureException
157n/a
158n/a def testTest(self):
159n/a pass
160n/a
161n/a self.testableTrue = TestableTestTrue('testTest')
162n/a self.testableFalse = TestableTestFalse('testTest')
163n/a
164n/a def testDefault(self):
165n/a self.assertTrue(unittest.TestCase.longMessage)
166n/a
167n/a def test_formatMsg(self):
168n/a self.assertEqual(self.testableFalse._formatMessage(None, "foo"), "foo")
169n/a self.assertEqual(self.testableFalse._formatMessage("foo", "bar"), "foo")
170n/a
171n/a self.assertEqual(self.testableTrue._formatMessage(None, "foo"), "foo")
172n/a self.assertEqual(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
173n/a
174n/a # This blows up if _formatMessage uses string concatenation
175n/a self.testableTrue._formatMessage(object(), 'foo')
176n/a
177n/a def test_formatMessage_unicode_error(self):
178n/a one = ''.join(chr(i) for i in range(255))
179n/a # this used to cause a UnicodeDecodeError constructing msg
180n/a self.testableTrue._formatMessage(one, '\uFFFD')
181n/a
182n/a def assertMessages(self, methodName, args, errors):
183n/a """
184n/a Check that methodName(*args) raises the correct error messages.
185n/a errors should be a list of 4 regex that match the error when:
186n/a 1) longMessage = False and no msg passed;
187n/a 2) longMessage = False and msg passed;
188n/a 3) longMessage = True and no msg passed;
189n/a 4) longMessage = True and msg passed;
190n/a """
191n/a def getMethod(i):
192n/a useTestableFalse = i < 2
193n/a if useTestableFalse:
194n/a test = self.testableFalse
195n/a else:
196n/a test = self.testableTrue
197n/a return getattr(test, methodName)
198n/a
199n/a for i, expected_regex in enumerate(errors):
200n/a testMethod = getMethod(i)
201n/a kwargs = {}
202n/a withMsg = i % 2
203n/a if withMsg:
204n/a kwargs = {"msg": "oops"}
205n/a
206n/a with self.assertRaisesRegex(self.failureException,
207n/a expected_regex=expected_regex):
208n/a testMethod(*args, **kwargs)
209n/a
210n/a def testAssertTrue(self):
211n/a self.assertMessages('assertTrue', (False,),
212n/a ["^False is not true$", "^oops$", "^False is not true$",
213n/a "^False is not true : oops$"])
214n/a
215n/a def testAssertFalse(self):
216n/a self.assertMessages('assertFalse', (True,),
217n/a ["^True is not false$", "^oops$", "^True is not false$",
218n/a "^True is not false : oops$"])
219n/a
220n/a def testNotEqual(self):
221n/a self.assertMessages('assertNotEqual', (1, 1),
222n/a ["^1 == 1$", "^oops$", "^1 == 1$",
223n/a "^1 == 1 : oops$"])
224n/a
225n/a def testAlmostEqual(self):
226n/a self.assertMessages('assertAlmostEqual', (1, 2),
227n/a ["^1 != 2 within 7 places$", "^oops$",
228n/a "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
229n/a
230n/a def testNotAlmostEqual(self):
231n/a self.assertMessages('assertNotAlmostEqual', (1, 1),
232n/a ["^1 == 1 within 7 places$", "^oops$",
233n/a "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
234n/a
235n/a def test_baseAssertEqual(self):
236n/a self.assertMessages('_baseAssertEqual', (1, 2),
237n/a ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
238n/a
239n/a def testAssertSequenceEqual(self):
240n/a # Error messages are multiline so not testing on full message
241n/a # assertTupleEqual and assertListEqual delegate to this method
242n/a self.assertMessages('assertSequenceEqual', ([], [None]),
243n/a [r"\+ \[None\]$", "^oops$", r"\+ \[None\]$",
244n/a r"\+ \[None\] : oops$"])
245n/a
246n/a def testAssertSetEqual(self):
247n/a self.assertMessages('assertSetEqual', (set(), set([None])),
248n/a ["None$", "^oops$", "None$",
249n/a "None : oops$"])
250n/a
251n/a def testAssertIn(self):
252n/a self.assertMessages('assertIn', (None, []),
253n/a [r'^None not found in \[\]$', "^oops$",
254n/a r'^None not found in \[\]$',
255n/a r'^None not found in \[\] : oops$'])
256n/a
257n/a def testAssertNotIn(self):
258n/a self.assertMessages('assertNotIn', (None, [None]),
259n/a [r'^None unexpectedly found in \[None\]$', "^oops$",
260n/a r'^None unexpectedly found in \[None\]$',
261n/a r'^None unexpectedly found in \[None\] : oops$'])
262n/a
263n/a def testAssertDictEqual(self):
264n/a self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
265n/a [r"\+ \{'key': 'value'\}$", "^oops$",
266n/a r"\+ \{'key': 'value'\}$",
267n/a r"\+ \{'key': 'value'\} : oops$"])
268n/a
269n/a def testAssertDictContainsSubset(self):
270n/a with warnings.catch_warnings():
271n/a warnings.simplefilter("ignore", DeprecationWarning)
272n/a
273n/a self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
274n/a ["^Missing: 'key'$", "^oops$",
275n/a "^Missing: 'key'$",
276n/a "^Missing: 'key' : oops$"])
277n/a
278n/a def testAssertMultiLineEqual(self):
279n/a self.assertMessages('assertMultiLineEqual', ("", "foo"),
280n/a [r"\+ foo$", "^oops$",
281n/a r"\+ foo$",
282n/a r"\+ foo : oops$"])
283n/a
284n/a def testAssertLess(self):
285n/a self.assertMessages('assertLess', (2, 1),
286n/a ["^2 not less than 1$", "^oops$",
287n/a "^2 not less than 1$", "^2 not less than 1 : oops$"])
288n/a
289n/a def testAssertLessEqual(self):
290n/a self.assertMessages('assertLessEqual', (2, 1),
291n/a ["^2 not less than or equal to 1$", "^oops$",
292n/a "^2 not less than or equal to 1$",
293n/a "^2 not less than or equal to 1 : oops$"])
294n/a
295n/a def testAssertGreater(self):
296n/a self.assertMessages('assertGreater', (1, 2),
297n/a ["^1 not greater than 2$", "^oops$",
298n/a "^1 not greater than 2$",
299n/a "^1 not greater than 2 : oops$"])
300n/a
301n/a def testAssertGreaterEqual(self):
302n/a self.assertMessages('assertGreaterEqual', (1, 2),
303n/a ["^1 not greater than or equal to 2$", "^oops$",
304n/a "^1 not greater than or equal to 2$",
305n/a "^1 not greater than or equal to 2 : oops$"])
306n/a
307n/a def testAssertIsNone(self):
308n/a self.assertMessages('assertIsNone', ('not None',),
309n/a ["^'not None' is not None$", "^oops$",
310n/a "^'not None' is not None$",
311n/a "^'not None' is not None : oops$"])
312n/a
313n/a def testAssertIsNotNone(self):
314n/a self.assertMessages('assertIsNotNone', (None,),
315n/a ["^unexpectedly None$", "^oops$",
316n/a "^unexpectedly None$",
317n/a "^unexpectedly None : oops$"])
318n/a
319n/a def testAssertIs(self):
320n/a self.assertMessages('assertIs', (None, 'foo'),
321n/a ["^None is not 'foo'$", "^oops$",
322n/a "^None is not 'foo'$",
323n/a "^None is not 'foo' : oops$"])
324n/a
325n/a def testAssertIsNot(self):
326n/a self.assertMessages('assertIsNot', (None, None),
327n/a ["^unexpectedly identical: None$", "^oops$",
328n/a "^unexpectedly identical: None$",
329n/a "^unexpectedly identical: None : oops$"])
330n/a
331n/a def testAssertRegex(self):
332n/a self.assertMessages('assertRegex', ('foo', 'bar'),
333n/a ["^Regex didn't match:",
334n/a "^oops$",
335n/a "^Regex didn't match:",
336n/a "^Regex didn't match: (.*) : oops$"])
337n/a
338n/a def testAssertNotRegex(self):
339n/a self.assertMessages('assertNotRegex', ('foo', 'foo'),
340n/a ["^Regex matched:",
341n/a "^oops$",
342n/a "^Regex matched:",
343n/a "^Regex matched: (.*) : oops$"])
344n/a
345n/a
346n/a def assertMessagesCM(self, methodName, args, func, errors):
347n/a """
348n/a Check that the correct error messages are raised while executing:
349n/a with method(*args):
350n/a func()
351n/a *errors* should be a list of 4 regex that match the error when:
352n/a 1) longMessage = False and no msg passed;
353n/a 2) longMessage = False and msg passed;
354n/a 3) longMessage = True and no msg passed;
355n/a 4) longMessage = True and msg passed;
356n/a """
357n/a p = product((self.testableFalse, self.testableTrue),
358n/a ({}, {"msg": "oops"}))
359n/a for (cls, kwargs), err in zip(p, errors):
360n/a method = getattr(cls, methodName)
361n/a with self.assertRaisesRegex(cls.failureException, err):
362n/a with method(*args, **kwargs) as cm:
363n/a func()
364n/a
365n/a def testAssertRaises(self):
366n/a self.assertMessagesCM('assertRaises', (TypeError,), lambda: None,
367n/a ['^TypeError not raised$', '^oops$',
368n/a '^TypeError not raised$',
369n/a '^TypeError not raised : oops$'])
370n/a
371n/a def testAssertRaisesRegex(self):
372n/a # test error not raised
373n/a self.assertMessagesCM('assertRaisesRegex', (TypeError, 'unused regex'),
374n/a lambda: None,
375n/a ['^TypeError not raised$', '^oops$',
376n/a '^TypeError not raised$',
377n/a '^TypeError not raised : oops$'])
378n/a # test error raised but with wrong message
379n/a def raise_wrong_message():
380n/a raise TypeError('foo')
381n/a self.assertMessagesCM('assertRaisesRegex', (TypeError, 'regex'),
382n/a raise_wrong_message,
383n/a ['^"regex" does not match "foo"$', '^oops$',
384n/a '^"regex" does not match "foo"$',
385n/a '^"regex" does not match "foo" : oops$'])
386n/a
387n/a def testAssertWarns(self):
388n/a self.assertMessagesCM('assertWarns', (UserWarning,), lambda: None,
389n/a ['^UserWarning not triggered$', '^oops$',
390n/a '^UserWarning not triggered$',
391n/a '^UserWarning not triggered : oops$'])
392n/a
393n/a def testAssertWarnsRegex(self):
394n/a # test error not raised
395n/a self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'unused regex'),
396n/a lambda: None,
397n/a ['^UserWarning not triggered$', '^oops$',
398n/a '^UserWarning not triggered$',
399n/a '^UserWarning not triggered : oops$'])
400n/a # test warning raised but with wrong message
401n/a def raise_wrong_message():
402n/a warnings.warn('foo')
403n/a self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'regex'),
404n/a raise_wrong_message,
405n/a ['^"regex" does not match "foo"$', '^oops$',
406n/a '^"regex" does not match "foo"$',
407n/a '^"regex" does not match "foo" : oops$'])
408n/a
409n/a
410n/aif __name__ == "__main__":
411n/a unittest.main()