blob: 507c5c79de49203498af8f535dafb7d163f70071 [file] [log] [blame]
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -08001#!/usr/bin/python2.4
2#
3#
4# Copyright 2008, The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Utilities for generating code coverage reports for Android tests."""
19
20# Python imports
21import glob
22import optparse
23import os
24
25# local imports
26import android_build
27import coverage_targets
28import errors
29import logger
30import run_command
31
32
33class CoverageGenerator(object):
34 """Helper utility for obtaining code coverage results on Android.
35
36 Intended to simplify the process of building,running, and generating code
37 coverage results for a pre-defined set of tests and targets
38 """
39
40 # environment variable to enable emma builds in Android build system
41 _EMMA_BUILD_FLAG = "EMMA_INSTRUMENT"
42 # build path to Emma target Makefile
43 _EMMA_BUILD_PATH = os.path.join("external", "emma")
44 # path to EMMA host jar, relative to Android build root
45 _EMMA_JAR = os.path.join(_EMMA_BUILD_PATH, "lib", "emma.jar")
46 _TEST_COVERAGE_EXT = "ec"
47 # default device-side path to code coverage results file
48 _DEVICE_COVERAGE_PATH = "/sdcard/coverage.ec"
49 # root path of generated coverage report files, relative to Android build root
50 _COVERAGE_REPORT_PATH = os.path.join("out", "emma")
51 _CORE_TARGET_PATH = os.path.join("development", "testrunner",
52 "coverage_targets.xml")
53 # vendor glob file path patterns to tests, relative to android
54 # build root
55 _VENDOR_TARGET_PATH = os.path.join("vendor", "*", "tests", "testinfo",
56 "coverage_targets.xml")
57
58 # path to root of target build intermediates
59 _TARGET_INTERMEDIATES_BASE_PATH = os.path.join("out", "target", "common",
60 "obj")
61
62 def __init__(self, android_root_path, adb_interface):
63 self._root_path = android_root_path
64 self._output_root_path = os.path.join(self._root_path,
65 self._COVERAGE_REPORT_PATH)
66 self._emma_jar_path = os.path.join(self._root_path, self._EMMA_JAR)
67 self._adb = adb_interface
68 self._targets_manifest = self._ReadTargets()
69
70 def EnableCoverageBuild(self):
71 """Enable building an Android target with code coverage instrumentation."""
72 os.environ[self._EMMA_BUILD_FLAG] = "true"
73
74 def ExtractReport(self, test_suite,
75 device_coverage_path=_DEVICE_COVERAGE_PATH,
76 output_path=None):
77 """Extract runtime coverage data and generate code coverage report.
78
79 Assumes test has just been executed.
80 Args:
81 test_suite: TestSuite to generate coverage data for
82 device_coverage_path: location of coverage file on device
83 output_path: path to place output files in. If None will use
84 <android_root_path>/<_COVERAGE_REPORT_PATH>/<target>/<test>
85
86 Returns:
87 absolute file path string of generated html report file.
88 """
89 if output_path is None:
90 output_path = os.path.join(self._root_path,
91 self._COVERAGE_REPORT_PATH,
92 test_suite.GetTargetName(),
93 test_suite.GetName())
94
95 coverage_local_name = "%s.%s" % (test_suite.GetName(),
96 self._TEST_COVERAGE_EXT)
97 coverage_local_path = os.path.join(output_path,
98 coverage_local_name)
99 if self._adb.Pull(device_coverage_path, coverage_local_path):
100
101 report_path = os.path.join(output_path,
102 test_suite.GetName())
103 target = self._targets_manifest.GetTarget(test_suite.GetTargetName())
104 return self._GenerateReport(report_path, coverage_local_path, [target],
105 do_src=True)
106 return None
107
108 def _GenerateReport(self, report_path, coverage_file_path, targets,
109 do_src=True):
110 """Generate the code coverage report.
111
112 Args:
113 report_path: absolute file path of output file, without extension
114 coverage_file_path: absolute file path of code coverage result file
115 targets: list of CoverageTargets to use as base for code coverage
116 measurement.
117 do_src: True if generate coverage report with source linked in.
118 Note this will increase size of generated report.
119
120 Returns:
121 absolute file path to generated report file.
122 """
123 input_metadatas = self._GatherMetadatas(targets)
124
125 if do_src:
126 src_arg = self._GatherSrcs(targets)
127 else:
128 src_arg = ""
129
130 report_file = "%s.html" % report_path
131 cmd1 = ("java -cp %s emma report -r html -in %s %s %s " %
132 (self._emma_jar_path, coverage_file_path, input_metadatas, src_arg))
133 cmd2 = "-Dreport.html.out.file=%s" % report_file
134 self._RunCmd(cmd1 + cmd2)
135 return report_file
136
137 def _GatherMetadatas(self, targets):
138 """Builds the emma input metadata argument from provided targets.
139
140 Args:
141 targets: list of CoverageTargets
142
143 Returns:
144 input metadata argument string
145 """
146 input_metadatas = ""
147 for target in targets:
148 input_metadata = os.path.join(self._GetBuildIntermediatePath(target),
149 "coverage.em")
150 input_metadatas += " -in %s" % input_metadata
151 return input_metadatas
152
153 def _GetBuildIntermediatePath(self, target):
154 return os.path.join(
155 self._root_path, self._TARGET_INTERMEDIATES_BASE_PATH, target.GetType(),
156 "%s_intermediates" % target.GetName())
157
158 def _GatherSrcs(self, targets):
159 """Builds the emma input source path arguments from provided targets.
160
161 Args:
162 targets: list of CoverageTargets
163 Returns:
164 source path arguments string
165 """
166 src_list = []
167 for target in targets:
168 target_srcs = target.GetPaths()
169 for path in target_srcs:
170 src_list.append("-sp %s" % os.path.join(self._root_path, path))
171 return " ".join(src_list)
172
173 def _MergeFiles(self, input_paths, dest_path):
174 """Merges a set of emma coverage files into a consolidated file.
175
176 Args:
177 input_paths: list of string absolute coverage file paths to merge
178 dest_path: absolute file path of destination file
179 """
180 input_list = []
181 for input_path in input_paths:
182 input_list.append("-in %s" % input_path)
183 input_args = " ".join(input_list)
184 self._RunCmd("java -cp %s emma merge %s -out %s" % (self._emma_jar_path,
185 input_args, dest_path))
186
187 def _RunCmd(self, cmd):
188 """Runs and logs the given os command."""
189 run_command.RunCommand(cmd, return_output=False)
190
191 def _CombineTargetCoverage(self):
192 """Combines all target mode code coverage results.
193
194 Will find all code coverage data files in direct sub-directories of
195 self._output_root_path, and combine them into a single coverage report.
196 Generated report is placed at self._output_root_path/android.html
197 """
198 coverage_files = self._FindCoverageFiles(self._output_root_path)
199 combined_coverage = os.path.join(self._output_root_path,
200 "android.%s" % self._TEST_COVERAGE_EXT)
201 self._MergeFiles(coverage_files, combined_coverage)
202 report_path = os.path.join(self._output_root_path, "android")
203 # don't link to source, to limit file size
204 self._GenerateReport(report_path, combined_coverage,
205 self._targets_manifest.GetTargets(), do_src=False)
206
207 def _CombineTestCoverage(self):
208 """Consolidates code coverage results for all target result directories."""
209 target_dirs = os.listdir(self._output_root_path)
210 for target_name in target_dirs:
211 output_path = os.path.join(self._output_root_path, target_name)
212 target = self._targets_manifest.GetTarget(target_name)
213 if os.path.isdir(output_path) and target is not None:
214 coverage_files = self._FindCoverageFiles(output_path)
215 combined_coverage = os.path.join(output_path, "%s.%s" %
216 (target_name, self._TEST_COVERAGE_EXT))
217 self._MergeFiles(coverage_files, combined_coverage)
218 report_path = os.path.join(output_path, target_name)
219 self._GenerateReport(report_path, combined_coverage, [target])
220 else:
221 logger.Log("%s is not a valid target directory, skipping" % output_path)
222
223 def _FindCoverageFiles(self, root_path):
224 """Finds all files in <root_path>/*/*.<_TEST_COVERAGE_EXT>.
225
226 Args:
227 root_path: absolute file path string to search from
228 Returns:
229 list of absolute file path strings of coverage files
230 """
231 file_pattern = os.path.join(root_path, "*", "*.%s" %
232 self._TEST_COVERAGE_EXT)
233 coverage_files = glob.glob(file_pattern)
234 return coverage_files
235
236 def GetEmmaBuildPath(self):
237 return self._EMMA_BUILD_PATH
238
239 def _ReadTargets(self):
240 """Parses the set of coverage target data.
241
242 Returns:
243 a CoverageTargets object that contains set of parsed targets.
244 Raises:
245 AbortError if a fatal error occurred when parsing the target files.
246 """
247 core_target_path = os.path.join(self._root_path, self._CORE_TARGET_PATH)
248 try:
249 targets = coverage_targets.CoverageTargets()
250 targets.Parse(core_target_path)
251 vendor_targets_pattern = os.path.join(self._root_path,
252 self._VENDOR_TARGET_PATH)
253 target_file_paths = glob.glob(vendor_targets_pattern)
254 for target_file_path in target_file_paths:
255 targets.Parse(target_file_path)
256 return targets
257 except errors.ParseError:
258 raise errors.AbortError
259
260 def TidyOutput(self):
261 """Runs tidy on all generated html files.
262
263 This is needed to the html files can be displayed cleanly on a web server.
264 Assumes tidy is on current PATH.
265 """
266 logger.Log("Tidying output files")
267 self._TidyDir(self._output_root_path)
268
269 def _TidyDir(self, dir_path):
270 """Recursively tidy all html files in given dir_path."""
271 html_file_pattern = os.path.join(dir_path, "*.html")
272 html_files_iter = glob.glob(html_file_pattern)
273 for html_file_path in html_files_iter:
274 os.system("tidy -m -errors -quiet %s" % html_file_path)
275 sub_dirs = os.listdir(dir_path)
276 for sub_dir_name in sub_dirs:
277 sub_dir_path = os.path.join(dir_path, sub_dir_name)
278 if os.path.isdir(sub_dir_path):
279 self._TidyDir(sub_dir_path)
280
281 def CombineCoverage(self):
282 """Create combined coverage reports for all targets and tests."""
283 self._CombineTestCoverage()
284 self._CombineTargetCoverage()
285
286
287def Run():
288 """Does coverage operations based on command line args."""
289 # TODO: do we want to support combining coverage for a single target
290
291 try:
292 parser = optparse.OptionParser(usage="usage: %prog --combine-coverage")
293 parser.add_option(
294 "-c", "--combine-coverage", dest="combine_coverage", default=False,
295 action="store_true", help="Combine coverage results stored given "
296 "android root path")
297 parser.add_option(
298 "-t", "--tidy", dest="tidy", default=False, action="store_true",
299 help="Run tidy on all generated html files")
300
301 options, args = parser.parse_args()
302
303 coverage = CoverageGenerator(android_build.GetTop(), None)
304 if options.combine_coverage:
305 coverage.CombineCoverage()
306 if options.tidy:
307 coverage.TidyOutput()
308 except errors.AbortError:
309 logger.SilentLog("Exiting due to AbortError")
310
311if __name__ == "__main__":
312 Run()