Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / build / android / pylib / instrumentation / test_jar.py
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.
4
5 """Helper class for instrumenation test jar."""
6 # pylint: disable=W0702
7
8 import collections
9 import logging
10 import os
11 import pickle
12 import re
13 import sys
14
15 from pylib import cmd_helper
16 from pylib import constants
17
18 sys.path.insert(0,
19                 os.path.join(constants.DIR_SOURCE_ROOT,
20                              'build', 'util', 'lib', 'common'))
21
22 import unittest_util # pylint: disable=F0401
23
24 # If you change the cached output of proguard, increment this number
25 PICKLE_FORMAT_VERSION = 1
26
27
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+? \[(.*)\]$')
39
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)
43
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()
55
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)
62       try:
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']
68           return True
69       except:
70         logging.warning('PICKLE_FORMAT_VERSION has changed, ignoring cache')
71     return False
72
73   def _GetProguardData(self):
74     proguard_output = cmd_helper.GetCmdOutput([self._PROGUARD_PATH,
75                                                '-injars', self._jar_path,
76                                                '-dontshrink',
77                                                '-dontoptimize',
78                                                '-dontobfuscate',
79                                                '-dontpreverify',
80                                                '-dump',
81                                               ]).split('\n')
82     clazz = None
83     method = None
84     annotation = None
85     has_value = False
86     qualified_method = None
87     for line in proguard_output:
88       m = self._PROGUARD_CLASS_RE.match(line)
89       if m:
90         clazz = m.group(1).replace('/', '.')  # Change package delim.
91         annotation = None
92         continue
93
94       m = self._PROGUARD_METHOD_RE.match(line)
95       if m:
96         method = m.group(1)
97         annotation = None
98         qualified_method = clazz + '#' + method
99         if method.startswith('test') and clazz.endswith('Test'):
100           self._test_methods += [qualified_method]
101         continue
102
103       if not qualified_method:
104         # Ignore non-method annotations.
105         continue
106
107       m = self._PROGUARD_ANNOTATION_RE.match(line)
108       if m:
109         annotation = m.group(1).split('/')[-1]  # Ignore the annotation package.
110         self._annotation_map[qualified_method].append(annotation)
111         has_value = False
112         continue
113       if annotation:
114         if not has_value:
115           m = self._PROGUARD_ANNOTATION_CONST_RE.match(line)
116           if m:
117             has_value = True
118         else:
119           m = self._PROGUARD_ANNOTATION_VALUE_RE.match(line)
120           if m:
121             value = m.group(1)
122             self._annotation_map[qualified_method].append(
123                 annotation + ':' + value)
124             has_value = False
125
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))
132
133   def _GetAnnotationMap(self):
134     return self._annotation_map
135
136   @staticmethod
137   def _IsTestMethod(test):
138     class_name, method = test.split('#')
139     return class_name.endswith('Test') and method.startswith('test')
140
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):
144       return []
145     return self._GetAnnotationMap()[test]
146
147   @staticmethod
148   def _AnnotationsMatchFilters(annotation_filter_list, annotations):
149     """Checks if annotations match any of the filters."""
150     if not annotation_filter_list:
151       return True
152     for annotation_filter in annotation_filter_list:
153       filters = annotation_filter.split('=')
154       if len(filters) == 2:
155         key = filters[0]
156         value_list = filters[1].split(',')
157         for value in value_list:
158           if key + ':' + value in annotations:
159             return True
160       elif annotation_filter in annotations:
161         return True
162     return False
163
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)]
169
170   def GetTestMethods(self):
171     """Returns a list of all test methods in this apk as Class#testMethod."""
172     return self._test_methods
173
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)
183
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.
187
188     Args:
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.
195
196     Returns:
197       List of all matching tests.
198     """
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():
204           logging.warning(
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))
211     else:
212       available_tests = [m for m in self.GetTestMethods()
213                          if not self.IsHostDrivenTest(m)]
214
215     tests = []
216     if test_filter:
217       # |available_tests| are in adb instrument format: package.path.class#test.
218
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.
224       tests = [
225           sanitized_test_names[t] for t in unittest_util.FilterTestNames(
226               sanitized_test_names.keys(), test_filter.replace('#', '.'))]
227     else:
228       tests = available_tests
229
230     return tests
231
232   @staticmethod
233   def IsHostDrivenTest(test):
234     return 'pythonDrivenTests' in test