Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

An initial attempt at a tempdir implementation. It fails because temp…

…dir() / 'foo' tries to construct another tempdir instance.
  • Loading branch information...
commit bf82b390a3df6d77370f9470816a93760ca3ca28 1 parent fc339bc
@jaraco authored
Showing with 60 additions and 2 deletions.
  1. +21 −0 path.py
  2. +39 −2 test_path.py
View
21 path.py
@@ -53,6 +53,7 @@
import codecs
import hashlib
import errno
+import tempfile
try:
import win32security
@@ -1099,3 +1100,23 @@ def chroot(self):
def startfile(self):
os.startfile(self)
return self
+
+class tempdir(path):
+ """
+ A temporary directory via tempfile.mkdtemp, and constructed with the
+ same parameters.
+ """
+
+ def __new__(cls, *args, **kwargs):
+ dirname = tempfile.mkdtemp(*args, **kwargs)
+ return super(tempdir, cls).__new__(cls, dirname)
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ if not exc_value:
+ self.rmtree()
View
41 test_path.py
@@ -30,7 +30,7 @@
import ntpath
import posixpath
-from path import path
+from path import path, tempdir
def p(**choices):
@@ -218,7 +218,10 @@ def testTouchReturnsSelf(self):
ret = p.touch()
self.assertEquals(p, ret)
-class TempDirTestCase(unittest.TestCase):
+class ScratchDirTestCase(unittest.TestCase):
+ """
+ Tests that run in a temporary directory (does not test tempdir class)
+ """
def setUp(self):
# Create a temporary directory.
f = tempfile.mktemp()
@@ -600,5 +603,39 @@ def testRmtreeP(self):
self.fail("Calling `rmtree_p` on non-existent directory "
"should not raise an exception.")
+class TempDirTestCase(unittest.TestCase):
+ def test_constructor(self):
+ """
+ One should be able to readily construct a temporary directory
+ """
+ d = tempdir()
+ assert isinstance(d, path)
+ assert d.exists()
+ assert d.isdir()
+ d.rmdir()
+ assert not d.exists()
+
+ def test_context_manager(self):
+ """
+ One should be able to use a tempdir object as a context, which will
+ clean up the contents after.
+ """
+ d = tempdir()
+ res = d.__enter__()
+ assert res is d
+ (d / 'somefile.txt').touch()
+ d.__exit__(None, None, None)
+ assert not d.exists()
+
+ def test_context_manager_exception(self):
+ """
+ The context manager will not clean up if an exception occurs.
+ """
+ d = tempdir()
+ d.__enter__()
+ (d / 'somefile.txt').touch()
+ d.__exit__(TypeError, TypeError('foo'), None)
+ assert d.exists()
+
if __name__ == '__main__':
unittest.main()
Please sign in to comment.
Something went wrong with that request. Please try again.