Index: Lib/test/test_support.py =================================================================== --- Lib/test/test_support.py (revision 77513) +++ Lib/test/test_support.py (working copy) @@ -612,6 +612,29 @@ sys.path[:] = self.original_value +class TempCWD(object): + """Context manager to temporarily create a directory and set it as CWD. + + Example: + with TempCWD('foo'): + assertEqual(os.path.basename(os.getcwd()), 'foo') + """ + + def __init__(self, dirname='tempcwd'): + self.dirname = os.path.join(TESTFN+'_cwd', dirname) + self._oldcwd = os.getcwd() + + def __enter__(self): + if not os.path.exists(self.dirname): + os.makedirs(self.dirname) + os.chdir(self.dirname) + return self.dirname + + def __exit__(self, exc, value, tb): + os.chdir(self._oldcwd) + rmtree(os.path.dirname(self.dirname)) + + class TransientResource(object): """Raise ResourceDenied if an exception is raised while the context manager