Created
January 9, 2014 22:09
-
-
Save cameronp98/8343012 to your computer and use it in GitHub Desktop.
Random crap w/ contextlib.contextmanager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
from shutil import rmtree | |
from tempfile import mkdtemp | |
import unittest | |
import os | |
@contextmanager | |
def working_directory(path): | |
current_dir = os.getcwd() | |
os.chdir(path) | |
try: | |
yield path | |
finally: | |
os.chdir(current_dir) | |
@contextmanager | |
def temporary_dir(*args, **kwargs): | |
name = mkdtemp(*args, **kwargs) | |
try: | |
yield name | |
finally: | |
rmtree(name) | |
class TestWorkingDirectoryCM(unittest.TestCase): | |
def setUp(self): | |
self.start_dir = os.getcwd() | |
self.target_dir = os.path.normpath("c:/") | |
def test_directory_changes(self): | |
with working_directory(self.target_dir): | |
self.assertNotEqual(os.getcwd(), self.start_dir) | |
def test_directory_changes_to_target(self): | |
with working_directory(self.target_dir): | |
self.assertEqual(os.getcwd(), self.target_dir) | |
def test_cm_yields_correct_path(self): | |
with working_directory(self.target_dir) as path: | |
self.assertEqual(os.getcwd(), path) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment