From a99b80186d4ac55b78a380bd66708ba67df63712 Mon Sep 17 00:00:00 2001 From: Brian Pugh Date: Thu, 10 Nov 2022 09:15:24 -0800 Subject: [PATCH] tempfile: Add unit tests for tempfile, and don't use os.path.join. --- python-stdlib/tempfile/tempfile.py | 2 +- python-stdlib/tempfile/test_tempfile.py | 50 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 python-stdlib/tempfile/test_tempfile.py diff --git a/python-stdlib/tempfile/tempfile.py b/python-stdlib/tempfile/tempfile.py index 3d0a485c..87d889ef 100644 --- a/python-stdlib/tempfile/tempfile.py +++ b/python-stdlib/tempfile/tempfile.py @@ -37,7 +37,7 @@ def mkdtemp(suffix=None, prefix=None, dir=None): while True: name = _get_candidate_name() - file = os.path.join(dir, prefix + name + suffix) + file = dir + "/" + prefix + name + suffix if _try(os.mkdir, file): return file diff --git a/python-stdlib/tempfile/test_tempfile.py b/python-stdlib/tempfile/test_tempfile.py new file mode 100644 index 00000000..f9499d18 --- /dev/null +++ b/python-stdlib/tempfile/test_tempfile.py @@ -0,0 +1,50 @@ +import os +import tempfile +import unittest + + +class Base(unittest.TestCase): + def assertExists(self, fn): + os.stat(fn) + + def assertNotExists(self, fn): + with self.assertRaises(OSError): + os.stat(fn) + + +class TestMkdtemp(Base): + def test_no_args(self): + fn = tempfile.mkdtemp() + self.assertTrue(fn.startswith("/tmp")) + self.assertExists(fn) + os.rmdir(fn) + + def test_prefix(self): + fn = tempfile.mkdtemp(prefix="foo") + self.assertTrue(fn.startswith("/tmp")) + self.assertTrue("foo" in fn) + self.assertFalse(fn.endswith("foo")) + self.assertExists(fn) + os.rmdir(fn) + + def test_suffix(self): + fn = tempfile.mkdtemp(suffix="foo") + self.assertTrue(fn.startswith("/tmp")) + self.assertTrue(fn.endswith("foo")) + self.assertExists(fn) + os.rmdir(fn) + + def test_dir(self): + fn = tempfile.mkdtemp(dir="tmp_micropython") + self.assertTrue(fn.startswith("tmp_micropython")) + self.assertExists(fn) + os.rmdir(fn) + + +class TestTemporaryDirectory(Base): + def test_context_manager_no_args(self): + with tempfile.TemporaryDirectory() as fn: + self.assertTrue(isinstance(fn, str)) + self.assertTrue(fn.startswith("/tmp")) + self.assertExists(fn) + self.assertNotExists(fn)