forked from dtmilano/AndroidViewClient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathculebra
More file actions
executable file
·365 lines (318 loc) · 11.3 KB
/
culebra
File metadata and controls
executable file
·365 lines (318 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#! /usr/bin/env shebang monkeyrunner -plugin $ANDROID_VIEW_CLIENT_HOME/bin/androidviewclient-2.3.11.jar @!
#! /usr/bin/env monkeyrunner
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013 Diego Torres Milano
Created on Mar 28, 2013
Culebra helps you create AndroidViewClient scripts generating a working template that can be
modified to suit more specific needs.
__ __ __ __
/ \ / \ / \ / \
____________________/ __\/ __\/ __\/ __\_____________________________
___________________/ /__/ /__/ /__/ /________________________________
| / \ / \ / \ / \ \___
|/ \_/ \_/ \_/ \ o \
\_____/--<
@author: diego
@author: Jennifer E. Swofford (ascii art snake)
'''
__version__ = '0.9.5'
import re
import sys
import os
import getopt
import warnings
from datetime import date
# This must be imported before MonkeyRunner and MonkeyDevice,
# otherwise the import fails.
# PyDev sets PYTHONPATH, use it
try:
for p in os.environ['PYTHONPATH'].split(':'):
if not p in sys.path:
sys.path.append(p)
except:
pass
try:
sys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
pass
from com.dtmilano.android.viewclient import ViewClient
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
HELP = 'help'
VERBOSE = 'verbose'
IGNORE_SECURE_DEVICE = 'ignore-secure-device'
FORCE_VIEW_SERVER_USE = 'force-view-server-use'
DO_NOT_START_VIEW_SERVER = 'do-not-start-view-server'
FIND_VIEWS_BY_ID = 'find-views-by-id'
FIND_VIEWS_WITH_TEXT = 'find-views-with-text'
FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 'find-views-with-content-description'
USE_REGEXPS = 'use-regexps'
VERBOSE_COMMENTS = 'verbose-comments'
UNIT_TEST = 'unit-test'
USE_JAR = 'use-jar'
USE_DICTIONARY = 'use-dictionary'
AUTO_REGEXPS = 'auto-regexps'
USAGE = 'usage: %s [OPTION]... [serialno]'
# -u,-s,-p,-v eaten by monkeyrunner
SHORT_OPTS = 'HVIFSi:t:d:rCUj:D:R:'
LONG_OPTS = [HELP, VERBOSE, IGNORE_SECURE_DEVICE, FORCE_VIEW_SERVER_USE, DO_NOT_START_VIEW_SERVER,
FIND_VIEWS_BY_ID + '=', FIND_VIEWS_WITH_TEXT + '=', FIND_VIEWS_WITH_CONTENT_DESCRIPTION + '=',
USE_REGEXPS, VERBOSE_COMMENTS, UNIT_TEST,
USE_JAR + '=', USE_DICTIONARY + '=', AUTO_REGEXPS + '=']
LONG_OPTS_ARG = {FIND_VIEWS_BY_ID: 'BOOL', FIND_VIEWS_WITH_TEXT: 'BOOL', FIND_VIEWS_WITH_CONTENT_DESCRIPTION: 'BOOL',
USE_JAR: 'BOOL', USE_DICTIONARY: 'BOOL', AUTO_REGEXPS: 'LIST'}
OPTS_HELP = {
'H': 'prints this help',
'i': 'whether to use findViewById() in script',
't': 'whether to use findViewWithText() in script',
'd': 'whether to sue findViewWithContentDescription',
'r': 'use regexps in matches',
'U': 'generates unit test script',
'j': 'use jar and appropriate shebang to run script',
'D': 'use a dictionary to store the Views found',
'R': 'auto regexps (i.e. clock)',
}
ID_RE = re.compile('id/([^/]*)(/(\d+))?')
AUTO_REGEXPS_RES = {'clock': re.compile('[012]\d:[0-5]\d')}
SHEBANG = {
'no-jar': '#! /usr/bin/env monkeyrunner',
'jar': '#! /usr/bin/env shebang monkeyrunner -plugin $ANDROID_VIEW_CLIENT_HOME/bin/androidviewclient-2.3.11.jar @!'
}
def shortAndLongOptions():
'''
@return: the list of corresponding (short-option, long-option) tuples
'''
short_opts = SHORT_OPTS.replace(':', '')
if len(short_opts) != len(LONG_OPTS):
raise Exception('There is a mismatch between short and long options')
t = tuple(short_opts) + tuple(LONG_OPTS)
l2 = len(t)/2
sl = []
for i in range(l2):
sl.append((t[i], t[i+l2]))
return sl
def usage(exitVal=1):
print >> sys.stderr, USAGE % progname
print >> sys.stderr, "Try '%s --help' for more information." % progname
sys.exit(exitVal)
def help():
print >> sys.stderr, USAGE % progname
print >> sys.stderr
print >> sys.stderr, "Options:"
for so, lo in shortAndLongOptions():
o = ' -%c, --%s' % (so, lo)
if lo[-1] == '=':
o += LONG_OPTS_ARG[lo[:-1]]
try:
o = '%-34s %-45s' % (o, OPTS_HELP[so])
except:
pass
print >> sys.stderr, o
sys.exit(0)
def error(msg, fatal=False):
print >>sys.stderr, "%s: ERROR: %s" % (progname, msg)
if fatal:
sys.exit(1)
def printVerboseComments(view):
'''
Prints the verbose comments for view.
'''
print '\n# class=%s' % view.getClass(),
try:
text = view.getText()
if text:
print 'text="%s"' % text,
except:
pass
try:
tag = view.getTag()
if tab != 'null':
print 'tag=%s' % tag
except:
pass
print
def variableNameFromId(id):
'''
Returns a suitable variable name from the id.
@type id: str
@param id: the I{id}
@return: the variable name from the id
'''
m = ID_RE.match(id)
if m:
var = m.group(1)
if m.group(3):
var += m.group(3)
if re.match('^\d', var):
var = 'id_' + var
if options[USE_DICTIONARY]:
return 'views[\'%s\']' % var
else:
return var
else:
raise Exception('Not an id: %s' % id)
def printFindViewWithText(view, useregexp):
'''
Prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
id = view.getUniqueId()
text = view.getText()
if text:
var = variableNameFromId(id)
if useregexp:
text = "re.compile('%s')" % text
else:
text = "'%s'" % text
print '%s = vc.findViewWithTextOrRaise(%s)' % (var, text)
elif kwargs1[VERBOSE]:
warnings.warn('View with id=%s has no text' % id)
def printFindViewWithContentDescription(view, useregexp):
'''
Prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
id = view.getUniqueId()
contentDescription = view.getContentDescription()
if contentDescription:
var = variableNameFromId(id)
if useregexp:
if options[AUTO_REGEXPS]:
for r in options[AUTO_REGEXPS]:
autoRegexp = AUTO_REGEXPS_RES[r]
if autoRegexp.match(contentDescription):
contentDescription = autoRegexp.pattern
break
contentDescription = "re.compile('%s')" % contentDescription
else:
contentDescription = "'%s'" % contentDescription
print '%s = vc.findViewWithContentDescriptionOrRaise(%s)' % (var, contentDescription)
elif kwargs1[VERBOSE]:
warnings.warn('View with id=%s has no content-description' % id)
def printFindViewById(view):
'''
Prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
id = view.getUniqueId()
var = variableNameFromId(id)
print '%s = vc.findViewByIdOrRaise("%s")' % (var, id)
def traverseAndPrint(view):
'''
Traverses the View tree and prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
if options[VERBOSE_COMMENTS]:
printVerboseComments(view)
if options[FIND_VIEWS_BY_ID]:
printFindViewById(view)
if options[FIND_VIEWS_WITH_TEXT]:
printFindViewWithText(view, options[USE_REGEXPS])
if options[FIND_VIEWS_WITH_CONTENT_DESCRIPTION]:
printFindViewWithContentDescription(view, options[USE_REGEXPS])
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1", "on")
# __main__
progname = os.path.basename(sys.argv[0])
try:
optlist, args = getopt.getopt(sys.argv[1:], SHORT_OPTS, LONG_OPTS)
except getopt.GetoptError, e:
print >>sys.stderr, 'ERROR:', str(e)
usage()
sys.argv[1:] = args
kwargs1 = {VERBOSE: False, 'ignoresecuredevice': False}
kwargs2 = {'forceviewserveruse': False, 'startviewserver': True}
options = {FIND_VIEWS_BY_ID: True, FIND_VIEWS_WITH_TEXT: False, FIND_VIEWS_WITH_CONTENT_DESCRIPTION: False,
USE_REGEXPS: False, VERBOSE_COMMENTS: False,
UNIT_TEST: False, USE_JAR: True, USE_DICTIONARY: False, AUTO_REGEXPS: None}
transform = traverseAndPrint
for o, a in optlist:
o = o.strip('-')
if o in ['H', HELP]:
help()
elif o in ['V', VERBOSE]:
kwargs1[VERBOSE] = True
elif o in ['I', IGNORE_SECURE_DEVICE]:
kwargs1['ignoresecuredevice'] = True
elif o in ['F', FORCE_VIEW_SERVER_USE]:
kwargs2['forceviewserveruse'] = True
elif o in ['S', DO_NOT_START_VIEW_SERVER]:
kwargs2['startviewserver'] = False
elif o in ['i', FIND_VIEWS_BY_ID]:
options[FIND_VIEWS_BY_ID] = str2bool(a)
elif o in ['t', FIND_VIEWS_WITH_TEXT]:
options[FIND_VIEWS_WITH_TEXT] = str2bool(a)
elif o in ['d', FIND_VIEWS_WITH_CONTENT_DESCRIPTION]:
options[FIND_VIEWS_WITH_CONTENT_DESCRIPTION] = str2bool(a)
elif o in ['r', USE_REGEXPS]:
options[USE_REGEXPS] = True
elif o in ['C', VERBOSE_COMMENTS]:
options[VERBOSE_COMMENTS] = True
elif o in ['U', UNIT_TEST]:
warnings.warn('Not implemented yet: %s' % o)
options[UNIT_TEST] = True
elif o in ['j', USE_JAR]:
options[USE_JAR] = str2bool(a)
elif o in ['D', USE_DICTIONARY]:
options[USE_DICTIONARY] = str2bool(a)
elif o in ['R', AUTO_REGEXPS]:
options[AUTO_REGEXPS] = a.split(',')
for r in options[AUTO_REGEXPS]:
if r not in AUTO_REGEXPS_RES:
error("invalid auto regexp: %s\n" % (r))
usage()
if not (options[FIND_VIEWS_BY_ID] or options[FIND_VIEWS_WITH_TEXT]):
if not options[VERBOSE_COMMENTS]:
warnings.warn('All printing options disabled. Output will be empty.')
else:
warnings.warn('Only verbose comments will be printed')
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
vc = ViewClient(device, serialno, **kwargs2)
print '''%s
# -*- coding: utf-8 -*-
\'\'\'
Copyright (C) 2013 Diego Torres Milano
Created on %s by Culebra v%s
__ __ __ __
/ \ / \ / \ / \
____________________/ __\/ __\/ __\/ __\_____________________________
___________________/ /__/ /__/ /__/ /________________________________
| / \ / \ / \ / \ \___
|/ \_/ \_/ \_/ \ o \
\_____/--<
@author: diego
@author: Jennifer E. Swofford (ascii art snake)
\'\'\'
import re
import sys
import os
''' % (SHEBANG['jar' if options[USE_JAR] else 'no-jar'], date.today(), __version__)
if not options[USE_JAR]:
print '''
# This must be imported before MonkeyRunner and MonkeyDevice,
# otherwise the import fails.
# PyDev sets PYTHONPATH, use it
try:
for p in os.environ['PYTHONPATH'].split(':'):
if not p in sys.path:
sys.path.append(p)
except:
pass
try:
sys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
pass
'''
print '''
from com.dtmilano.android.viewclient import ViewClient
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device, serialno = ViewClient.connectToDeviceOrExit()
vc = ViewClient(device, serialno)
'''
if options[USE_DICTIONARY]:
print '''views = dict()'''
vc.traverse(transform=transform)