blob: 52e8a8ca8fa9037f41b67de9d9ee3fa374a860b9 [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,
Brett Chabot8424ffc2010-01-21 17:29:18 -080089 output_path=None,
90 test_qualifier=None):
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -080091 """Extract runtime coverage data and generate code coverage report.
92
93 Assumes test has just been executed.
94 Args:
95 test_suite: TestSuite to generate coverage data for
96 device_coverage_path: location of coverage file on device
97 output_path: path to place output files in. If None will use
Brett Chabot8424ffc2010-01-21 17:29:18 -080098 <android_root_path>/<_COVERAGE_REPORT_PATH>/<target>/<test[-qualifier]>
99 test_qualifier: designates mode test was run with. e.g size=small.
100 If not None, this will be used to customize output_path as shown above.
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800101
102 Returns:
103 absolute file path string of generated html report file.
104 """
105 if output_path is None:
Brett Chabot8424ffc2010-01-21 17:29:18 -0800106 report_name = test_suite.GetName()
107 if test_qualifier:
108 report_name = report_name + "-" + test_qualifier
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800109 output_path = os.path.join(self._root_path,
110 self._COVERAGE_REPORT_PATH,
111 test_suite.GetTargetName(),
Brett Chabot8424ffc2010-01-21 17:29:18 -0800112 report_name)
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800113
Brett Chabot8424ffc2010-01-21 17:29:18 -0800114 coverage_local_name = "%s.%s" % (report_name,
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800115 self._TEST_COVERAGE_EXT)
116 coverage_local_path = os.path.join(output_path,
117 coverage_local_name)
118 if self._adb.Pull(device_coverage_path, coverage_local_path):
119
120 report_path = os.path.join(output_path,
Brett Chabot8424ffc2010-01-21 17:29:18 -0800121 report_name)
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800122 target = self._targets_manifest.GetTarget(test_suite.GetTargetName())
Brett Chabotae68f1a2009-05-28 18:29:24 -0700123 if target is None:
124 msg = ["Error: test %s references undefined target %s."
125 % (test_suite.GetName(), test_suite.GetTargetName())]
126 msg.append(" Ensure target is defined in %s" % self._TARGET_DEF_FILE)
127 logger.Log("".join(msg))
128 else:
129 return self._GenerateReport(report_path, coverage_local_path, [target],
130 do_src=True)
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800131 return None
132
133 def _GenerateReport(self, report_path, coverage_file_path, targets,
134 do_src=True):
135 """Generate the code coverage report.
136
137 Args:
138 report_path: absolute file path of output file, without extension
139 coverage_file_path: absolute file path of code coverage result file
140 targets: list of CoverageTargets to use as base for code coverage
141 measurement.
142 do_src: True if generate coverage report with source linked in.
143 Note this will increase size of generated report.
144
145 Returns:
146 absolute file path to generated report file.
147 """
148 input_metadatas = self._GatherMetadatas(targets)
149
150 if do_src:
151 src_arg = self._GatherSrcs(targets)
152 else:
153 src_arg = ""
154
155 report_file = "%s.html" % report_path
156 cmd1 = ("java -cp %s emma report -r html -in %s %s %s " %
157 (self._emma_jar_path, coverage_file_path, input_metadatas, src_arg))
158 cmd2 = "-Dreport.html.out.file=%s" % report_file
159 self._RunCmd(cmd1 + cmd2)
160 return report_file
161
162 def _GatherMetadatas(self, targets):
163 """Builds the emma input metadata argument from provided targets.
164
165 Args:
166 targets: list of CoverageTargets
167
168 Returns:
169 input metadata argument string
170 """
171 input_metadatas = ""
172 for target in targets:
173 input_metadata = os.path.join(self._GetBuildIntermediatePath(target),
174 "coverage.em")
175 input_metadatas += " -in %s" % input_metadata
176 return input_metadatas
177
178 def _GetBuildIntermediatePath(self, target):
179 return os.path.join(
180 self._root_path, self._TARGET_INTERMEDIATES_BASE_PATH, target.GetType(),
181 "%s_intermediates" % target.GetName())
182
183 def _GatherSrcs(self, targets):
184 """Builds the emma input source path arguments from provided targets.
185
186 Args:
187 targets: list of CoverageTargets
188 Returns:
189 source path arguments string
190 """
191 src_list = []
192 for target in targets:
193 target_srcs = target.GetPaths()
194 for path in target_srcs:
195 src_list.append("-sp %s" % os.path.join(self._root_path, path))
196 return " ".join(src_list)
197
198 def _MergeFiles(self, input_paths, dest_path):
199 """Merges a set of emma coverage files into a consolidated file.
200
201 Args:
202 input_paths: list of string absolute coverage file paths to merge
203 dest_path: absolute file path of destination file
204 """
205 input_list = []
206 for input_path in input_paths:
207 input_list.append("-in %s" % input_path)
208 input_args = " ".join(input_list)
209 self._RunCmd("java -cp %s emma merge %s -out %s" % (self._emma_jar_path,
210 input_args, dest_path))
211
212 def _RunCmd(self, cmd):
213 """Runs and logs the given os command."""
214 run_command.RunCommand(cmd, return_output=False)
215
216 def _CombineTargetCoverage(self):
217 """Combines all target mode code coverage results.
218
219 Will find all code coverage data files in direct sub-directories of
220 self._output_root_path, and combine them into a single coverage report.
221 Generated report is placed at self._output_root_path/android.html
222 """
223 coverage_files = self._FindCoverageFiles(self._output_root_path)
224 combined_coverage = os.path.join(self._output_root_path,
225 "android.%s" % self._TEST_COVERAGE_EXT)
226 self._MergeFiles(coverage_files, combined_coverage)
227 report_path = os.path.join(self._output_root_path, "android")
228 # don't link to source, to limit file size
229 self._GenerateReport(report_path, combined_coverage,
230 self._targets_manifest.GetTargets(), do_src=False)
231
232 def _CombineTestCoverage(self):
233 """Consolidates code coverage results for all target result directories."""
234 target_dirs = os.listdir(self._output_root_path)
235 for target_name in target_dirs:
236 output_path = os.path.join(self._output_root_path, target_name)
237 target = self._targets_manifest.GetTarget(target_name)
238 if os.path.isdir(output_path) and target is not None:
239 coverage_files = self._FindCoverageFiles(output_path)
240 combined_coverage = os.path.join(output_path, "%s.%s" %
241 (target_name, self._TEST_COVERAGE_EXT))
242 self._MergeFiles(coverage_files, combined_coverage)
243 report_path = os.path.join(output_path, target_name)
244 self._GenerateReport(report_path, combined_coverage, [target])
245 else:
246 logger.Log("%s is not a valid target directory, skipping" % output_path)
247
248 def _FindCoverageFiles(self, root_path):
249 """Finds all files in <root_path>/*/*.<_TEST_COVERAGE_EXT>.
250
251 Args:
252 root_path: absolute file path string to search from
253 Returns:
254 list of absolute file path strings of coverage files
255 """
256 file_pattern = os.path.join(root_path, "*", "*.%s" %
257 self._TEST_COVERAGE_EXT)
258 coverage_files = glob.glob(file_pattern)
259 return coverage_files
260
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800261 def _ReadTargets(self):
262 """Parses the set of coverage target data.
263
264 Returns:
265 a CoverageTargets object that contains set of parsed targets.
266 Raises:
267 AbortError if a fatal error occurred when parsing the target files.
268 """
269 core_target_path = os.path.join(self._root_path, self._CORE_TARGET_PATH)
270 try:
271 targets = coverage_targets.CoverageTargets()
272 targets.Parse(core_target_path)
273 vendor_targets_pattern = os.path.join(self._root_path,
274 self._VENDOR_TARGET_PATH)
275 target_file_paths = glob.glob(vendor_targets_pattern)
276 for target_file_path in target_file_paths:
277 targets.Parse(target_file_path)
278 return targets
279 except errors.ParseError:
280 raise errors.AbortError
281
282 def TidyOutput(self):
283 """Runs tidy on all generated html files.
284
285 This is needed to the html files can be displayed cleanly on a web server.
286 Assumes tidy is on current PATH.
287 """
288 logger.Log("Tidying output files")
289 self._TidyDir(self._output_root_path)
290
291 def _TidyDir(self, dir_path):
292 """Recursively tidy all html files in given dir_path."""
293 html_file_pattern = os.path.join(dir_path, "*.html")
294 html_files_iter = glob.glob(html_file_pattern)
295 for html_file_path in html_files_iter:
296 os.system("tidy -m -errors -quiet %s" % html_file_path)
297 sub_dirs = os.listdir(dir_path)
298 for sub_dir_name in sub_dirs:
299 sub_dir_path = os.path.join(dir_path, sub_dir_name)
300 if os.path.isdir(sub_dir_path):
301 self._TidyDir(sub_dir_path)
302
303 def CombineCoverage(self):
304 """Create combined coverage reports for all targets and tests."""
305 self._CombineTestCoverage()
306 self._CombineTargetCoverage()
307
308
Brett Chabot764d3fa2009-06-25 17:57:31 -0700309def EnableCoverageBuild():
310 """Enable building an Android target with code coverage instrumentation."""
311 os.environ["EMMA_INSTRUMENT"] = "true"
312
313
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800314def Run():
315 """Does coverage operations based on command line args."""
316 # TODO: do we want to support combining coverage for a single target
317
318 try:
319 parser = optparse.OptionParser(usage="usage: %prog --combine-coverage")
320 parser.add_option(
321 "-c", "--combine-coverage", dest="combine_coverage", default=False,
322 action="store_true", help="Combine coverage results stored given "
323 "android root path")
324 parser.add_option(
325 "-t", "--tidy", dest="tidy", default=False, action="store_true",
326 help="Run tidy on all generated html files")
327
328 options, args = parser.parse_args()
329
Brett Chabotddbd2822009-11-13 18:33:43 -0800330 coverage = CoverageGenerator(None)
The Android Open Source Project2b83cbd2009-03-05 17:04:45 -0800331 if options.combine_coverage:
332 coverage.CombineCoverage()
333 if options.tidy:
334 coverage.TidyOutput()
335 except errors.AbortError:
336 logger.SilentLog("Exiting due to AbortError")
337
338if __name__ == "__main__":
339 Run()