[Piglit] [PATCH] backends/json.py: Use an object_hook function for loading.

Dylan Baker baker.dylan.c at gmail.com
Fri Apr 10 13:59:40 PDT 2015


This simplifies loading, removing the need to iterate over items in the
json again, since the conversion is done during the parsing pass.
---

This adds more code, but most of the new code is unit tests, without the
tests this would result in negative lines of code.

 framework/backends/json.py            | 20 +++++++++-----------
 framework/tests/json_backend_tests.py |  7 +++++++
 2 files changed, 16 insertions(+), 11 deletions(-)

diff --git a/framework/backends/json.py b/framework/backends/json.py
index affd64e..2034ecd 100644
--- a/framework/backends/json.py
+++ b/framework/backends/json.py
@@ -61,6 +61,13 @@ def piglit_encoder(obj):
     return obj
 
 
+def piglit_decoder(obj):
+    """Json decoder for piglit that can load TestResult objects."""
+    if isinstance(obj, dict) and 'result' in obj:
+        return results.TestResult.load(obj)
+    return obj
+
+
 class JSONBackend(FileBackend):
     """ Piglit's native JSON backend
 
@@ -208,10 +215,7 @@ def _load(results_file):
     """
     result = results.TestrunResult()
     result.results_vesrion = 0  # This should get overwritten
-    result.__dict__.update(json.load(results_file))
-
-    for key, value in result.tests.viewitems():
-        result.tests[key] = results.TestResult.load(value)
+    result.__dict__.update(json.load(results_file, object_hook=piglit_decoder))
 
     return result
 
@@ -240,16 +244,10 @@ def _resume(results_dir):
     for file_ in os.listdir(os.path.join(results_dir, 'tests')):
         with open(os.path.join(results_dir, 'tests', file_), 'r') as f:
             try:
-                test = json.load(f)
+                testrun.tests.update(json.load(f, object_hook=piglit_decoder))
             except ValueError:
                 continue
 
-        # XXX: There has to be a better way to get a single key: value out
-        # of a dict even when the key name isn't known
-        # XXX: Yes, using a piglit_decoder function
-        for key, value in test.iteritems():
-            testrun.tests[key] = results.TestResult.load(value)
-
     return testrun
 
 
diff --git a/framework/tests/json_backend_tests.py b/framework/tests/json_backend_tests.py
index 45626e8..6c0ee6b 100644
--- a/framework/tests/json_backend_tests.py
+++ b/framework/tests/json_backend_tests.py
@@ -286,3 +286,10 @@ def test_load_json():
 
     nt.assert_is_instance(result, results.TestrunResult)
     nt.assert_in('sometest', result.tests)
+
+
+def test_piglit_decoder():
+    """backends.json.piglit_decoder: Works correctly"""
+    test = json.loads('{"foo": {"result": "pass"}}',
+                      object_hook=backends.json.piglit_decoder)
+    nt.assert_is_instance(test['foo'], results.TestResult)
-- 
2.3.5



More information about the Piglit mailing list