def wrapper(self, *args, **kwargs): path = Path(_maketemp(prefix=func.__name__)) path.mkdir() keep = False prev_val = os.environ.get('RW_DIR') os.environ['RW_DIR'] = str(path) prev_cwd = os.getcwd() os.chdir(path) try: try: return func(self, path, *args, **kwargs) except Exception as err: print(("Test %s.%s failed with error %s: '%s', output is at %r" % (type(self).__name__, type(err), err, func.__name__, path)), file=sys.stderr) keep = True raise # end be informed about failure finally: if prev_val is not None: os.environ['RW_DIR'] = prev_val # end restore state os.chdir(prev_cwd) # Need to collect here to be sure all handles have been closed. It appears # a windows-only issue. In fact things should be deleted, as well as # memory maps closed, once objects go out of scope. For some reason # though this is not the case here unless we collect explicitly. if not keep: gc.collect() shutil.rmtree(path)