Ejemplo n.º 1
0
 def test_swap_item(self):
     D = {"x":1}
     with support.swap_item(D, "x", 5) as x:
         self.assertEqual(D["x"], 5)
         self.assertEqual(x, 1)
     self.assertEqual(D["x"], 1)
     with support.swap_item(D, "y", 5) as y:
         self.assertEqual(D["y"], 5)
         self.assertIsNone(y)
     self.assertNotIn("y", D)
     with support.swap_item(D, "y", 5):
         del D["y"]
     self.assertNotIn("y", D)
    def test_cannot_replace_builtins_dict_between_calls(self):
        def foo():
            return len([1, 2, 3])

        self.configure_func(foo)

        self.assertEqual(foo(), 3)
        with swap_item(globals(), "__builtins__", {"len": lambda x: 7}):
            self.assertEqual(foo(), 3)
    def test_globals_shadow_builtins(self):
        # Modify globals() to shadow an entry in builtins.
        def foo():
            return len([1, 2, 3])

        self.configure_func(foo)

        self.assertEqual(foo(), 3)
        with swap_item(globals(), "len", lambda x: 7):
            self.assertEqual(foo(), 7)
    def test_cannot_replace_builtins_dict_while_active(self):
        def foo():
            x = range(3)
            yield len(x)
            yield len(x)

        self.configure_func(foo)

        g = foo()
        self.assertEqual(next(g), 3)
        with swap_item(globals(), "__builtins__", {"len": lambda x: 7}):
            self.assertEqual(next(g), 3)
    def test_override_builtin(self):
        # Test that overriding builtins.__import__ can bypass sys.modules.
        import os

        def foo():
            import os
            return os
        self.assertEqual(foo(), os)  # Quick sanity check.

        with swap_attr(builtins, "__import__", lambda *x: 5):
            self.assertEqual(foo(), 5)

        # Test what happens when we shadow __import__ in globals(); this
        # currently does not impact the import process, but if this changes,
        # other code will need to change, so keep this test as a tripwire.
        with swap_item(globals(), "__import__", lambda *x: 5):
            self.assertEqual(foo(), os)
 def copy(self, obj, proto):
     with support.swap_item(sys.modules, 'operator', self.module):
         pickled = pickle.dumps(obj, proto)
     with support.swap_item(sys.modules, 'operator', self.module2):
         return pickle.loads(pickled)