blob: fe658492f3397204550cbcc61043d8e368b8dc16 [file] [log] [blame]
Michael Foord2560e5c2010-03-27 12:34:21 +00001import unittest
2
Michael Foord2560e5c2010-03-27 12:34:21 +00003
4class Test_Assertions(unittest.TestCase):
5 def test_AlmostEqual(self):
6 self.assertAlmostEqual(1.00000001, 1.0)
7 self.assertNotAlmostEqual(1.0000001, 1.0)
8 self.assertRaises(self.failureException,
9 self.assertAlmostEqual, 1.0000001, 1.0)
10 self.assertRaises(self.failureException,
11 self.assertNotAlmostEqual, 1.00000001, 1.0)
12
13 self.assertAlmostEqual(1.1, 1.0, places=0)
14 self.assertRaises(self.failureException,
15 self.assertAlmostEqual, 1.1, 1.0, places=1)
16
17 self.assertAlmostEqual(0, .1+.1j, places=0)
18 self.assertNotAlmostEqual(0, .1+.1j, places=1)
19 self.assertRaises(self.failureException,
20 self.assertAlmostEqual, 0, .1+.1j, places=1)
21 self.assertRaises(self.failureException,
22 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
23
24 self.assertAlmostEqual(float('inf'), float('inf'))
25 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
26 float('inf'), float('inf'))
27
28
29 def test_assertRaises(self):
30 def _raise(e):
31 raise e
32 self.assertRaises(KeyError, _raise, KeyError)
33 self.assertRaises(KeyError, _raise, KeyError("key"))
34 try:
35 self.assertRaises(KeyError, lambda: None)
36 except self.failureException as e:
37 self.assertIn("KeyError not raised", str(e))
38 else:
39 self.fail("assertRaises() didn't fail")
40 try:
41 self.assertRaises(KeyError, _raise, ValueError)
42 except ValueError:
43 pass
44 else:
45 self.fail("assertRaises() didn't let exception pass through")
46 with self.assertRaises(KeyError) as cm:
47 try:
48 raise KeyError
49 except Exception as e:
50 exc = e
51 raise
52 self.assertIs(cm.exception, exc)
53
54 with self.assertRaises(KeyError):
55 raise KeyError("key")
56 try:
57 with self.assertRaises(KeyError):
58 pass
59 except self.failureException as e:
60 self.assertIn("KeyError not raised", str(e))
61 else:
62 self.fail("assertRaises() didn't fail")
63 try:
64 with self.assertRaises(KeyError):
65 raise ValueError
66 except ValueError:
67 pass
68 else:
69 self.fail("assertRaises() didn't let exception pass through")
70
71
72class TestLongMessage(unittest.TestCase):
73 """Test that the individual asserts honour longMessage.
74 This actually tests all the message behaviour for
75 asserts that use longMessage."""
76
77 def setUp(self):
78 class TestableTestFalse(unittest.TestCase):
79 longMessage = False
80 failureException = self.failureException
81
82 def testTest(self):
83 pass
84
85 class TestableTestTrue(unittest.TestCase):
86 longMessage = True
87 failureException = self.failureException
88
89 def testTest(self):
90 pass
91
92 self.testableTrue = TestableTestTrue('testTest')
93 self.testableFalse = TestableTestFalse('testTest')
94
95 def testDefault(self):
96 self.assertFalse(unittest.TestCase.longMessage)
97
98 def test_formatMsg(self):
99 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
100 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
101
102 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
103 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
104
105 # This blows up if _formatMessage uses string concatenation
106 self.testableTrue._formatMessage(object(), 'foo')
107
108 def test_formatMessage_unicode_error(self):
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000109 one = ''.join(chr(i) for i in range(255))
110 # this used to cause a UnicodeDecodeError constructing msg
111 self.testableTrue._formatMessage(one, '\uFFFD')
Michael Foord2560e5c2010-03-27 12:34:21 +0000112
113 def assertMessages(self, methodName, args, errors):
114 def getMethod(i):
115 useTestableFalse = i < 2
116 if useTestableFalse:
117 test = self.testableFalse
118 else:
119 test = self.testableTrue
120 return getattr(test, methodName)
121
122 for i, expected_regexp in enumerate(errors):
123 testMethod = getMethod(i)
124 kwargs = {}
125 withMsg = i % 2
126 if withMsg:
127 kwargs = {"msg": "oops"}
128
129 with self.assertRaisesRegexp(self.failureException,
130 expected_regexp=expected_regexp):
131 testMethod(*args, **kwargs)
132
133 def testAssertTrue(self):
134 self.assertMessages('assertTrue', (False,),
135 ["^False is not True$", "^oops$", "^False is not True$",
136 "^False is not True : oops$"])
137
138 def testAssertFalse(self):
139 self.assertMessages('assertFalse', (True,),
140 ["^True is not False$", "^oops$", "^True is not False$",
141 "^True is not False : oops$"])
142
143 def testNotEqual(self):
144 self.assertMessages('assertNotEqual', (1, 1),
145 ["^1 == 1$", "^oops$", "^1 == 1$",
146 "^1 == 1 : oops$"])
147
148 def testAlmostEqual(self):
149 self.assertMessages('assertAlmostEqual', (1, 2),
150 ["^1 != 2 within 7 places$", "^oops$",
151 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
152
153 def testNotAlmostEqual(self):
154 self.assertMessages('assertNotAlmostEqual', (1, 1),
155 ["^1 == 1 within 7 places$", "^oops$",
156 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
157
158 def test_baseAssertEqual(self):
159 self.assertMessages('_baseAssertEqual', (1, 2),
160 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
161
162 def testAssertSequenceEqual(self):
163 # Error messages are multiline so not testing on full message
164 # assertTupleEqual and assertListEqual delegate to this method
165 self.assertMessages('assertSequenceEqual', ([], [None]),
166 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
167 r"\+ \[None\] : oops$"])
168
169 def testAssertSetEqual(self):
170 self.assertMessages('assertSetEqual', (set(), set([None])),
171 ["None$", "^oops$", "None$",
172 "None : oops$"])
173
174 def testAssertIn(self):
175 self.assertMessages('assertIn', (None, []),
176 ['^None not found in \[\]$', "^oops$",
177 '^None not found in \[\]$',
178 '^None not found in \[\] : oops$'])
179
180 def testAssertNotIn(self):
181 self.assertMessages('assertNotIn', (None, [None]),
182 ['^None unexpectedly found in \[None\]$', "^oops$",
183 '^None unexpectedly found in \[None\]$',
184 '^None unexpectedly found in \[None\] : oops$'])
185
186 def testAssertDictEqual(self):
187 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
188 [r"\+ \{'key': 'value'\}$", "^oops$",
189 "\+ \{'key': 'value'\}$",
190 "\+ \{'key': 'value'\} : oops$"])
191
192 def testAssertDictContainsSubset(self):
193 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
194 ["^Missing: 'key'$", "^oops$",
195 "^Missing: 'key'$",
196 "^Missing: 'key' : oops$"])
197
198 def testAssertItemsEqual(self):
199 self.assertMessages('assertItemsEqual', ([], [None]),
200 [r"\[None\]$", "^oops$",
201 r"\[None\]$",
202 r"\[None\] : oops$"])
203
204 def testAssertMultiLineEqual(self):
205 self.assertMessages('assertMultiLineEqual', ("", "foo"),
206 [r"\+ foo$", "^oops$",
207 r"\+ foo$",
208 r"\+ foo : oops$"])
209
210 def testAssertLess(self):
211 self.assertMessages('assertLess', (2, 1),
212 ["^2 not less than 1$", "^oops$",
213 "^2 not less than 1$", "^2 not less than 1 : oops$"])
214
215 def testAssertLessEqual(self):
216 self.assertMessages('assertLessEqual', (2, 1),
217 ["^2 not less than or equal to 1$", "^oops$",
218 "^2 not less than or equal to 1$",
219 "^2 not less than or equal to 1 : oops$"])
220
221 def testAssertGreater(self):
222 self.assertMessages('assertGreater', (1, 2),
223 ["^1 not greater than 2$", "^oops$",
224 "^1 not greater than 2$",
225 "^1 not greater than 2 : oops$"])
226
227 def testAssertGreaterEqual(self):
228 self.assertMessages('assertGreaterEqual', (1, 2),
229 ["^1 not greater than or equal to 2$", "^oops$",
230 "^1 not greater than or equal to 2$",
231 "^1 not greater than or equal to 2 : oops$"])
232
233 def testAssertIsNone(self):
234 self.assertMessages('assertIsNone', ('not None',),
235 ["^'not None' is not None$", "^oops$",
236 "^'not None' is not None$",
237 "^'not None' is not None : oops$"])
238
239 def testAssertIsNotNone(self):
240 self.assertMessages('assertIsNotNone', (None,),
241 ["^unexpectedly None$", "^oops$",
242 "^unexpectedly None$",
243 "^unexpectedly None : oops$"])
244
245 def testAssertIs(self):
246 self.assertMessages('assertIs', (None, 'foo'),
247 ["^None is not 'foo'$", "^oops$",
248 "^None is not 'foo'$",
249 "^None is not 'foo' : oops$"])
250
251 def testAssertIsNot(self):
252 self.assertMessages('assertIsNot', (None, None),
253 ["^unexpectedly identical: None$", "^oops$",
254 "^unexpectedly identical: None$",
255 "^unexpectedly identical: None : oops$"])