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