OLD | NEW |
| (Empty) |
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 | |
5 from cStringIO import StringIO | |
6 | |
7 import coverage | |
8 | |
9 # This is instead of a contextmanager because it causes old pylints to crash :( | |
10 class _Cover(object): | |
11 def __init__(self, enabled, maybe_kwargs): | |
12 self.enabled = enabled | |
13 self.kwargs = maybe_kwargs or {} | |
14 self.c = None | |
15 | |
16 def __call__(self, **kwargs): | |
17 new_kwargs = self.kwargs | |
18 if self.enabled: | |
19 new_kwargs = new_kwargs.copy() | |
20 new_kwargs.update(kwargs) | |
21 return _Cover(self.enabled, new_kwargs) | |
22 | |
23 def __enter__(self): | |
24 if self.enabled: | |
25 if self.c is None: | |
26 self.c = coverage.coverage(**self.kwargs) | |
27 self.c._warn_no_data = False # pylint: disable=protected-access | |
28 self.c.start() | |
29 | |
30 def __exit__(self, *_): | |
31 if self.enabled: | |
32 self.c.stop() | |
33 self.c.save() | |
34 | |
35 | |
36 class CoverageContext(object): | |
37 def __init__(self, name, cover_branches, html_report, enabled=True): | |
38 self.opts = None | |
39 self.cov = None | |
40 self.enabled = enabled | |
41 | |
42 self.html_report = html_report | |
43 | |
44 if enabled: | |
45 self.opts = { | |
46 'data_file': '.%s_coverage' % name, | |
47 'data_suffix': True, | |
48 'branch': cover_branches, | |
49 } | |
50 self.cov = coverage.coverage(**self.opts) | |
51 self.cov.erase() | |
52 | |
53 def cleanup(self): | |
54 if self.enabled: | |
55 self.cov.combine() | |
56 | |
57 def report(self, verbose, omit=None): | |
58 fail = False | |
59 | |
60 if self.enabled: | |
61 if self.html_report: | |
62 self.cov.html_report(directory=self.html_report, omit=None) | |
63 | |
64 outf = StringIO() | |
65 fail = self.cov.report(file=outf, omit=omit) != 100.0 | |
66 summary = outf.getvalue().replace('%- 15s' % 'Name', 'Coverage Report', 1) | |
67 if verbose: | |
68 print | |
69 print summary | |
70 elif fail: | |
71 print | |
72 lines = summary.splitlines() | |
73 lines[2:-2] = [l for l in lines[2:-2] | |
74 if not l.strip().endswith('100%')] | |
75 print '\n'.join(lines) | |
76 print | |
77 print 'FATAL: Test coverage is not at 100%.' | |
78 | |
79 return not fail | |
80 | |
81 def create_subprocess_context(self): | |
82 # Can't have this method be the contextmanager because otherwise | |
83 # self (and self.cov) will get pickled to the subprocess, and we don't want | |
84 # that :( | |
85 return _Cover(self.enabled, self.opts) | |
OLD | NEW |