[Piglit] [PATCH 1/4] unittests/utils.py: Don't leave a bunch of temp files around

Dylan Baker baker.dylan.c at gmail.com
Wed Apr 6 22:46:43 UTC 2016


Currently unit tests leave a bunch of temporary files and directories
around. This is due to the fact that functions implemented using
contextlib.contextmanager don't automatically handle exceptions like
context managers implemented as by classes do. Using try/finally solves
the problem.

There are a couple of temporary directories still left behind, but those
are a different problem to be handled by a different patch.

Signed-off-by: Dylan Baker <dylanx.c.baker at intel.com>
---
 unittests/utils.py | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)

diff --git a/unittests/utils.py b/unittests/utils.py
index 178d24b..089f479 100644
--- a/unittests/utils.py
+++ b/unittests/utils.py
@@ -260,9 +260,10 @@ def resultfile():
     with tempfile_.NamedTemporaryFile(mode=_WRITE_MODE, delete=False) as f:
         json.dump(data, f, default=backends.json.piglit_encoder)
 
-    yield f
-
-    os.remove(f.name)
+    try:
+        yield f
+    finally:
+        os.remove(f.name)
 
 
 @contextmanager
@@ -283,17 +284,20 @@ def tempfile(contents):
     temp.write(contents)
     temp.close()
 
-    yield temp.name
-
-    os.remove(temp.name)
+    try:
+        yield temp.name
+    finally:
+        os.remove(temp.name)
 
 
 @contextmanager
 def tempdir():
     """ Creates a temporary directory, returns it, and then deletes it """
     tdir = tempfile_.mkdtemp()
-    yield tdir
-    shutil.rmtree(tdir)
+    try:
+        yield tdir
+    finally:
+        shutil.rmtree(tdir)
 
 
 def nose_generator(func):
-- 
2.8.0



More information about the Piglit mailing list