1# Copyright 2014 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5import json 6 7from telemetry.internal.results import output_formatter 8 9 10def ResultsAsDict(page_test_results, benchmark_metadata): 11 """Takes PageTestResults to a dict serializable to JSON. 12 13 To serialize results as JSON we first convert them to a dict that can be 14 serialized by the json module. It also requires a benchmark_metadat object 15 for metadata to be integrated into the results (currently the benchmark 16 name). This function will also output trace files if they exist. 17 18 Args: 19 page_test_results: a PageTestResults object 20 benchmark_metadata: a benchmark.BenchmarkMetadata object 21 """ 22 result_dict = { 23 'format_version': '0.2', 24 'next_version': '0.3', 25 # TODO(sullivan): benchmark_name should be removed when updating 26 # format_version to 0.3. 27 'benchmark_name': benchmark_metadata.name, 28 'benchmark_metadata': benchmark_metadata.AsDict(), 29 'summary_values': [v.AsDict() for v in 30 page_test_results.all_summary_values], 31 'per_page_values': [v.AsDict() for v in 32 page_test_results.all_page_specific_values], 33 'pages': {p.id: p.AsDict() for p in _GetAllPages(page_test_results)} 34 } 35 if page_test_results.serialized_trace_file_ids_to_paths: 36 result_dict['files'] = page_test_results.serialized_trace_file_ids_to_paths 37 return result_dict 38 39 40def _GetAllPages(page_test_results): 41 pages = set(page_run.story for page_run in 42 page_test_results.all_page_runs) 43 return pages 44 45 46class JsonOutputFormatter(output_formatter.OutputFormatter): 47 def __init__(self, output_stream, benchmark_metadata): 48 super(JsonOutputFormatter, self).__init__(output_stream) 49 self._benchmark_metadata = benchmark_metadata 50 51 @property 52 def benchmark_metadata(self): 53 return self._benchmark_metadata 54 55 def Format(self, page_test_results): 56 json.dump( 57 ResultsAsDict(page_test_results, self.benchmark_metadata), 58 self.output_stream, indent=2) 59 self.output_stream.write('\n') 60