bpo-40701: tempfile mixes str and bytes in an inconsistent manner (GH-20442)
The case of tempfile.tempdir variable being bytes is now handled consistently.
The getters return the right type and no more error of mixing str and bytes unless explicitly caused by the user.
Adds a regression test.
Expands the documentation to clarify the behavior.
Co-authored-by: Eric L <ewl+git@lavar.de>
Co-authored-by: Gregory P. Smith <greg@krypto.org>
diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py
index 77d710e..5822c75 100644
--- a/Lib/test/test_tempfile.py
+++ b/Lib/test/test_tempfile.py
@@ -667,6 +667,37 @@ def test_choose_directory(self):
finally:
os.rmdir(dir)
+ def test_for_tempdir_is_bytes_issue40701_api_warts(self):
+ orig_tempdir = tempfile.tempdir
+ self.assertIsInstance(tempfile.tempdir, (str, type(None)))
+ try:
+ fd, path = tempfile.mkstemp()
+ os.close(fd)
+ os.unlink(path)
+ self.assertIsInstance(path, str)
+ tempfile.tempdir = tempfile.gettempdirb()
+ self.assertIsInstance(tempfile.tempdir, bytes)
+ self.assertIsInstance(tempfile.gettempdir(), str)
+ self.assertIsInstance(tempfile.gettempdirb(), bytes)
+ fd, path = tempfile.mkstemp()
+ os.close(fd)
+ os.unlink(path)
+ self.assertIsInstance(path, bytes)
+ fd, path = tempfile.mkstemp(suffix='.txt')
+ os.close(fd)
+ os.unlink(path)
+ self.assertIsInstance(path, str)
+ fd, path = tempfile.mkstemp(prefix='test-temp-')
+ os.close(fd)
+ os.unlink(path)
+ self.assertIsInstance(path, str)
+ fd, path = tempfile.mkstemp(dir=tempfile.gettempdir())
+ os.close(fd)
+ os.unlink(path)
+ self.assertIsInstance(path, str)
+ finally:
+ tempfile.tempdir = orig_tempdir
+
class TestMkdtemp(TestBadTempdir, BaseTestCase):
"""Test mkdtemp()."""
@@ -775,6 +806,32 @@ def test_collision_with_existing_directory(self):
dir2 = tempfile.mkdtemp()
self.assertTrue(dir2.endswith('bbb'))
+ def test_for_tempdir_is_bytes_issue40701_api_warts(self):
+ orig_tempdir = tempfile.tempdir
+ self.assertIsInstance(tempfile.tempdir, (str, type(None)))
+ try:
+ path = tempfile.mkdtemp()
+ os.rmdir(path)
+ self.assertIsInstance(path, str)
+ tempfile.tempdir = tempfile.gettempdirb()
+ self.assertIsInstance(tempfile.tempdir, bytes)
+ self.assertIsInstance(tempfile.gettempdir(), str)
+ self.assertIsInstance(tempfile.gettempdirb(), bytes)
+ path = tempfile.mkdtemp()
+ os.rmdir(path)
+ self.assertIsInstance(path, bytes)
+ path = tempfile.mkdtemp(suffix='-dir')
+ os.rmdir(path)
+ self.assertIsInstance(path, str)
+ path = tempfile.mkdtemp(prefix='test-mkdtemp-')
+ os.rmdir(path)
+ self.assertIsInstance(path, str)
+ path = tempfile.mkdtemp(dir=tempfile.gettempdir())
+ os.rmdir(path)
+ self.assertIsInstance(path, str)
+ finally:
+ tempfile.tempdir = orig_tempdir
+
class TestMktemp(BaseTestCase):
"""Test mktemp()."""