diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2017-07-04 04:55:32 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-07-04 04:55:32 (GMT) |
commit | bebd2cfa5f21811dd0ee4f3b1a1b85d379b83436 (patch) | |
tree | b089cbbaf1aa59ae16419beb7523a6a57dfe1c1f | |
parent | 4132adb4b8f90893d8f19ff46edff56f189faca0 (diff) | |
download | cpython-bebd2cfa5f21811dd0ee4f3b1a1b85d379b83436.zip cpython-bebd2cfa5f21811dd0ee4f3b1a1b85d379b83436.tar.gz cpython-bebd2cfa5f21811dd0ee4f3b1a1b85d379b83436.tar.bz2 |
[3.6] bpo-30441: Fix bug when modifying os.environ while iterating over it (GH-2409). (#2556)
(cherry picked from commit 8a8d28501fc8ce25926d168f1c657656c809fd4c)
-rw-r--r-- | Lib/os.py | 4 | ||||
-rw-r--r-- | Lib/test/test_os.py | 24 | ||||
-rw-r--r-- | Misc/ACKS | 1 | ||||
-rw-r--r-- | Misc/NEWS.d/next/Library/2017-06-29-14-25-14.bpo-30441.3Wh9kc.rst | 1 |
4 files changed, 29 insertions, 1 deletions
@@ -685,7 +685,9 @@ class _Environ(MutableMapping): raise KeyError(key) from None def __iter__(self): - for key in self._data: + # list() from dict object is an atomic operation + keys = list(self._data) + for key in keys: yield self.decodekey(key) def __len__(self): diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index fdeb9a9..f74c199 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -836,6 +836,30 @@ class EnvironTests(mapping_tests.BasicTestMappingProtocol): self.assertIs(cm.exception.args[0], missing) self.assertTrue(cm.exception.__suppress_context__) + def _test_environ_iteration(self, collection): + iterator = iter(collection) + new_key = "__new_key__" + + next(iterator) # start iteration over os.environ.items + + # add a new key in os.environ mapping + os.environ[new_key] = "test_environ_iteration" + + try: + next(iterator) # force iteration over modified mapping + self.assertEqual(os.environ[new_key], "test_environ_iteration") + finally: + del os.environ[new_key] + + def test_iter_error_when_changing_os_environ(self): + self._test_environ_iteration(os.environ) + + def test_iter_error_when_changing_os_environ_items(self): + self._test_environ_iteration(os.environ.items()) + + def test_iter_error_when_changing_os_environ_values(self): + self._test_environ_iteration(os.environ.values()) + class WalkTests(unittest.TestCase): """Tests for os.walk().""" @@ -1077,6 +1077,7 @@ Vilmos Nebehaj Fredrik Nehr Tony Nelson Trent Nelson +Osvaldo Santana Neto Chad Netzer Max Neunhöffer Anthon van der Neut diff --git a/Misc/NEWS.d/next/Library/2017-06-29-14-25-14.bpo-30441.3Wh9kc.rst b/Misc/NEWS.d/next/Library/2017-06-29-14-25-14.bpo-30441.3Wh9kc.rst new file mode 100644 index 0000000..55dd613 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2017-06-29-14-25-14.bpo-30441.3Wh9kc.rst @@ -0,0 +1 @@ +Fix bug when modifying os.environ while iterating over it |