Skip to content

Commit

Permalink
First stab at temp_dir context manager.
Browse files Browse the repository at this point in the history
  • Loading branch information
themattrix committed Jan 20, 2015
1 parent b31f8fb commit 5a7bdd8
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Temporary |Version| |Build| |Coverage| |Health|
===================================================================
===============================================

|Compatibility| |Implementations| |Format| |Downloads|

Expand Down
1 change: 1 addition & 0 deletions requirements_install.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
contextlib2
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
license='MIT',
author='Matthew Tardiff',
author_email='mattrix@gmail.com',
install_requires=(),
install_requires=(
'contextlib2',),
tests_require=(
'nose',
'flake8',
Expand Down
4 changes: 4 additions & 0 deletions temporary/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from temporary.directory import temp_dir

# silence PyFlakes
assert temp_dir
18 changes: 18 additions & 0 deletions temporary/directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from contextlib2 import contextmanager
from os import chdir, getcwd
from shutil import rmtree
from tempfile import mkdtemp


@contextmanager
def temp_dir(suffix='', prefix='tmp', parent_dir=None, make_cwd=False):
prev_cwd = getcwd()
abs_path = mkdtemp(suffix, prefix, parent_dir)
try:
if make_cwd:
chdir(abs_path)
yield abs_path
finally:
if make_cwd:
chdir(prev_cwd)
rmtree(abs_path)
33 changes: 33 additions & 0 deletions temporary/test/test_directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from os.path import exists, isdir
from nose.tools import eq_
from temporary import temp_dir


#
# Tests
#

def test_temp_dir():
for x in __ensure_usage():
yield x


#
# Test Helpers
#

def __ensure_usage(**kwargs):
def ensure_context_manager():
with temp_dir(**kwargs) as d:
eq_(isdir(d), True)
eq_(exists(d), False)

def ensure_decorator():
@temp_dir(**kwargs)
def inner():
pass

inner()

yield ensure_context_manager
yield ensure_decorator

0 comments on commit 5a7bdd8

Please sign in to comment.