blob: d83d00a150e3178f29f4818eb9610b133798520c [file] [log] [blame]
James Robinson646469d2014-10-03 15:33:28 -07001# Copyright (c) 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Helper class for instrumenation test jar."""
6# pylint: disable=W0702
7
8import logging
9import os
10import pickle
11import re
12import sys
13import tempfile
14
15from pylib import cmd_helper
16from pylib import constants
17from pylib.device import device_utils
18
19sys.path.insert(0,
20 os.path.join(constants.DIR_SOURCE_ROOT,
21 'build', 'util', 'lib', 'common'))
22
23import unittest_util # pylint: disable=F0401
24
25# If you change the cached output of proguard, increment this number
James Robinson6e9a1c92014-11-13 17:05:42 -080026PICKLE_FORMAT_VERSION = 3
James Robinson646469d2014-10-03 15:33:28 -070027
28
29class TestJar(object):
30 _ANNOTATIONS = frozenset(
31 ['Smoke', 'SmallTest', 'MediumTest', 'LargeTest', 'EnormousTest',
32 'FlakyTest', 'DisabledTest', 'Manual', 'PerfTest', 'HostDrivenTest',
33 'IntegrationTest'])
34 _DEFAULT_ANNOTATION = 'SmallTest'
35 _PROGUARD_CLASS_RE = re.compile(r'\s*?- Program class:\s*([\S]+)$')
36 _PROGUARD_SUPERCLASS_RE = re.compile(r'\s*? Superclass:\s*([\S]+)$')
37 _PROGUARD_METHOD_RE = re.compile(r'\s*?- Method:\s*(\S*)[(].*$')
38 _PROGUARD_ANNOTATION_RE = re.compile(r'\s*?- Annotation \[L(\S*);\]:$')
39 _PROGUARD_ANNOTATION_CONST_RE = (
40 re.compile(r'\s*?- Constant element value.*$'))
41 _PROGUARD_ANNOTATION_VALUE_RE = re.compile(r'\s*?- \S+? \[(.*)\]$')
42
43 def __init__(self, jar_path):
44 if not os.path.exists(jar_path):
45 raise Exception('%s not found, please build it' % jar_path)
46
47 self._PROGUARD_PATH = os.path.join(constants.ANDROID_SDK_ROOT,
48 'tools/proguard/lib/proguard.jar')
49 if not os.path.exists(self._PROGUARD_PATH):
50 self._PROGUARD_PATH = os.path.join(os.environ['ANDROID_BUILD_TOP'],
51 'external/proguard/lib/proguard.jar')
52 self._jar_path = jar_path
53 self._pickled_proguard_name = self._jar_path + '-proguard.pickle'
54 self._test_methods = {}
55 if not self._GetCachedProguardData():
56 self._GetProguardData()
57
James Robinson6e9a1c92014-11-13 17:05:42 -080058 @staticmethod
59 def _CalculateMd5(path):
60 # TODO(jbudorick): Move MD5sum calculations out of here and
61 # AndroidCommands to their own module.
62 out = cmd_helper.GetCmdOutput(
63 [os.path.join(constants.GetOutDirectory(),
64 'md5sum_bin_host'),
65 path])
66 return out
67
James Robinson646469d2014-10-03 15:33:28 -070068 def _GetCachedProguardData(self):
69 if (os.path.exists(self._pickled_proguard_name) and
70 (os.path.getmtime(self._pickled_proguard_name) >
71 os.path.getmtime(self._jar_path))):
72 logging.info('Loading cached proguard output from %s',
73 self._pickled_proguard_name)
74 try:
75 with open(self._pickled_proguard_name, 'r') as r:
76 d = pickle.loads(r.read())
James Robinson6e9a1c92014-11-13 17:05:42 -080077 jar_md5 = self._CalculateMd5(self._jar_path)
78 if (d['JAR_MD5SUM'] == jar_md5 and
79 d['VERSION'] == PICKLE_FORMAT_VERSION):
James Robinson646469d2014-10-03 15:33:28 -070080 self._test_methods = d['TEST_METHODS']
81 return True
82 except:
83 logging.warning('PICKLE_FORMAT_VERSION has changed, ignoring cache')
84 return False
85
86 def _GetProguardData(self):
87 logging.info('Retrieving test methods via proguard.')
88
89 with tempfile.NamedTemporaryFile() as proguard_output:
90 cmd_helper.RunCmd(['java', '-jar',
91 self._PROGUARD_PATH,
92 '-injars', self._jar_path,
93 '-dontshrink',
94 '-dontoptimize',
95 '-dontobfuscate',
96 '-dontpreverify',
97 '-dump', proguard_output.name])
98
99 clazzez = {}
100
101 annotation = None
102 annotation_has_value = False
103 clazz = None
104 method = None
105
106 for line in proguard_output:
107 if len(line) == 0:
108 annotation = None
109 annotation_has_value = False
110 method = None
111 continue
112
113 m = self._PROGUARD_CLASS_RE.match(line)
114 if m:
115 clazz = m.group(1).replace('/', '.')
116 clazzez[clazz] = {
117 'methods': {},
118 'annotations': {}
119 }
120 annotation = None
121 annotation_has_value = False
122 method = None
123 continue
124
125 if not clazz:
126 continue
127
128 m = self._PROGUARD_SUPERCLASS_RE.match(line)
129 if m:
130 clazzez[clazz]['superclass'] = m.group(1).replace('/', '.')
131 continue
132
133 if clazz.endswith('Test'):
134 m = self._PROGUARD_METHOD_RE.match(line)
135 if m:
136 method = m.group(1)
137 clazzez[clazz]['methods'][method] = {'annotations': {}}
138 annotation = None
139 annotation_has_value = False
140 continue
141
142 m = self._PROGUARD_ANNOTATION_RE.match(line)
143 if m:
144 # Ignore the annotation package.
145 annotation = m.group(1).split('/')[-1]
146 if method:
147 clazzez[clazz]['methods'][method]['annotations'][annotation] = None
148 else:
149 clazzez[clazz]['annotations'][annotation] = None
150 continue
151
152 if annotation:
153 if not annotation_has_value:
154 m = self._PROGUARD_ANNOTATION_CONST_RE.match(line)
155 annotation_has_value = bool(m)
156 else:
157 m = self._PROGUARD_ANNOTATION_VALUE_RE.match(line)
158 if m:
159 if method:
160 clazzez[clazz]['methods'][method]['annotations'][annotation] = (
161 m.group(1))
162 else:
163 clazzez[clazz]['annotations'][annotation] = m.group(1)
164 annotation_has_value = None
165
166 test_clazzez = ((n, i) for n, i in clazzez.items() if n.endswith('Test'))
167 for clazz_name, clazz_info in test_clazzez:
168 logging.info('Processing %s' % clazz_name)
169 c = clazz_name
170 min_sdk_level = None
171
172 while c in clazzez:
173 c_info = clazzez[c]
174 if not min_sdk_level:
175 min_sdk_level = c_info['annotations'].get('MinAndroidSdkLevel', None)
176 c = c_info.get('superclass', None)
177
178 for method_name, method_info in clazz_info['methods'].items():
179 if method_name.startswith('test'):
180 qualified_method = '%s#%s' % (clazz_name, method_name)
181 method_annotations = []
182 for annotation_name, annotation_value in (
183 method_info['annotations'].items()):
184 method_annotations.append(annotation_name)
185 if annotation_value:
186 method_annotations.append(
187 annotation_name + ':' + annotation_value)
188 self._test_methods[qualified_method] = {
189 'annotations': method_annotations
190 }
191 if min_sdk_level is not None:
192 self._test_methods[qualified_method]['min_sdk_level'] = (
193 int(min_sdk_level))
194
195 logging.info('Storing proguard output to %s', self._pickled_proguard_name)
196 d = {'VERSION': PICKLE_FORMAT_VERSION,
James Robinson6e9a1c92014-11-13 17:05:42 -0800197 'TEST_METHODS': self._test_methods,
198 'JAR_MD5SUM': self._CalculateMd5(self._jar_path)}
James Robinson646469d2014-10-03 15:33:28 -0700199 with open(self._pickled_proguard_name, 'w') as f:
200 f.write(pickle.dumps(d))
201
202
203 @staticmethod
204 def _IsTestMethod(test):
205 class_name, method = test.split('#')
206 return class_name.endswith('Test') and method.startswith('test')
207
208 def GetTestAnnotations(self, test):
209 """Returns a list of all annotations for the given |test|. May be empty."""
210 if not self._IsTestMethod(test) or not test in self._test_methods:
211 return []
212 return self._test_methods[test]['annotations']
213
214 @staticmethod
215 def _AnnotationsMatchFilters(annotation_filter_list, annotations):
216 """Checks if annotations match any of the filters."""
217 if not annotation_filter_list:
218 return True
219 for annotation_filter in annotation_filter_list:
220 filters = annotation_filter.split('=')
221 if len(filters) == 2:
222 key = filters[0]
223 value_list = filters[1].split(',')
224 for value in value_list:
225 if key + ':' + value in annotations:
226 return True
227 elif annotation_filter in annotations:
228 return True
229 return False
230
231 def GetAnnotatedTests(self, annotation_filter_list):
232 """Returns a list of all tests that match the given annotation filters."""
233 return [test for test, attr in self.GetTestMethods().iteritems()
234 if self._IsTestMethod(test) and self._AnnotationsMatchFilters(
235 annotation_filter_list, attr['annotations'])]
236
237 def GetTestMethods(self):
238 """Returns a dict of all test methods and relevant attributes.
239
240 Test methods are retrieved as Class#testMethod.
241 """
242 return self._test_methods
243
244 def _GetTestsMissingAnnotation(self):
245 """Get a list of test methods with no known annotations."""
246 tests_missing_annotations = []
247 for test_method in self.GetTestMethods().iterkeys():
248 annotations_ = frozenset(self.GetTestAnnotations(test_method))
249 if (annotations_.isdisjoint(self._ANNOTATIONS) and
250 not self.IsHostDrivenTest(test_method)):
251 tests_missing_annotations.append(test_method)
252 return sorted(tests_missing_annotations)
253
254 def _IsTestValidForSdkRange(self, test_name, attached_min_sdk_level):
255 required_min_sdk_level = self.GetTestMethods()[test_name].get(
256 'min_sdk_level', None)
257 return (required_min_sdk_level is None or
258 attached_min_sdk_level >= required_min_sdk_level)
259
260 def GetAllMatchingTests(self, annotation_filter_list,
261 exclude_annotation_list, test_filter):
262 """Get a list of tests matching any of the annotations and the filter.
263
264 Args:
265 annotation_filter_list: List of test annotations. A test must have at
266 least one of these annotations. A test without any annotations is
267 considered to be SmallTest.
268 exclude_annotation_list: List of test annotations. A test must not have
269 any of these annotations.
270 test_filter: Filter used for partial matching on the test method names.
271
272 Returns:
273 List of all matching tests.
274 """
275 if annotation_filter_list:
276 available_tests = self.GetAnnotatedTests(annotation_filter_list)
277 # Include un-annotated tests in SmallTest.
278 if annotation_filter_list.count(self._DEFAULT_ANNOTATION) > 0:
279 for test in self._GetTestsMissingAnnotation():
280 logging.warning(
281 '%s has no annotations. Assuming "%s".', test,
282 self._DEFAULT_ANNOTATION)
283 available_tests.append(test)
James Robinson646469d2014-10-03 15:33:28 -0700284 else:
285 available_tests = [m for m in self.GetTestMethods()
286 if not self.IsHostDrivenTest(m)]
287
James Robinsone1b30cf2014-10-21 12:25:40 -0700288 if exclude_annotation_list:
289 excluded_tests = self.GetAnnotatedTests(exclude_annotation_list)
290 available_tests = list(set(available_tests) - set(excluded_tests))
291
James Robinson646469d2014-10-03 15:33:28 -0700292 tests = []
293 if test_filter:
294 # |available_tests| are in adb instrument format: package.path.class#test.
295
296 # Maps a 'class.test' name to each 'package.path.class#test' name.
297 sanitized_test_names = dict([
298 (t.split('.')[-1].replace('#', '.'), t) for t in available_tests])
299 # Filters 'class.test' names and populates |tests| with the corresponding
300 # 'package.path.class#test' names.
301 tests = [
302 sanitized_test_names[t] for t in unittest_util.FilterTestNames(
303 sanitized_test_names.keys(), test_filter.replace('#', '.'))]
304 else:
305 tests = available_tests
306
307 # Filter out any tests with SDK level requirements that don't match the set
308 # of attached devices.
309 sdk_versions = [
310 int(v) for v in
311 device_utils.DeviceUtils.parallel().GetProp(
312 'ro.build.version.sdk').pGet(None)]
313 tests = filter(
314 lambda t: self._IsTestValidForSdkRange(t, min(sdk_versions)),
315 tests)
316
317 return tests
318
319 @staticmethod
320 def IsHostDrivenTest(test):
321 return 'pythonDrivenTests' in test