Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(546)

Side by Side Diff: build/android/pylib/instrumentation/apk_info.py

Issue 12921004: [Android] Enable running uiautomator tests. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 7 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 # Copyright (c) 2012 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 """Gathers information about APKs."""
6
7 import collections
8 import logging
9 import os
10 import pickle
11 import re
12
13 from pylib import cmd_helper
14 from pylib import constants
15
16
17 # If you change the cached output of proguard, increment this number
18 PICKLE_FORMAT_VERSION = 1
19
20 def GetPackageNameForApk(apk_path):
21 """Returns the package name of the apk file."""
22 aapt_output = cmd_helper.GetCmdOutput(
23 ['aapt', 'dump', 'badging', apk_path]).split('\n')
24 package_name_re = re.compile(r'package: .*name=\'(\S*)\'')
25 for line in aapt_output:
26 m = package_name_re.match(line)
27 if m:
28 return m.group(1)
29 raise Exception('Failed to determine package name of %s' % apk_path)
30
31
32 class ApkInfo(object):
33 """Helper class for inspecting APKs."""
34
35 def __init__(self, apk_path, jar_path):
36 sdk_root = os.getenv('ANDROID_SDK_ROOT', constants.ANDROID_SDK_ROOT)
37 self._PROGUARD_PATH = os.path.join(sdk_root,
38 'tools/proguard/bin/proguard.sh')
39 if not os.path.exists(self._PROGUARD_PATH):
40 self._PROGUARD_PATH = os.path.join(os.environ['ANDROID_BUILD_TOP'],
41 'external/proguard/bin/proguard.sh')
42 self._PROGUARD_CLASS_RE = re.compile(r'\s*?- Program class:\s*([\S]+)$')
43 self._PROGUARD_METHOD_RE = re.compile(r'\s*?- Method:\s*(\S*)[(].*$')
44 self._PROGUARD_ANNOTATION_RE = re.compile(r'\s*?- Annotation \[L(\S*);\]:$')
45 self._PROGUARD_ANNOTATION_CONST_RE = (
46 re.compile(r'\s*?- Constant element value.*$'))
47 self._PROGUARD_ANNOTATION_VALUE_RE = re.compile(r'\s*?- \S+? \[(.*)\]$')
48
49 if not os.path.exists(apk_path):
50 raise Exception('%s not found, please build it' % apk_path)
51 self._apk_path = apk_path
52 if not os.path.exists(jar_path):
53 raise Exception('%s not found, please build it' % jar_path)
54 self._jar_path = jar_path
55 self._annotation_map = collections.defaultdict(list)
56 self._pickled_proguard_name = self._jar_path + '-proguard.pickle'
57 self._test_methods = []
58 self._Initialize()
59
60 def _Initialize(self):
61 if not self._GetCachedProguardData():
62 self._GetProguardData()
63
64 def _GetCachedProguardData(self):
65 if (os.path.exists(self._pickled_proguard_name) and
66 (os.path.getmtime(self._pickled_proguard_name) >
67 os.path.getmtime(self._jar_path))):
68 logging.info('Loading cached proguard output from %s',
69 self._pickled_proguard_name)
70 try:
71 with open(self._pickled_proguard_name, 'r') as r:
72 d = pickle.loads(r.read())
73 if d['VERSION'] == PICKLE_FORMAT_VERSION:
74 self._annotation_map = d['ANNOTATION_MAP']
75 self._test_methods = d['TEST_METHODS']
76 return True
77 except:
78 logging.warning('PICKLE_FORMAT_VERSION has changed, ignoring cache')
79 return False
80
81 def _GetProguardData(self):
82 proguard_output = cmd_helper.GetCmdOutput([self._PROGUARD_PATH,
83 '-injars', self._jar_path,
84 '-dontshrink',
85 '-dontoptimize',
86 '-dontobfuscate',
87 '-dontpreverify',
88 '-dump',
89 ]).split('\n')
90 clazz = None
91 method = None
92 annotation = None
93 has_value = False
94 qualified_method = None
95 for line in proguard_output:
96 m = self._PROGUARD_CLASS_RE.match(line)
97 if m:
98 clazz = m.group(1).replace('/', '.') # Change package delim.
99 annotation = None
100 continue
101
102 m = self._PROGUARD_METHOD_RE.match(line)
103 if m:
104 method = m.group(1)
105 annotation = None
106 qualified_method = clazz + '#' + method
107 if method.startswith('test') and clazz.endswith('Test'):
108 self._test_methods += [qualified_method]
109 continue
110
111 if not qualified_method:
112 # Ignore non-method annotations.
113 continue
114
115 m = self._PROGUARD_ANNOTATION_RE.match(line)
116 if m:
117 annotation = m.group(1).split('/')[-1] # Ignore the annotation package.
118 self._annotation_map[qualified_method].append(annotation)
119 has_value = False
120 continue
121 if annotation:
122 if not has_value:
123 m = self._PROGUARD_ANNOTATION_CONST_RE.match(line)
124 if m:
125 has_value = True
126 else:
127 m = self._PROGUARD_ANNOTATION_VALUE_RE.match(line)
128 if m:
129 value = m.group(1)
130 self._annotation_map[qualified_method].append(
131 annotation + ':' + value)
132 has_value = False
133
134 logging.info('Storing proguard output to %s', self._pickled_proguard_name)
135 d = {'VERSION': PICKLE_FORMAT_VERSION,
136 'ANNOTATION_MAP': self._annotation_map,
137 'TEST_METHODS': self._test_methods}
138 with open(self._pickled_proguard_name, 'w') as f:
139 f.write(pickle.dumps(d))
140
141 def _GetAnnotationMap(self):
142 return self._annotation_map
143
144 def _IsTestMethod(self, test):
145 class_name, method = test.split('#')
146 return class_name.endswith('Test') and method.startswith('test')
147
148 def GetApkPath(self):
149 return self._apk_path
150
151 def GetPackageName(self):
152 """Returns the package name of this APK."""
153 return GetPackageNameForApk(self._apk_path)
154
155 def GetTestAnnotations(self, test):
156 """Returns a list of all annotations for the given |test|. May be empty."""
157 if not self._IsTestMethod(test):
158 return []
159 return self._GetAnnotationMap()[test]
160
161 def _AnnotationsMatchFilters(self, annotation_filter_list, annotations):
162 """Checks if annotations match any of the filters."""
163 if not annotation_filter_list:
164 return True
165 for annotation_filter in annotation_filter_list:
166 filters = annotation_filter.split('=')
167 if len(filters) == 2:
168 key = filters[0]
169 value_list = filters[1].split(',')
170 for value in value_list:
171 if key + ':' + value in annotations:
172 return True
173 elif annotation_filter in annotations:
174 return True
175 return False
176
177 def GetAnnotatedTests(self, annotation_filter_list):
178 """Returns a list of all tests that match the given annotation filters."""
179 return [test for test, annotations in self._GetAnnotationMap().iteritems()
180 if self._IsTestMethod(test) and self._AnnotationsMatchFilters(
181 annotation_filter_list, annotations)]
182
183 def GetTestMethods(self):
184 """Returns a list of all test methods in this apk as Class#testMethod."""
185 return self._test_methods
186
187 @staticmethod
188 def IsPythonDrivenTest(test):
189 return 'pythonDrivenTests' in test
OLDNEW
« no previous file with comments | « build/android/pylib/host_driven/run_python_tests.py ('k') | build/android/pylib/instrumentation/dispatch.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698