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