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