1 # 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.
5 """Helper class for instrumenation test jar."""
6 # pylint: disable=W0702
15 from pylib import cmd_helper
16 from pylib import constants
19 os.path.join(constants.DIR_SOURCE_ROOT,
20 'build', 'util', 'lib', 'common'))
22 import unittest_util # pylint: disable=F0401
24 # If you change the cached output of proguard, increment this number
25 PICKLE_FORMAT_VERSION = 1
28 class TestJar(object):
29 _ANNOTATIONS = frozenset(
30 ['Smoke', 'SmallTest', 'MediumTest', 'LargeTest', 'EnormousTest',
31 'FlakyTest', 'DisabledTest', 'Manual', 'PerfTest', 'HostDrivenTest'])
32 _DEFAULT_ANNOTATION = 'SmallTest'
33 _PROGUARD_CLASS_RE = re.compile(r'\s*?- Program class:\s*([\S]+)$')
34 _PROGUARD_METHOD_RE = re.compile(r'\s*?- Method:\s*(\S*)[(].*$')
35 _PROGUARD_ANNOTATION_RE = re.compile(r'\s*?- Annotation \[L(\S*);\]:$')
36 _PROGUARD_ANNOTATION_CONST_RE = (
37 re.compile(r'\s*?- Constant element value.*$'))
38 _PROGUARD_ANNOTATION_VALUE_RE = re.compile(r'\s*?- \S+? \[(.*)\]$')
40 def __init__(self, jar_path):
41 if not os.path.exists(jar_path):
42 raise Exception('%s not found, please build it' % jar_path)
44 self._PROGUARD_PATH = os.path.join(constants.ANDROID_SDK_ROOT,
45 'tools/proguard/bin/proguard.sh')
46 if not os.path.exists(self._PROGUARD_PATH):
47 self._PROGUARD_PATH = os.path.join(os.environ['ANDROID_BUILD_TOP'],
48 'external/proguard/bin/proguard.sh')
49 self._jar_path = jar_path
50 self._annotation_map = collections.defaultdict(list)
51 self._pickled_proguard_name = self._jar_path + '-proguard.pickle'
52 self._test_methods = []
53 if not self._GetCachedProguardData():
54 self._GetProguardData()
56 def _GetCachedProguardData(self):
57 if (os.path.exists(self._pickled_proguard_name) and
58 (os.path.getmtime(self._pickled_proguard_name) >
59 os.path.getmtime(self._jar_path))):
60 logging.info('Loading cached proguard output from %s',
61 self._pickled_proguard_name)
63 with open(self._pickled_proguard_name, 'r') as r:
64 d = pickle.loads(r.read())
65 if d['VERSION'] == PICKLE_FORMAT_VERSION:
66 self._annotation_map = d['ANNOTATION_MAP']
67 self._test_methods = d['TEST_METHODS']
70 logging.warning('PICKLE_FORMAT_VERSION has changed, ignoring cache')
73 def _GetProguardData(self):
74 proguard_output = cmd_helper.GetCmdOutput([self._PROGUARD_PATH,
75 '-injars', self._jar_path,
86 qualified_method = None
87 for line in proguard_output:
88 m = self._PROGUARD_CLASS_RE.match(line)
90 clazz = m.group(1).replace('/', '.') # Change package delim.
94 m = self._PROGUARD_METHOD_RE.match(line)
98 qualified_method = clazz + '#' + method
99 if method.startswith('test') and clazz.endswith('Test'):
100 self._test_methods += [qualified_method]
103 if not qualified_method:
104 # Ignore non-method annotations.
107 m = self._PROGUARD_ANNOTATION_RE.match(line)
109 annotation = m.group(1).split('/')[-1] # Ignore the annotation package.
110 self._annotation_map[qualified_method].append(annotation)
115 m = self._PROGUARD_ANNOTATION_CONST_RE.match(line)
119 m = self._PROGUARD_ANNOTATION_VALUE_RE.match(line)
122 self._annotation_map[qualified_method].append(
123 annotation + ':' + value)
126 logging.info('Storing proguard output to %s', self._pickled_proguard_name)
127 d = {'VERSION': PICKLE_FORMAT_VERSION,
128 'ANNOTATION_MAP': self._annotation_map,
129 'TEST_METHODS': self._test_methods}
130 with open(self._pickled_proguard_name, 'w') as f:
131 f.write(pickle.dumps(d))
133 def _GetAnnotationMap(self):
134 return self._annotation_map
137 def _IsTestMethod(test):
138 class_name, method = test.split('#')
139 return class_name.endswith('Test') and method.startswith('test')
141 def GetTestAnnotations(self, test):
142 """Returns a list of all annotations for the given |test|. May be empty."""
143 if not self._IsTestMethod(test):
145 return self._GetAnnotationMap()[test]
148 def _AnnotationsMatchFilters(annotation_filter_list, annotations):
149 """Checks if annotations match any of the filters."""
150 if not annotation_filter_list:
152 for annotation_filter in annotation_filter_list:
153 filters = annotation_filter.split('=')
154 if len(filters) == 2:
156 value_list = filters[1].split(',')
157 for value in value_list:
158 if key + ':' + value in annotations:
160 elif annotation_filter in annotations:
164 def GetAnnotatedTests(self, annotation_filter_list):
165 """Returns a list of all tests that match the given annotation filters."""
166 return [test for test, annotations in self._GetAnnotationMap().iteritems()
167 if self._IsTestMethod(test) and self._AnnotationsMatchFilters(
168 annotation_filter_list, annotations)]
170 def GetTestMethods(self):
171 """Returns a list of all test methods in this apk as Class#testMethod."""
172 return self._test_methods
174 def _GetTestsMissingAnnotation(self):
175 """Get a list of test methods with no known annotations."""
176 tests_missing_annotations = []
177 for test_method in self.GetTestMethods():
178 annotations_ = frozenset(self.GetTestAnnotations(test_method))
179 if (annotations_.isdisjoint(self._ANNOTATIONS) and
180 not self.IsHostDrivenTest(test_method)):
181 tests_missing_annotations.append(test_method)
182 return sorted(tests_missing_annotations)
184 def GetAllMatchingTests(self, annotation_filter_list,
185 exclude_annotation_list, test_filter):
186 """Get a list of tests matching any of the annotations and the filter.
189 annotation_filter_list: List of test annotations. A test must have at
190 least one of these annotations. A test without any annotations is
191 considered to be SmallTest.
192 exclude_annotation_list: List of test annotations. A test must not have
193 any of these annotations.
194 test_filter: Filter used for partial matching on the test method names.
197 List of all matching tests.
199 if annotation_filter_list:
200 available_tests = self.GetAnnotatedTests(annotation_filter_list)
201 # Include un-annotated tests in SmallTest.
202 if annotation_filter_list.count(self._DEFAULT_ANNOTATION) > 0:
203 for test in self._GetTestsMissingAnnotation():
205 '%s has no annotations. Assuming "%s".', test,
206 self._DEFAULT_ANNOTATION)
207 available_tests.append(test)
208 if exclude_annotation_list:
209 excluded_tests = self.GetAnnotatedTests(exclude_annotation_list)
210 available_tests = list(set(available_tests) - set(excluded_tests))
212 available_tests = [m for m in self.GetTestMethods()
213 if not self.IsHostDrivenTest(m)]
217 # |available_tests| are in adb instrument format: package.path.class#test.
219 # Maps a 'class.test' name to each 'package.path.class#test' name.
220 sanitized_test_names = dict([
221 (t.split('.')[-1].replace('#', '.'), t) for t in available_tests])
222 # Filters 'class.test' names and populates |tests| with the corresponding
223 # 'package.path.class#test' names.
225 sanitized_test_names[t] for t in unittest_util.FilterTestNames(
226 sanitized_test_names.keys(), test_filter.replace('#', '.'))]
228 tests = available_tests
233 def IsHostDrivenTest(test):
234 return 'pythonDrivenTests' in test