1 // Copyright 2015 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.testing.local; 6 7 import org.json.JSONArray; 8 import org.json.JSONException; 9 import org.json.JSONObject; 10 import org.junit.runner.Description; 11 12 import java.io.File; 13 import java.io.FileNotFoundException; 14 import java.io.FileOutputStream; 15 import java.io.PrintStream; 16 17 /** 18 * Creates json file with junit test information. Format of the json file mirrors the 19 * json generated by build/android/pylib/results/json_results.py. 20 */ 21 public class JsonLogger { 22 23 private final JSONObject mBaseJsonObject; 24 private final JSONObject mBaseTestInfoJsonObject; 25 private final File mOutputFile; 26 JsonLogger(File outputFile)27 public JsonLogger(File outputFile) { 28 mBaseJsonObject = new JSONObject(); 29 mBaseTestInfoJsonObject = new JSONObject(); 30 mOutputFile = outputFile; 31 32 try { 33 mBaseJsonObject.put("global_tags", new JSONArray()); 34 mBaseJsonObject.put("all_tests", new JSONArray()); 35 mBaseJsonObject.put("disabled_tests", new JSONArray()); 36 mBaseJsonObject.put("per_iteration_data", new JSONArray().put(mBaseTestInfoJsonObject)); 37 } catch (JSONException e) { 38 System.err.println("Unable to create json output."); 39 } 40 } 41 42 /** Add the results of a test run to the json output. */ addTestResultInfo(Description test, boolean passed, long elapsedTimeMillis)43 public void addTestResultInfo(Description test, boolean passed, long elapsedTimeMillis) { 44 JSONObject testInfoJsonObject = new JSONObject(); 45 46 try { 47 testInfoJsonObject.put("status", (passed ? "SUCCESS" : "FAILURE")); 48 testInfoJsonObject.put("elapsed_time_ms", elapsedTimeMillis); 49 testInfoJsonObject.put("output_snippet", ""); 50 testInfoJsonObject.put("output_snippet_base64", ""); 51 testInfoJsonObject.put("losless_snippet", ""); 52 53 if (mBaseTestInfoJsonObject.optJSONArray(testName(test)) == null) { 54 mBaseTestInfoJsonObject.put(testName(test), new JSONArray()); 55 mBaseJsonObject.getJSONArray("all_tests").put(testName(test)); 56 } 57 mBaseTestInfoJsonObject.getJSONArray(testName(test)).put(testInfoJsonObject); 58 } catch (JSONException e) { 59 System.err.println("Unable to log test to json output: " + testName(test)); 60 } 61 } 62 63 /** Writes the json output to a file. */ writeJsonToFile()64 public void writeJsonToFile() throws FileNotFoundException { 65 try (PrintStream stream = new PrintStream(new FileOutputStream(mOutputFile))) { 66 stream.print(mBaseJsonObject); 67 } 68 } 69 testName(Description test)70 private String testName(Description test) { 71 return test.getClassName() + "#" + test.getMethodName(); 72 } 73 } 74