blob: 39a2ceb21e1dc3e1e52f530d0e41fd160a90b00d [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"
Brett Chabot72731f32009-03-31 11:14:05 -070073 #TODO: can emma.jar automagically be added to bootclasspath here?
74
75 def TestDeviceCoverageSupport(self):
76 """Check if device has support for generating code coverage metrics.
77
78 Currently this will check if the emma.jar file is on the device's boot
79 classpath.
80
81 Returns:
82 True if device can support code coverage. False otherwise.
83 """
84 output = self._adb.SendShellCommand("cat init.rc | grep BOOTCLASSPATH | "
85 "grep emma.jar")
86 if len(output) > 0:
87 return True
88 else:
89 logger.Log("Error: Targeted device does not have emma.jar on its "
90 "BOOTCLASSPATH.")
91 logger.Log("Modify the BOOTCLASSPATH entry in system/core/rootdir/init.rc"
92 " to add emma.jar")
93 return False
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080094
95 def ExtractReport(self, test_suite,
96 device_coverage_path=_DEVICE_COVERAGE_PATH,
97 output_path=None):
98 """Extract runtime coverage data and generate code coverage report.
99
100 Assumes test has just been executed.
101 Args:
102 test_suite: TestSuite to generate coverage data for
103 device_coverage_path: location of coverage file on device
104 output_path: path to place output files in. If None will use
105 <android_root_path>/<_COVERAGE_REPORT_PATH>/<target>/<test>
106
107 Returns:
108 absolute file path string of generated html report file.
109 """
110 if output_path is None:
111 output_path = os.path.join(self._root_path,
112 self._COVERAGE_REPORT_PATH,
113 test_suite.GetTargetName(),
114 test_suite.GetName())
115
116 coverage_local_name = "%s.%s" % (test_suite.GetName(),
117 self._TEST_COVERAGE_EXT)
118 coverage_local_path = os.path.join(output_path,
119 coverage_local_name)
120 if self._adb.Pull(device_coverage_path, coverage_local_path):
121
122 report_path = os.path.join(output_path,
123 test_suite.GetName())
124 target = self._targets_manifest.GetTarget(test_suite.GetTargetName())
125 return self._GenerateReport(report_path, coverage_local_path, [target],
126 do_src=True)
127 return None
128
129 def _GenerateReport(self, report_path, coverage_file_path, targets,
130 do_src=True):
131 """Generate the code coverage report.
132
133 Args:
134 report_path: absolute file path of output file, without extension
135 coverage_file_path: absolute file path of code coverage result file
136 targets: list of CoverageTargets to use as base for code coverage
137 measurement.
138 do_src: True if generate coverage report with source linked in.
139 Note this will increase size of generated report.
140
141 Returns:
142 absolute file path to generated report file.
143 """
144 input_metadatas = self._GatherMetadatas(targets)
145
146 if do_src:
147 src_arg = self._GatherSrcs(targets)
148 else:
149 src_arg = ""
150
151 report_file = "%s.html" % report_path
152 cmd1 = ("java -cp %s emma report -r html -in %s %s %s " %
153 (self._emma_jar_path, coverage_file_path, input_metadatas, src_arg))
154 cmd2 = "-Dreport.html.out.file=%s" % report_file
155 self._RunCmd(cmd1 + cmd2)
156 return report_file
157
158 def _GatherMetadatas(self, targets):
159 """Builds the emma input metadata argument from provided targets.
160
161 Args:
162 targets: list of CoverageTargets
163
164 Returns:
165 input metadata argument string
166 """
167 input_metadatas = ""
168 for target in targets:
169 input_metadata = os.path.join(self._GetBuildIntermediatePath(target),
170 "coverage.em")
171 input_metadatas += " -in %s" % input_metadata
172 return input_metadatas
173
174 def _GetBuildIntermediatePath(self, target):
175 return os.path.join(
176 self._root_path, self._TARGET_INTERMEDIATES_BASE_PATH, target.GetType(),
177 "%s_intermediates" % target.GetName())
178
179 def _GatherSrcs(self, targets):
180 """Builds the emma input source path arguments from provided targets.
181
182 Args:
183 targets: list of CoverageTargets
184 Returns:
185 source path arguments string
186 """
187 src_list = []
188 for target in targets:
189 target_srcs = target.GetPaths()
190 for path in target_srcs:
191 src_list.append("-sp %s" % os.path.join(self._root_path, path))
192 return " ".join(src_list)
193
194 def _MergeFiles(self, input_paths, dest_path):
195 """Merges a set of emma coverage files into a consolidated file.
196
197 Args:
198 input_paths: list of string absolute coverage file paths to merge
199 dest_path: absolute file path of destination file
200 """
201 input_list = []
202 for input_path in input_paths:
203 input_list.append("-in %s" % input_path)
204 input_args = " ".join(input_list)
205 self._RunCmd("java -cp %s emma merge %s -out %s" % (self._emma_jar_path,
206 input_args, dest_path))
207
208 def _RunCmd(self, cmd):
209 """Runs and logs the given os command."""
210 run_command.RunCommand(cmd, return_output=False)
211
212 def _CombineTargetCoverage(self):
213 """Combines all target mode code coverage results.
214
215 Will find all code coverage data files in direct sub-directories of
216 self._output_root_path, and combine them into a single coverage report.
217 Generated report is placed at self._output_root_path/android.html
218 """
219 coverage_files = self._FindCoverageFiles(self._output_root_path)
220 combined_coverage = os.path.join(self._output_root_path,
221 "android.%s" % self._TEST_COVERAGE_EXT)
222 self._MergeFiles(coverage_files, combined_coverage)
223 report_path = os.path.join(self._output_root_path, "android")
224 # don't link to source, to limit file size
225 self._GenerateReport(report_path, combined_coverage,
226 self._targets_manifest.GetTargets(), do_src=False)
227
228 def _CombineTestCoverage(self):
229 """Consolidates code coverage results for all target result directories."""
230 target_dirs = os.listdir(self._output_root_path)
231 for target_name in target_dirs:
232 output_path = os.path.join(self._output_root_path, target_name)
233 target = self._targets_manifest.GetTarget(target_name)
234 if os.path.isdir(output_path) and target is not None:
235 coverage_files = self._FindCoverageFiles(output_path)
236 combined_coverage = os.path.join(output_path, "%s.%s" %
237 (target_name, self._TEST_COVERAGE_EXT))
238 self._MergeFiles(coverage_files, combined_coverage)
239 report_path = os.path.join(output_path, target_name)
240 self._GenerateReport(report_path, combined_coverage, [target])
241 else:
242 logger.Log("%s is not a valid target directory, skipping" % output_path)
243
244 def _FindCoverageFiles(self, root_path):
245 """Finds all files in <root_path>/*/*.<_TEST_COVERAGE_EXT>.
246
247 Args:
248 root_path: absolute file path string to search from
249 Returns:
250 list of absolute file path strings of coverage files
251 """
252 file_pattern = os.path.join(root_path, "*", "*.%s" %
253 self._TEST_COVERAGE_EXT)
254 coverage_files = glob.glob(file_pattern)
255 return coverage_files
256
257 def GetEmmaBuildPath(self):
258 return self._EMMA_BUILD_PATH
259
260 def _ReadTargets(self):
261 """Parses the set of coverage target data.
262
263 Returns:
264 a CoverageTargets object that contains set of parsed targets.
265 Raises:
266 AbortError if a fatal error occurred when parsing the target files.
267 """
268 core_target_path = os.path.join(self._root_path, self._CORE_TARGET_PATH)
269 try:
270 targets = coverage_targets.CoverageTargets()
271 targets.Parse(core_target_path)
272 vendor_targets_pattern = os.path.join(self._root_path,
273 self._VENDOR_TARGET_PATH)
274 target_file_paths = glob.glob(vendor_targets_pattern)
275 for target_file_path in target_file_paths:
276 targets.Parse(target_file_path)
277 return targets
278 except errors.ParseError:
279 raise errors.AbortError
280
281 def TidyOutput(self):
282 """Runs tidy on all generated html files.
283
284 This is needed to the html files can be displayed cleanly on a web server.
285 Assumes tidy is on current PATH.
286 """
287 logger.Log("Tidying output files")
288 self._TidyDir(self._output_root_path)
289
290 def _TidyDir(self, dir_path):
291 """Recursively tidy all html files in given dir_path."""
292 html_file_pattern = os.path.join(dir_path, "*.html")
293 html_files_iter = glob.glob(html_file_pattern)
294 for html_file_path in html_files_iter:
295 os.system("tidy -m -errors -quiet %s" % html_file_path)
296 sub_dirs = os.listdir(dir_path)
297 for sub_dir_name in sub_dirs:
298 sub_dir_path = os.path.join(dir_path, sub_dir_name)
299 if os.path.isdir(sub_dir_path):
300 self._TidyDir(sub_dir_path)
301
302 def CombineCoverage(self):
303 """Create combined coverage reports for all targets and tests."""
304 self._CombineTestCoverage()
305 self._CombineTargetCoverage()
306
307
308def Run():
309 """Does coverage operations based on command line args."""
310 # TODO: do we want to support combining coverage for a single target
311
312 try:
313 parser = optparse.OptionParser(usage="usage: %prog --combine-coverage")
314 parser.add_option(
315 "-c", "--combine-coverage", dest="combine_coverage", default=False,
316 action="store_true", help="Combine coverage results stored given "
317 "android root path")
318 parser.add_option(
319 "-t", "--tidy", dest="tidy", default=False, action="store_true",
320 help="Run tidy on all generated html files")
321
322 options, args = parser.parse_args()
323
324 coverage = CoverageGenerator(android_build.GetTop(), None)
325 if options.combine_coverage:
326 coverage.CombineCoverage()
327 if options.tidy:
328 coverage.TidyOutput()
329 except errors.AbortError:
330 logger.SilentLog("Exiting due to AbortError")
331
332if __name__ == "__main__":
333 Run()