diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 6dac9ab3c41717..f0329ed841bb1c 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -117,11 +117,15 @@ def _sanitize_params(prefix, suffix, dir): output_type = _infer_return_type(prefix, suffix, dir) if suffix is None: suffix = output_type() + if _os.path.dirname(suffix): + raise ValueError("'suffix' can't contain a directory component") if prefix is None: if output_type is str: prefix = template else: prefix = _os.fsencode(template) + if _os.path.dirname(prefix): + raise ValueError("'prefix' can't contain a directory component") if dir is None: if output_type is str: dir = gettempdir() diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 0e00ff1d0cc366..d56c44c02ab001 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -2054,5 +2054,49 @@ def test_delete_false(self): self.assertTrue(os.path.exists(working_dir)) shutil.rmtree(working_dir) + +class TestPrefixAndSuffix(BaseTestCase): + DATA = ( + f"dir{os.sep}name", + f"{os.sep}abs_name", + os.fsencode(f"dir{os.sep}name"), + os.fsencode(f"{os.sep}abs_name"), + ) + if os.altsep is not None: + DATA += ( + f"dir{os.altsep}name", + f"{os.altsep}abs_name", + os.fsencode(f"dir{os.altsep}name"), + os.fsencode(f"{os.altsep}abs_name"), + ) + + def test_prefix_error(self): + MESSAGE = "'prefix' can't contain a directory component" + + for value in self.DATA: + with self.subTest((value)): + with self.assertRaisesRegex(ValueError, MESSAGE): + tempfile.mkstemp(prefix=value) + with self.assertRaisesRegex(ValueError, MESSAGE): + os.rmdir(tempfile.mkdtemp(prefix=value)) + with self.assertRaisesRegex(ValueError, MESSAGE): + tempfile.TemporaryFile(prefix=value) + with self.assertRaisesRegex(ValueError, MESSAGE): + tempfile.NamedTemporaryFile(prefix=value) + + def test_suffix_error(self): + MESSAGE = "'suffix' can't contain a directory component" + + for value in self.DATA: + with self.subTest((value)): + with self.assertRaisesRegex(ValueError, MESSAGE): + tempfile.mkstemp(suffix=value) + with self.assertRaisesRegex(ValueError, MESSAGE): + os.rmdir(tempfile.mkdtemp(suffix=value)) + with self.assertRaisesRegex(ValueError, MESSAGE): + tempfile.TemporaryFile(suffix=value) + with self.assertRaisesRegex(ValueError, MESSAGE): + tempfile.NamedTemporaryFile(suffix=value) + if __name__ == "__main__": unittest.main()