Permalink
Browse files

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

…dir() / 'foo' tries to construct another tempdir instance.
  • Loading branch information...
jaraco committed Jan 15, 2013
1 parent fc339bc commit bf82b390a3df6d77370f9470816a93760ca3ca28
Showing with 60 additions and 2 deletions.
  1. +21 −0 path.py
  2. +39 −2 test_path.py
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()
@@ -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()

0 comments on commit bf82b39

Please sign in to comment.