Best Python code snippet using hypothesis
test_assertions.py
Source:test_assertions.py  
1import datetime2import warnings3import weakref4import unittest5from itertools import product6class 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        self.assertAlmostEqual(1.1, 1.0, places=0)15        self.assertRaises(self.failureException,16                          self.assertAlmostEqual, 1.1, 1.0, places=1)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        self.assertAlmostEqual(float('inf'), float('inf'))24        self.assertRaises(self.failureException, self.assertNotAlmostEqual,25                          float('inf'), float('inf'))26    def test_AmostEqualWithDelta(self):27        self.assertAlmostEqual(1.1, 1.0, delta=0.5)28        self.assertAlmostEqual(1.0, 1.1, delta=0.5)29        self.assertNotAlmostEqual(1.1, 1.0, delta=0.05)30        self.assertNotAlmostEqual(1.0, 1.1, delta=0.05)31        self.assertAlmostEqual(1.0, 1.0, delta=0.5)32        self.assertRaises(self.failureException, self.assertNotAlmostEqual,33                          1.0, 1.0, delta=0.5)34        self.assertRaises(self.failureException, self.assertAlmostEqual,35                          1.1, 1.0, delta=0.05)36        self.assertRaises(self.failureException, self.assertNotAlmostEqual,37                          1.1, 1.0, delta=0.5)38        self.assertRaises(TypeError, self.assertAlmostEqual,39                          1.1, 1.0, places=2, delta=2)40        self.assertRaises(TypeError, self.assertNotAlmostEqual,41                          1.1, 1.0, places=2, delta=2)42        first = datetime.datetime.now()43        second = first + datetime.timedelta(seconds=10)44        self.assertAlmostEqual(first, second,45                               delta=datetime.timedelta(seconds=20))46        self.assertNotAlmostEqual(first, second,47                                  delta=datetime.timedelta(seconds=5))48    def test_assertRaises(self):49        def _raise(e):50            raise e51        self.assertRaises(KeyError, _raise, KeyError)52        self.assertRaises(KeyError, _raise, KeyError("key"))53        try:54            self.assertRaises(KeyError, lambda: None)55        except self.failureException as e:56            self.assertIn("KeyError not raised", str(e))57        else:58            self.fail("assertRaises() didn't fail")59        try:60            self.assertRaises(KeyError, _raise, ValueError)61        except ValueError:62            pass63        else:64            self.fail("assertRaises() didn't let exception pass through")65        with self.assertRaises(KeyError) as cm:66            try:67                raise KeyError68            except Exception as e:69                exc = e70                raise71        self.assertIs(cm.exception, exc)72        with self.assertRaises(KeyError):73            raise KeyError("key")74        try:75            with self.assertRaises(KeyError):76                pass77        except self.failureException as e:78            self.assertIn("KeyError not raised", str(e))79        else:80            self.fail("assertRaises() didn't fail")81        try:82            with self.assertRaises(KeyError):83                raise ValueError84        except ValueError:85            pass86        else:87            self.fail("assertRaises() didn't let exception pass through")88    def test_assertRaises_frames_survival(self):89        # Issue #9815: assertRaises should avoid keeping local variables90        # in a traceback alive.91        class A:92            pass93        wr = None94        class Foo(unittest.TestCase):95            def foo(self):96                nonlocal wr97                a = A()98                wr = weakref.ref(a)99                try:100                    raise OSError101                except OSError:102                    raise ValueError103            def test_functional(self):104                self.assertRaises(ValueError, self.foo)105            def test_with(self):106                with self.assertRaises(ValueError):107                    self.foo()108        Foo("test_functional").run()109        self.assertIsNone(wr())110        Foo("test_with").run()111        self.assertIsNone(wr())112    def testAssertNotRegex(self):113        self.assertNotRegex('Ala ma kota', r'r+')114        try:115            self.assertNotRegex('Ala ma kota', r'k.t', 'Message')116        except self.failureException as e:117            self.assertIn('Message', e.args[0])118        else:119            self.fail('assertNotRegex should have failed.')120class TestLongMessage(unittest.TestCase):121    """Test that the individual asserts honour longMessage.122    This actually tests all the message behaviour for123    asserts that use longMessage."""124    def setUp(self):125        class TestableTestFalse(unittest.TestCase):126            longMessage = False127            failureException = self.failureException128            def testTest(self):129                pass130        class TestableTestTrue(unittest.TestCase):131            longMessage = True132            failureException = self.failureException133            def testTest(self):134                pass135        self.testableTrue = TestableTestTrue('testTest')136        self.testableFalse = TestableTestFalse('testTest')137    def testDefault(self):138        self.assertTrue(unittest.TestCase.longMessage)139    def test_formatMsg(self):140        self.assertEqual(self.testableFalse._formatMessage(None, "foo"), "foo")141        self.assertEqual(self.testableFalse._formatMessage("foo", "bar"), "foo")142        self.assertEqual(self.testableTrue._formatMessage(None, "foo"), "foo")143        self.assertEqual(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")144        # This blows up if _formatMessage uses string concatenation145        self.testableTrue._formatMessage(object(), 'foo')146    def test_formatMessage_unicode_error(self):147        one = ''.join(chr(i) for i in range(255))148        # this used to cause a UnicodeDecodeError constructing msg149        self.testableTrue._formatMessage(one, '\uFFFD')150    def assertMessages(self, methodName, args, errors):151        """152        Check that methodName(*args) raises the correct error messages.153        errors should be a list of 4 regex that match the error when:154          1) longMessage = False and no msg passed;155          2) longMessage = False and msg passed;156          3) longMessage = True and no msg passed;157          4) longMessage = True and msg passed;158        """159        def getMethod(i):160            useTestableFalse = i < 2161            if useTestableFalse:162                test = self.testableFalse163            else:164                test = self.testableTrue165            return getattr(test, methodName)166        for i, expected_regex in enumerate(errors):167            testMethod = getMethod(i)168            kwargs = {}169            withMsg = i % 2170            if withMsg:171                kwargs = {"msg": "oops"}172            with self.assertRaisesRegex(self.failureException,173                                        expected_regex=expected_regex):174                testMethod(*args, **kwargs)175    def testAssertTrue(self):176        self.assertMessages('assertTrue', (False,),177                            ["^False is not true$", "^oops$", "^False is not true$",178                             "^False is not true : oops$"])179    def testAssertFalse(self):180        self.assertMessages('assertFalse', (True,),181                            ["^True is not false$", "^oops$", "^True is not false$",182                             "^True is not false : oops$"])183    def testNotEqual(self):184        self.assertMessages('assertNotEqual', (1, 1),185                            ["^1 == 1$", "^oops$", "^1 == 1$",186                             "^1 == 1 : oops$"])187    def testAlmostEqual(self):188        self.assertMessages(189            'assertAlmostEqual', (1, 2),190            [r"^1 != 2 within 7 places \(1 difference\)$", "^oops$",191             r"^1 != 2 within 7 places \(1 difference\)$",192             r"^1 != 2 within 7 places \(1 difference\) : oops$"])193    def testNotAlmostEqual(self):194        self.assertMessages('assertNotAlmostEqual', (1, 1),195                            ["^1 == 1 within 7 places$", "^oops$",196                             "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])197    def test_baseAssertEqual(self):198        self.assertMessages('_baseAssertEqual', (1, 2),199                            ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])200    def testAssertSequenceEqual(self):201        # Error messages are multiline so not testing on full message202        # assertTupleEqual and assertListEqual delegate to this method203        self.assertMessages('assertSequenceEqual', ([], [None]),204                            [r"\+ \[None\]$", "^oops$", r"\+ \[None\]$",205                             r"\+ \[None\] : oops$"])206    def testAssertSetEqual(self):207        self.assertMessages('assertSetEqual', (set(), set([None])),208                            ["None$", "^oops$", "None$",209                             "None : oops$"])210    def testAssertIn(self):211        self.assertMessages('assertIn', (None, []),212                            [r'^None not found in \[\]$', "^oops$",213                             r'^None not found in \[\]$',214                             r'^None not found in \[\] : oops$'])215    def testAssertNotIn(self):216        self.assertMessages('assertNotIn', (None, [None]),217                            [r'^None unexpectedly found in \[None\]$', "^oops$",218                             r'^None unexpectedly found in \[None\]$',219                             r'^None unexpectedly found in \[None\] : oops$'])220    def testAssertDictEqual(self):221        self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),222                            [r"\+ \{'key': 'value'\}$", "^oops$",223                             r"\+ \{'key': 'value'\}$",224                             r"\+ \{'key': 'value'\} : oops$"])225    def testAssertDictContainsSubset(self):226        with warnings.catch_warnings():227            warnings.simplefilter("ignore", DeprecationWarning)228            self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),229                                ["^Missing: 'key'$", "^oops$",230                                 "^Missing: 'key'$",231                                 "^Missing: 'key' : oops$"])232    def testAssertMultiLineEqual(self):233        self.assertMessages('assertMultiLineEqual', ("", "foo"),234                            [r"\+ foo$", "^oops$",235                             r"\+ foo$",236                             r"\+ foo : oops$"])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    def testAssertLessEqual(self):242        self.assertMessages('assertLessEqual', (2, 1),243                            ["^2 not less than or equal to 1$", "^oops$",244                             "^2 not less than or equal to 1$",245                             "^2 not less than or equal to 1 : oops$"])246    def testAssertGreater(self):247        self.assertMessages('assertGreater', (1, 2),248                            ["^1 not greater than 2$", "^oops$",249                             "^1 not greater than 2$",250                             "^1 not greater than 2 : oops$"])251    def testAssertGreaterEqual(self):252        self.assertMessages('assertGreaterEqual', (1, 2),253                            ["^1 not greater than or equal to 2$", "^oops$",254                             "^1 not greater than or equal to 2$",255                             "^1 not greater than or equal to 2 : oops$"])256    def testAssertIsNone(self):257        self.assertMessages('assertIsNone', ('not None',),258                            ["^'not None' is not None$", "^oops$",259                             "^'not None' is not None$",260                             "^'not None' is not None : oops$"])261    def testAssertIsNotNone(self):262        self.assertMessages('assertIsNotNone', (None,),263                            ["^unexpectedly None$", "^oops$",264                             "^unexpectedly None$",265                             "^unexpectedly None : oops$"])266    def testAssertIs(self):267        self.assertMessages('assertIs', (None, 'foo'),268                            ["^None is not 'foo'$", "^oops$",269                             "^None is not 'foo'$",270                             "^None is not 'foo' : oops$"])271    def testAssertIsNot(self):272        self.assertMessages('assertIsNot', (None, None),273                            ["^unexpectedly identical: None$", "^oops$",274                             "^unexpectedly identical: None$",275                             "^unexpectedly identical: None : oops$"])276    def testAssertRegex(self):277        self.assertMessages('assertRegex', ('foo', 'bar'),278                            ["^Regex didn't match:",279                             "^oops$",280                             "^Regex didn't match:",281                             "^Regex didn't match: (.*) : oops$"])282    def testAssertNotRegex(self):283        self.assertMessages('assertNotRegex', ('foo', 'foo'),284                            ["^Regex matched:",285                             "^oops$",286                             "^Regex matched:",287                             "^Regex matched: (.*) : oops$"])288    def assertMessagesCM(self, methodName, args, func, errors):289        """290        Check that the correct error messages are raised while executing:291          with method(*args):292              func()293        *errors* should be a list of 4 regex that match the error when:294          1) longMessage = False and no msg passed;295          2) longMessage = False and msg passed;296          3) longMessage = True and no msg passed;297          4) longMessage = True and msg passed;298        """299        p = product((self.testableFalse, self.testableTrue),300                    ({}, {"msg": "oops"}))301        for (cls, kwargs), err in zip(p, errors):302            method = getattr(cls, methodName)303            with self.assertRaisesRegex(cls.failureException, err):304                with method(*args, **kwargs) as cm:305                    func()306    def testAssertRaises(self):307        self.assertMessagesCM('assertRaises', (TypeError,), lambda: None,308                              ['^TypeError not raised$', '^oops$',309                               '^TypeError not raised$',310                               '^TypeError not raised : oops$'])311    def testAssertRaisesRegex(self):312        # test error not raised313        self.assertMessagesCM('assertRaisesRegex', (TypeError, 'unused regex'),314                              lambda: None,315                              ['^TypeError not raised$', '^oops$',316                               '^TypeError not raised$',317                               '^TypeError not raised : oops$'])318        # test error raised but with wrong message319        def raise_wrong_message():320            raise TypeError('foo')321        self.assertMessagesCM('assertRaisesRegex', (TypeError, 'regex'),322                              raise_wrong_message,323                              ['^"regex" does not match "foo"$', '^oops$',324                               '^"regex" does not match "foo"$',325                               '^"regex" does not match "foo" : oops$'])326    def testAssertWarns(self):327        self.assertMessagesCM('assertWarns', (UserWarning,), lambda: None,328                              ['^UserWarning not triggered$', '^oops$',329                               '^UserWarning not triggered$',330                               '^UserWarning not triggered : oops$'])331    def testAssertWarnsRegex(self):332        # test error not raised333        self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'unused regex'),334                              lambda: None,335                              ['^UserWarning not triggered$', '^oops$',336                               '^UserWarning not triggered$',337                               '^UserWarning not triggered : oops$'])338        # test warning raised but with wrong message339        def raise_wrong_message():340            warnings.warn('foo')341        self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'regex'),342                              raise_wrong_message,343                              ['^"regex" does not match "foo"$', '^oops$',344                               '^"regex" does not match "foo"$',345                               '^"regex" does not match "foo" : oops$'])346if __name__ == "__main__":...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
