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 csv 6 7from telemetry.internal.results import output_formatter 8from telemetry.value import scalar 9 10 11class CsvPivotTableOutputFormatter(output_formatter.OutputFormatter): 12 """Output the results as CSV suitable for reading into a spreadsheet. 13 14 This will write a header row, and one row for each value. Each value row 15 contains the value and unit, identifies the value (story_set, page, name), and 16 (optionally) data from --output-trace-tag. This format matches what 17 spreadsheet programs expect as input for a "pivot table". 18 19 A trace tag (--output-trace-tag) can be used to tag each value, to allow 20 easy combination of the resulting CSVs from several runs. 21 If the trace_tag contains a comma, it will be written as several 22 comma-separated values. 23 24 This class only processes scalar values. 25 """ 26 27 FIELDS = ['story_set', 'page', 'name', 'value', 'units', 'run_index'] 28 29 def __init__(self, output_stream, trace_tag=''): 30 super(CsvPivotTableOutputFormatter, self).__init__(output_stream) 31 self._trace_tag = trace_tag 32 33 def Format(self, page_test_results): 34 csv_writer = csv.writer(self.output_stream) 35 36 # Observe trace_tag. Use comma to split up the trace tag. 37 tag_values = self._trace_tag.split(',') 38 tag_values = [x for x in tag_values if x] # filter empty list entries 39 tag_headers = ['trace_tag_%d' % i for i in range(len(tag_values))] 40 41 # Write header. 42 csv_writer.writerow(self.FIELDS + tag_headers) 43 44 # Write all values. Each row contains a value + page-level metadata. 45 for run in page_test_results.all_page_runs: 46 run_index = page_test_results.all_page_runs.index(run) 47 page_dict = { 48 'page': run.story.display_name, 49 'story_set': run.story.page_set.Name(), 50 'run_index': run_index, 51 } 52 for value in run.values: 53 if isinstance(value, scalar.ScalarValue): 54 value_dict = { 55 'name': value.name, 56 'value': value.value, 57 'units': value.units, 58 } 59 value_dict.update(page_dict.items()) 60 csv_writer.writerow( 61 [value_dict[field] for field in self.FIELDS] + tag_values) 62