blob: eb46f1f490ce357e722f35cd9da591cd0889d0d5 [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#
Brett Chabot764d3fa2009-06-25 17:57:31 -07006# 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
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -08009#
Brett Chabot764d3fa2009-06-25 17:57:31 -070010# http://www.apache.org/licenses/LICENSE-2.0
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080011#
Brett Chabot764d3fa2009-06-25 17:57:31 -070012# 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
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080016# 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
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080040 # path to EMMA host jar, relative to Android build root
Brett Chabot764d3fa2009-06-25 17:57:31 -070041 _EMMA_JAR = os.path.join("external", "emma", "lib", "emma.jar")
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080042 _TEST_COVERAGE_EXT = "ec"
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080043 # root path of generated coverage report files, relative to Android build root
44 _COVERAGE_REPORT_PATH = os.path.join("out", "emma")
Brett Chabotae68f1a2009-05-28 18:29:24 -070045 _TARGET_DEF_FILE = "coverage_targets.xml"
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080046 _CORE_TARGET_PATH = os.path.join("development", "testrunner",
Brett Chabotae68f1a2009-05-28 18:29:24 -070047 _TARGET_DEF_FILE)
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080048 # vendor glob file path patterns to tests, relative to android
49 # build root
50 _VENDOR_TARGET_PATH = os.path.join("vendor", "*", "tests", "testinfo",
Brett Chabotae68f1a2009-05-28 18:29:24 -070051 _TARGET_DEF_FILE)
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080052
53 # path to root of target build intermediates
54 _TARGET_INTERMEDIATES_BASE_PATH = os.path.join("out", "target", "common",
55 "obj")
56
Brett Chabot764d3fa2009-06-25 17:57:31 -070057 def __init__(self, adb_interface):
58 self._root_path = android_build.GetTop()
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080059 self._output_root_path = os.path.join(self._root_path,
60 self._COVERAGE_REPORT_PATH)
61 self._emma_jar_path = os.path.join(self._root_path, self._EMMA_JAR)
62 self._adb = adb_interface
63 self._targets_manifest = self._ReadTargets()
64
Brett Chabot72731f32009-03-31 11:14:05 -070065 def TestDeviceCoverageSupport(self):
66 """Check if device has support for generating code coverage metrics.
67
68 Currently this will check if the emma.jar file is on the device's boot
69 classpath.
70
71 Returns:
72 True if device can support code coverage. False otherwise.
73 """
Brett Chabot764d3fa2009-06-25 17:57:31 -070074 try:
75 output = self._adb.SendShellCommand("cat init.rc | grep BOOTCLASSPATH | "
76 "grep emma.jar")
77 if len(output) > 0:
78 return True
79 except errors.AbortError:
80 pass
81 logger.Log("Error: Targeted device does not have emma.jar on its "
82 "BOOTCLASSPATH.")
83 logger.Log("Modify the BOOTCLASSPATH entry in system/core/rootdir/init.rc"
84 " to add emma.jar")
85 return False
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080086
87 def ExtractReport(self, test_suite,
Brett Chabotae68f1a2009-05-28 18:29:24 -070088 device_coverage_path,
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080089 output_path=None):
90 """Extract runtime coverage data and generate code coverage report.
91
92 Assumes test has just been executed.
93 Args:
94 test_suite: TestSuite to generate coverage data for
95 device_coverage_path: location of coverage file on device
96 output_path: path to place output files in. If None will use
97 <android_root_path>/<_COVERAGE_REPORT_PATH>/<target>/<test>
98
99 Returns:
100 absolute file path string of generated html report file.
101 """
102 if output_path is None:
103 output_path = os.path.join(self._root_path,
104 self._COVERAGE_REPORT_PATH,
105 test_suite.GetTargetName(),
106 test_suite.GetName())
107
108 coverage_local_name = "%s.%s" % (test_suite.GetName(),
109 self._TEST_COVERAGE_EXT)
110 coverage_local_path = os.path.join(output_path,
111 coverage_local_name)
112 if self._adb.Pull(device_coverage_path, coverage_local_path):
113
114 report_path = os.path.join(output_path,
115 test_suite.GetName())
116 target = self._targets_manifest.GetTarget(test_suite.GetTargetName())
Brett Chabotae68f1a2009-05-28 18:29:24 -0700117 if target is None:
118 msg = ["Error: test %s references undefined target %s."
119 % (test_suite.GetName(), test_suite.GetTargetName())]
120 msg.append(" Ensure target is defined in %s" % self._TARGET_DEF_FILE)
121 logger.Log("".join(msg))
122 else:
123 return self._GenerateReport(report_path, coverage_local_path, [target],
124 do_src=True)
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800125 return None
126
127 def _GenerateReport(self, report_path, coverage_file_path, targets,
128 do_src=True):
129 """Generate the code coverage report.
130
131 Args:
132 report_path: absolute file path of output file, without extension
133 coverage_file_path: absolute file path of code coverage result file
134 targets: list of CoverageTargets to use as base for code coverage
135 measurement.
136 do_src: True if generate coverage report with source linked in.
137 Note this will increase size of generated report.
138
139 Returns:
140 absolute file path to generated report file.
141 """
142 input_metadatas = self._GatherMetadatas(targets)
143
144 if do_src:
145 src_arg = self._GatherSrcs(targets)
146 else:
147 src_arg = ""
148
149 report_file = "%s.html" % report_path
150 cmd1 = ("java -cp %s emma report -r html -in %s %s %s " %
151 (self._emma_jar_path, coverage_file_path, input_metadatas, src_arg))
152 cmd2 = "-Dreport.html.out.file=%s" % report_file
153 self._RunCmd(cmd1 + cmd2)
154 return report_file
155
156 def _GatherMetadatas(self, targets):
157 """Builds the emma input metadata argument from provided targets.
158
159 Args:
160 targets: list of CoverageTargets
161
162 Returns:
163 input metadata argument string
164 """
165 input_metadatas = ""
166 for target in targets:
167 input_metadata = os.path.join(self._GetBuildIntermediatePath(target),
168 "coverage.em")
169 input_metadatas += " -in %s" % input_metadata
170 return input_metadatas
171
172 def _GetBuildIntermediatePath(self, target):
173 return os.path.join(
174 self._root_path, self._TARGET_INTERMEDIATES_BASE_PATH, target.GetType(),
175 "%s_intermediates" % target.GetName())
176
177 def _GatherSrcs(self, targets):
178 """Builds the emma input source path arguments from provided targets.
179
180 Args:
181 targets: list of CoverageTargets
182 Returns:
183 source path arguments string
184 """
185 src_list = []
186 for target in targets:
187 target_srcs = target.GetPaths()
188 for path in target_srcs:
189 src_list.append("-sp %s" % os.path.join(self._root_path, path))
190 return " ".join(src_list)
191
192 def _MergeFiles(self, input_paths, dest_path):
193 """Merges a set of emma coverage files into a consolidated file.
194
195 Args:
196 input_paths: list of string absolute coverage file paths to merge
197 dest_path: absolute file path of destination file
198 """
199 input_list = []
200 for input_path in input_paths:
201 input_list.append("-in %s" % input_path)
202 input_args = " ".join(input_list)
203 self._RunCmd("java -cp %s emma merge %s -out %s" % (self._emma_jar_path,
204 input_args, dest_path))
205
206 def _RunCmd(self, cmd):
207 """Runs and logs the given os command."""
208 run_command.RunCommand(cmd, return_output=False)
209
210 def _CombineTargetCoverage(self):
211 """Combines all target mode code coverage results.
212
213 Will find all code coverage data files in direct sub-directories of
214 self._output_root_path, and combine them into a single coverage report.
215 Generated report is placed at self._output_root_path/android.html
216 """
217 coverage_files = self._FindCoverageFiles(self._output_root_path)
218 combined_coverage = os.path.join(self._output_root_path,
219 "android.%s" % self._TEST_COVERAGE_EXT)
220 self._MergeFiles(coverage_files, combined_coverage)
221 report_path = os.path.join(self._output_root_path, "android")
222 # don't link to source, to limit file size
223 self._GenerateReport(report_path, combined_coverage,
224 self._targets_manifest.GetTargets(), do_src=False)
225
226 def _CombineTestCoverage(self):
227 """Consolidates code coverage results for all target result directories."""
228 target_dirs = os.listdir(self._output_root_path)
229 for target_name in target_dirs:
230 output_path = os.path.join(self._output_root_path, target_name)
231 target = self._targets_manifest.GetTarget(target_name)
232 if os.path.isdir(output_path) and target is not None:
233 coverage_files = self._FindCoverageFiles(output_path)
234 combined_coverage = os.path.join(output_path, "%s.%s" %
235 (target_name, self._TEST_COVERAGE_EXT))
236 self._MergeFiles(coverage_files, combined_coverage)
237 report_path = os.path.join(output_path, target_name)
238 self._GenerateReport(report_path, combined_coverage, [target])
239 else:
240 logger.Log("%s is not a valid target directory, skipping" % output_path)
241
242 def _FindCoverageFiles(self, root_path):
243 """Finds all files in <root_path>/*/*.<_TEST_COVERAGE_EXT>.
244
245 Args:
246 root_path: absolute file path string to search from
247 Returns:
248 list of absolute file path strings of coverage files
249 """
250 file_pattern = os.path.join(root_path, "*", "*.%s" %
251 self._TEST_COVERAGE_EXT)
252 coverage_files = glob.glob(file_pattern)
253 return coverage_files
254
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800255 def _ReadTargets(self):
256 """Parses the set of coverage target data.
257
258 Returns:
259 a CoverageTargets object that contains set of parsed targets.
260 Raises:
261 AbortError if a fatal error occurred when parsing the target files.
262 """
263 core_target_path = os.path.join(self._root_path, self._CORE_TARGET_PATH)
264 try:
265 targets = coverage_targets.CoverageTargets()
266 targets.Parse(core_target_path)
267 vendor_targets_pattern = os.path.join(self._root_path,
268 self._VENDOR_TARGET_PATH)
269 target_file_paths = glob.glob(vendor_targets_pattern)
270 for target_file_path in target_file_paths:
271 targets.Parse(target_file_path)
272 return targets
273 except errors.ParseError:
274 raise errors.AbortError
275
276 def TidyOutput(self):
277 """Runs tidy on all generated html files.
278
279 This is needed to the html files can be displayed cleanly on a web server.
280 Assumes tidy is on current PATH.
281 """
282 logger.Log("Tidying output files")
283 self._TidyDir(self._output_root_path)
284
285 def _TidyDir(self, dir_path):
286 """Recursively tidy all html files in given dir_path."""
287 html_file_pattern = os.path.join(dir_path, "*.html")
288 html_files_iter = glob.glob(html_file_pattern)
289 for html_file_path in html_files_iter:
290 os.system("tidy -m -errors -quiet %s" % html_file_path)
291 sub_dirs = os.listdir(dir_path)
292 for sub_dir_name in sub_dirs:
293 sub_dir_path = os.path.join(dir_path, sub_dir_name)
294 if os.path.isdir(sub_dir_path):
295 self._TidyDir(sub_dir_path)
296
297 def CombineCoverage(self):
298 """Create combined coverage reports for all targets and tests."""
299 self._CombineTestCoverage()
300 self._CombineTargetCoverage()
301
302
Brett Chabot764d3fa2009-06-25 17:57:31 -0700303def EnableCoverageBuild():
304 """Enable building an Android target with code coverage instrumentation."""
305 os.environ["EMMA_INSTRUMENT"] = "true"
306
307
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800308def 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()