source: rtems-tools/tester/rt/coverage.py @ 5195eb7

5
Last change on this file since 5195eb7 was 5195eb7, checked in by Chris Johns <chrisj@…>, on 06/17/18 at 23:36:38

tester: Clean up the coverage python code.

  • Property mode set to 100644
File size: 15.7 KB
Line 
1#
2# RTEMS Tools Project (http://www.rtems.org/)
3# Copyright 2014 Krzysztof Miesowicz (krzysztof.miesowicz@gmail.com)
4# All rights reserved.
5#
6# This file is part of the RTEMS Tools package in 'rtems-tools'.
7#
8# Redistribution and use in source and binary forms, with or without
9# modification, are permitted provided that the following conditions are met:
10#
11# 1. Redistributions of source code must retain the above copyright notice,
12# this list of conditions and the following disclaimer.
13#
14# 2. Redistributions in binary form must reproduce the above copyright notice,
15# this list of conditions and the following disclaimer in the documentation
16# and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29#
30
31from __future__ import print_function
32
33import datetime
34import shutil
35import os
36
37try:
38    import configparser
39except:
40    import ConfigParser as configparser
41
42from rtemstoolkit import error
43from rtemstoolkit import path
44from rtemstoolkit import log
45from rtemstoolkit import execute
46from rtemstoolkit import macros
47
48
49from . import options
50
51class summary:
52    def __init__(self, p_summary_dir):
53        self.summary_file_path = path.join(p_summary_dir, 'summary.txt')
54        self.index_file_path = path.join(p_summary_dir, 'index.html')
55        self.bytes_analyzed = 0
56        self.bytes_not_executed = 0
57        self.percentage_executed = 0.0
58        self.percentage_not_executed = 100.0
59        self.ranges_uncovered = 0
60        self.branches_uncovered = 0
61        self.branches_total = 0
62        self.branches_always_taken = 0
63        self.branches_never_taken = 0
64        self.percentage_branches_covered = 0.0
65        self.is_failure = False
66
67    def parse(self):
68        if not path.exists(self.summary_file_path):
69            log.output('coverage: summary file %s does not exist!' % (self.summary_file_path))
70            self.is_failure = True
71
72        with open(self.summary_file_path, 'r') as summary_file:
73           self.bytes_analyzed = self._get_next_with_colon(summary_file)
74           self.bytes_not_executed = self._get_next_with_colon(summary_file)
75           self.percentage_executed = self._get_next_with_colon(summary_file)
76           self.percentage_not_executed = self._get_next_with_colon(summary_file)
77           self.ranges_uncovered = self._get_next_with_colon(summary_file)
78           self.branches_total = self._get_next_with_colon(summary_file)
79           self.branches_uncovered = self._get_next_with_colon(summary_file)
80           self.branches_always_taken = self._get_next_without_colon(summary_file)
81           self.branches_never_taken = self._get_next_without_colon(summary_file)
82        if len(self.branches_uncovered) > 0 and len(self.branches_total) > 0:
83            self.percentage_branches_covered = \
84                1.0 - (float(self.branches_uncovered) / float(self.branches_total))
85        else:
86            self.percentage_branches_covered = 0.0
87        return
88
89    def _get_next_with_colon(self, summary_file):
90        line = summary_file.readline()
91        if ':' in line:
92            return line.split(':')[1].strip()
93        else:
94            return ''
95
96    def _get_next_without_colon(self, summary_file):
97        line = summary_file.readline()
98        return line.strip().split(' ')[0]
99
100class report_gen_html:
101    def __init__(self, p_symbol_sets_list, build_dir, rtdir, bsp):
102        self.symbol_sets_list = ['score']
103        self.build_dir = build_dir
104        self.partial_reports_files = list(["index.html", "summary.txt"])
105        self.number_of_columns = 1
106        self.covoar_src_path = path.join(rtdir, 'covoar')
107        self.bsp = bsp
108
109    def _find_partial_reports(self):
110        partial_reports = {}
111        for symbol_set in self.symbol_sets_list:
112            set_summary = summary(path.join(self.build_dir,
113                                  self.bsp + "-coverage",
114                                  symbol_set))
115            set_summary.parse()
116            partial_reports[symbol_set] = set_summary
117        return partial_reports
118
119    def _prepare_head_section(self):
120        head_section = '''
121        <head>
122        <title>RTEMS coverage report</title>
123        <style type="text/css">
124            progress[value] {
125              -webkit-appearance: none;
126               appearance: none;
127
128              width: 150px;
129              height: 15px;
130            }
131        </style>
132        </head>'''
133        return head_section
134
135    def _prepare_index_content(self, partial_reports):
136        header = "<h1> RTEMS coverage analysis report </h1>"
137        header += "<h3>Coverage reports by symbols sets:</h3>"
138        table = "<table>"
139        table += self._header_row()
140        for symbol_set in partial_reports:
141            table += self._row(symbol_set, partial_reports[symbol_set])
142        table += "</table> </br>"
143        timestamp = "Analysis performed on " + datetime.datetime.now().ctime()
144        return "<body>\n" + header + table + timestamp + "\n</body>"
145
146    def _row(self, symbol_set, summary):
147        row = "<tr>"
148        row += "<td>" + symbol_set + "</td>"
149        if summary.is_failure:
150            row += ' <td colspan="' + str(self.number_of_columns-1) \
151            + '" style="background-color:red">FAILURE</td>'
152        else:
153            row += " <td>" + self._link(summary.index_file_path,"Index") \
154            + "</td>"
155            row += " <td>" + self._link(summary.summary_file_path,"Summary") \
156            + "</td>"
157            row += " <td>" + summary.bytes_analyzed + "</td>"
158            row += " <td>" + summary.bytes_not_executed + "</td>"
159            row += " <td>" + summary.ranges_uncovered + "</td>"
160            row += " <td>" + summary.percentage_executed + "%</td>"
161            row += " <td>" + summary.percentage_not_executed + "%</td>"
162            row += ' <td><progress value="' + summary.percentage_executed \
163            + '" max="100"></progress></td>'
164            row += " <td>" + summary.branches_uncovered + "</td>"
165            row += " <td>" + summary.branches_total + "</td>"
166            row += " <td> {:.3%} </td>".format(summary.percentage_branches_covered)
167            spbc = 100 * summary.percentage_branches_covered
168            row += ' <td><progress value="{:.3}" max="100"></progress></td>'.format(spbc)
169            row += "</tr>\n"
170        return row
171
172    def _header_row(self):
173        row = "<tr>"
174        row += "<th> Symbols set name </th>"
175        row += "<th> Index file </th>"
176        row += "<th> Summary file </th>"
177        row += "<th> Bytes analyzed </th>"
178        row += "<th> Bytes not executed </th>"
179        row += "<th> Uncovered ranges </th>"
180        row += "<th> Percentage covered </th>"
181        row += "<th> Percentage uncovered </th>"
182        row += "<th> Instruction coverage </th>"
183        row += "<th> Branches uncovered </th>"
184        row += "<th> Branches total </th>"
185        row += "<th> Branches covered percentage </th>"
186        row += "<th> Branches coverage </th>"
187        row += "</tr>\n"
188        self.number_of_columns = row.count('<th>')
189        return row
190
191    def _link(self, address, text):
192        return '<a href="' + address + '">' + text + '</a>'
193
194    def _create_index_file(self, head_section, content):
195        name = path.join(self.build_dir, self.bsp + "-report.html")
196        with open(name, 'w') as f:
197            f.write(head_section)
198            f.write(content)
199
200    def generate(self):
201        partial_reports = self._find_partial_reports()
202        head_section = self._prepare_head_section()
203        index_content = self._prepare_index_content(partial_reports)
204        self._create_index_file(head_section,index_content)
205
206    def add_covoar_src_path(self):
207        table_js_path = path.join(self.covoar_src_path, 'table.js')
208        covoar_css_path = path.join(self.covoar_src_path, 'covoar.css')
209        for symbol_set in self.symbol_sets_list:
210            symbol_set_dir = path.join(self.build_dir,
211                                       self.bsp + '-coverage', symbol_set)
212            html_files = os.listdir(symbol_set_dir)
213            for html_file in html_files:
214                html_file = path.join(symbol_set_dir, html_file)
215                if path.exists(html_file) and 'html' in html_file:
216                    with open(html_file, 'r') as f:
217                        file_data = f.read()
218                    file_data = file_data.replace('table.js', table_js_path)
219                    file_data = file_data.replace('covoar.css',
220                                                  covoar_css_path)
221                    with open(html_file, 'w') as f:
222                        f.write(file_data)
223
224class build_path_generator(object):
225    '''
226    Generates the build path from the path to executables
227    '''
228    def __init__(self, executables, target):
229        self.executables = executables
230        self.target = target
231    def run(self):
232        build_path = '/'
233        path_ = self.executables[0].split('/')
234        for p in path_:
235            if p == self.target:
236                break
237            else:
238                build_path = path.join(build_path, p)
239        return build_path
240
241class symbol_parser(object):
242    '''
243    Parse the symbol sets ini and create custom ini file for covoar
244    '''
245    def __init__(self,
246                 symbol_config_path,
247                 symbol_select_path,
248                 coverage_arg,
249                 build_dir):
250        self.symbol_select_file = symbol_select_path
251        self.symbol_file = symbol_config_path
252        self.build_dir = build_dir
253        self.symbol_sets = {}
254        self.cov_arg = coverage_arg
255        self.ssets = []
256
257    def parse(self):
258        config = configparser.ConfigParser()
259        try:
260            config.read(self.symbol_file)
261            if self.cov_arg:
262                self.ssets = self.cov_arg.split(',')
263            else:
264                self.ssets = config.get('symbol-sets', 'sets').split(',')
265                self.ssets = [sset.encode('utf-8') for sset in self.ssets]
266            for sset in self.ssets:
267                lib = path.join(self.build_dir, config.get('libraries', sset))
268                self.symbol_sets[sset] = lib.encode('utf-8')
269        except:
270            raise error.general('Symbol set parsing failed')
271
272    def _write_ini(self):
273        config = configparser.ConfigParser()
274        try:
275            sets = ', '.join(self.symbol_sets.keys())
276            config.add_section('symbol-sets')
277            config.set('symbol-sets', 'sets', sets)
278            for key in self.symbol_sets.keys():
279                config.add_section(key)
280                config.set(key, 'libraries', self.symbol_sets[key])
281            with open(self.symbol_select_file, 'w') as conf:
282                config.write(conf)
283        except:
284            raise error.general('symbol parser write failed')
285
286    def run(self):
287        self.parse()
288        self._write_ini()
289
290class covoar(object):
291    '''
292    Covoar runner
293    '''
294    def __init__(self, base_result_dir, config_dir, executables, explanations_txt):
295        self.base_result_dir = base_result_dir
296        self.config_dir = config_dir
297        self.executables = ' '.join(executables)
298        self.explanations_txt = explanations_txt
299        self.project_name = 'RTEMS-5'
300
301    def run(self, set_name, symbol_file):
302        covoar_result_dir = path.join(self.base_result_dir, set_name)
303        if (not path.exists(covoar_result_dir)):
304            path.mkdir(covoar_result_dir)
305        if (not path.exists(symbol_file)):
306            raise error.general('symbol set file: coverage %s not created, skipping %s'% (symbol_file, set_name))
307        command = 'covoar -S ' + symbol_file + \
308                  ' -O ' + covoar_result_dir + \
309                  ' -E ' + self.explanations_txt + \
310                  ' -p ' + self.project_name + ' ' + self.executables
311        log.notice()
312        log.notice('Running coverage analysis: %s (%s)' % (set_name, covoar_result_dir))
313        start_time = datetime.datetime.now()
314        executor = execute.execute(verbose = True, output = self.output_handler)
315        exit_code = executor.shell(command, cwd=os.getcwd())
316        if exit_code[0] != 0:
317            raise error.general('coverage: covoar failure:: %d' % (exit_code[0]))
318        end_time = datetime.datetime.now()
319        log.notice('Coverage time: %s' % (str(end_time - start_time)))
320
321    def output_handler(self, text):
322        log.output('%s' % (text))
323
324class coverage_run(object):
325    '''
326    Coverage analysis support for rtems-test
327    '''
328    def __init__(self, p_macros, coverage_arg, executables):
329        '''
330        Constructor
331        '''
332        self.macros = p_macros
333        self.build_dir = self.macros['_cwd']
334        self.explanations_txt = self.macros.expand(self.macros['cov_explanations'])
335        self.test_dir = path.join(self.build_dir, self.macros['bsp'] + '-coverage')
336        if not path.exists(self.test_dir):
337            path.mkdir(self.test_dir)
338        self.rtdir = path.abspath(self.macros['_rtdir'])
339        self.rtscripts = self.macros.expand(self.macros['_rtscripts'])
340        self.coverage_config_path = path.join(self.rtscripts, 'coverage')
341        self.symbol_config_path = path.join(self.coverage_config_path,
342                                            'symbol-sets.ini')
343        self.symbol_select_path = path.join(self.coverage_config_path,
344                                            self.macros['bsp'] + '-symbols.ini')
345        self.executables = executables
346        self.symbol_sets = []
347        self.no_clean = int(self.macros['_no_clean'])
348        self.report_format = self.macros['cov_report_format']
349        self.coverage_arg = coverage_arg
350        self.target = self.macros['target']
351
352    def run(self):
353        try:
354            if self.executables is None:
355                raise error.general('no test executables provided.')
356            build_dir = build_path_generator(self.executables, self.target).run()
357            parser = symbol_parser(self.symbol_config_path,
358                                   self.symbol_select_path,
359                                   self.coverage_arg,
360                                   build_dir)
361            parser.run()
362            covoar_runner = covoar(self.test_dir, self.symbol_select_path,
363                                   self.executables, self.explanations_txt)
364            covoar_runner.run('score', self.symbol_select_path)
365            self._generate_reports();
366            self._summarize();
367        finally:
368            self._cleanup();
369
370    def _generate_reports(self):
371        log.notice('Coverage generating reports')
372        if self.report_format == 'html':
373            report = report_gen_html(self.symbol_sets,
374                                     self.build_dir,
375                                     self.rtdir,
376                                     self.macros['bsp'])
377            report.generate()
378            report.add_covoar_src_path()
379
380    def _cleanup(self):
381        if not self.no_clean:
382            log.output('Coverage cleaning tempfiles')
383            for exe in self.executables:
384                trace_file = exe + '.cov'
385                if path.exists(trace_file):
386                    os.remove(trace_file)
387            os.remove(self.symbol_select_path)
388
389    def _summarize(self):
390        log.notice('Coverage analysis finished: %s' % (self.build_dir))
Note: See TracBrowser for help on using the repository browser.