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
·1673 lines (1436 loc) · 62.8 KB
/
culebra
File metadata and controls
executable file
·1673 lines (1436 loc) · 62.8 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2013-2022 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 Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
"""
from __future__ import print_function
import textwrap
import culebratester_client
from culebratester_client import WindowHierarchy
__version__ = '21.16.9'
import calendar
import codecs
import getopt
import os
import re
import sys
import warnings
from datetime import date
try:
sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
pass
from com.dtmilano.android.viewclient import ViewClient, ViewClientOptions, View, CulebraOptions
from com.dtmilano.android.culebron import Culebron, Operation, Unit
from com.dtmilano.android.concertina import Concertina
from com.dtmilano.android.common import debugArgsToDict
from com.dtmilano.android.code_generator import HelperCodeGenerator, VcCodeGenerator
DEBUG = False
USAGE = 'usage: %s [OPTION]... [serialno]'
TAG = 'CULEBRA'
class Descriptor:
CONTENT_DESCRIPTION = 'content-description'
TEXT = 'text'
ID = 'id'
@staticmethod
def findBestDescriptor(view):
'''
Finds the best possible descriptor for the View
'''
cd = view.getContentDescription()
if cd and options[CulebraOptions.FIND_VIEWS_WITH_CONTENT_DESCRIPTION]:
return Descriptor.CONTENT_DESCRIPTION
else:
t = view.getText()
if t and options[CulebraOptions.FIND_VIEWS_WITH_TEXT]:
return Descriptor.TEXT
return Descriptor.ID
def fillAutoRegexpsRes():
are = {'clock': re.compile('[012]?\d\\\\:[0-5]\d')}
d = "("
for i in range(7):
d += calendar.day_abbr[i]
if i != 6:
d += '|'
d += '), ('
for i in range(1, 13):
d += calendar.month_name[i]
if i != 12:
d += '|'
d += ') [0123]\d'
are['date'] = re.compile(d, re.IGNORECASE)
are['battery'] = re.compile('Charging, \d\d%')
return are
CulebraOptions.AUTO_REGEXPS_RES = fillAutoRegexpsRes()
SB_NO_JAR = 'no-jar'
SB_JAR = 'jar'
SB_JAR_LINUX = 'jar-linux'
SHEBANG = {
SB_NO_JAR: '#! /usr/bin/env python3',
SB_JAR: '#! /usr/bin/env shebang monkeyrunner -plugin $ANDROID_VIEW_CLIENT_HOME/bin/androidviewclient-$ANDROID_VIEW_CLIENT_VERSION.jar @!',
SB_JAR_LINUX: '#! /usr/local/bin/shebang monkeyrunner -plugin $AVC_HOME/bin/androidviewclient-$AVC_VERSION.jar @!'
}
indent = ''
prefix = ''
def shortAndLongOptions():
'''
@return: the list of corresponding (short-option, long-option) tuples
'''
short_opts = CulebraOptions.SHORT_OPTS.replace(':', '')
if len(short_opts) != len(CulebraOptions.LONG_OPTS):
_s = ""
for i in range(max(len(short_opts), len(CulebraOptions.LONG_OPTS))):
l = ''
try:
l = short_opts[i]
except IndexError:
pass
L = ''
try:
L = CulebraOptions.LONG_OPTS[i]
except IndexError:
pass
_s += "%3s - %s\n" % (l, L)
raise Exception('There is a mismatch between short and long options: short=%d, long=%d\n%s' %
(len(short_opts), len(CulebraOptions.LONG_OPTS), _s))
t = tuple(short_opts) + tuple(CulebraOptions.LONG_OPTS)
l2 = int(len(t) / 2)
sl = []
for i in range(l2):
sl.append((t[i], t[i + l2]))
return sl
def usage(exitVal=1):
print(USAGE % progname, file=sys.stderr)
print("Try '%s --help' for more information." % progname, file=sys.stderr)
sys.exit(exitVal)
def _help():
print(USAGE % progname, file=sys.stderr)
print(file=sys.stderr)
print("Options:", file=sys.stderr)
for so, lo in shortAndLongOptions():
o = ' -%c, --%s' % (so, lo)
if lo[-1] == '=':
o += CulebraOptions.LONG_OPTS_ARG[lo[:-1]]
try:
o = '%-34s %-45s' % (o, CulebraOptions.OPTS_HELP[so])
except:
pass
print(o, file=sys.stderr)
sys.exit(0)
def version():
print(progname, __version__)
sys.exit(0)
def autoRegexpsHelp():
print("Available %s options:" % CulebraOptions.AUTO_REGEXPS, file=sys.stderr)
print("\thelp: prints this help", file=sys.stderr)
print("\tall: includes all the available regexps", file=sys.stderr)
for r in CulebraOptions.AUTO_REGEXPS_RES:
print("\t%s: %s" % (r, CulebraOptions.AUTO_REGEXPS_RES[r].pattern), file=sys.stderr)
print(file=sys.stderr)
sys.exit(0)
def concertinaConfigHelp():
print("Default Concertina configuration:", file=sys.stderr)
print(Concertina.getConcertinaConfigDefault(), file=sys.stderr)
sys.exit(0)
def error(msg, fatal=False):
print("%s: ERROR: %s" % (progname, msg), file=sys.stderr)
if fatal:
sys.exit(1)
def notNull(val, default):
if val:
return val
return default
def printVerboseComments(view):
"""
Prints the verbose comments for view.
"""
print('\n%s# class=%s' % (indent, view.getClass()), end=' ')
try:
text = view.getText()
if text:
u = 'u' if isinstance(text, str) else ''
if '\n' in text:
text = re.sub(r'\n(.)', r'\n#\1', text)
print(" text=%c'%s'" % (u, text), end=' ')
except:
pass
try:
contentDescription = view.getContentDescription()
if contentDescription:
print(" cd='%s'" % contentDescription, end=' ')
except:
pass
try:
tag = view.getTag()
if tag and tag != 'null':
print(' tag=%s' % tag, end=' ')
except:
pass
print()
def variableNameFromIdOrKey(view):
'''
Returns a suitable variable name from the id.
@type view: L{View}
@param id: the View from where the I{uniqueId} is obtained
@return: the variable name from the id
'''
var = View.variableNameFromId(view)
if options[CulebraOptions.USE_DICTIONARY]:
return '%sviews[\'%s\']' % (
prefix, notNull(dictionaryKeyFrom(options[CulebraOptions.DICTIONARY_KEYS_FROM], view), var))
else:
return var
def dictionaryKeyFrom(key, view):
if key == 'id':
return view.getUniqueId()
elif key == 'text':
return view.getText()
elif key == 'content-description':
return view.getContentDescription()
else:
raise Exception('Not a valid dictionary key: %s' % key)
def escapeRegexpSpecialChars(text):
return re.escape(text)
def printFindViewWithText(view, useregexp, op=Operation.ASSIGN, arg=None):
'''
Prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
if isinstance(view, View):
text = view.getText()
else:
text = view.text
isUnicode = isinstance(text, str)
if isUnicode and sys.stdout.encoding is None:
warnings.warn('''\
You are trying to print unicode characters to an unencoded stdout, it will probably fail.
You have to set PYTHONIOENCODING environment variable. For example:
export PYTHONIOENCODING=utf-8
''')
u = 'u' if isUnicode else ''
if text:
var = variableNameFromIdOrKey(view)
if text.find("\n") > 0 or text.find("'") > 0:
# 2 quotes + 1 quote = 3 quotes
text = "''%s''" % text
if useregexp:
# if there are special chars already in the text escape them
text = escapeRegexpSpecialChars(text)
if options[CulebraOptions.AUTO_REGEXPS]:
for r in options[CulebraOptions.AUTO_REGEXPS]:
autoRegexp = CulebraOptions.AUTO_REGEXPS_RES[r]
if autoRegexp.match(text):
text = autoRegexp.pattern
break
text = "re.compile(%s'%s')" % (u, text)
else:
text = "%s'%s'" % (u, text)
if op == Operation.ASSIGN:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('finding view with text=%s' % text)
print('%s%s = %svc.findViewWithTextOrRaise(%s)' % (indent, var, prefix, text))
elif op == Operation.LONG_TOUCH_VIEW:
root = ', root=%svc.findViewByIdOrRaise(\'%s\')' % (prefix, arg.getUniqueId()) if arg else ''
if options[CulebraOptions.MULTI_DEVICE]:
logAction('long touch view with text=%s on ${serialno}' % text)
print('%s[_vc.findViewWithTextOrRaise(%s%s).longTouch() for _vc in %sallVcs()]' % (
indent, text, root, prefix))
else:
logAction('long touch view with text=%s' % text)
print('%s%svc.findViewWithTextOrRaise(%s%s).longTouch()' % (indent, prefix, text, root))
elif op == Operation.TOUCH_VIEW:
root = ', root=%svc.findViewByIdOrRaise(\'%s\')' % (prefix, arg.getUniqueId()) if arg else ''
if options[CulebraOptions.MULTI_DEVICE]:
logAction('touching view with text=%s on ${serialno}' % text)
print('%s[_vc.findViewWithTextOrRaise(%s%s).touch() for _vc in %sallVcs()]' % (
indent, text, root, prefix))
else:
logAction('touching view with text=%s' % text)
print('%s%svc.findViewWithTextOrRaise(%s%s).touch()' % (indent, prefix, text, root))
elif op == Operation.TYPE:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%svc.findViewWithTextOrRaise("%s").type(u"%s")' % (indent, prefix, text, arg))
elif op == Operation.SET_TEXT:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%svc.findViewWithTextOrRaise(%s).setText(u"%s")' % (indent, prefix, text, arg))
elif op == Operation.SET_TEXT_UI_AUTOMATOR_HELPER:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'setting view with text={text}')
find_object_line = textwrap.indent(f'obj_ref = helper.until.find_object(body={view.obtain_selector()})',
' ' * 40,
lambda line: not line.startswith('obj_ref ='))
print(textwrap.dedent(f'''
{find_object_line}
response = helper.ui_device.wait(oid=obj_ref.oid)
helper.ui_object2.set_text(oid=response['oid'], text={text})'''))
elif op in [Operation.FLING_BACKWARD, Operation.FLING_FORWARD, Operation.FLING_TO_BEGINNING,
Operation.FLING_TO_END]:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
commandName = Operation.toCommandName(op)
logAction('flinging view with text=%s %s' % (text, commandName))
print('%s%svc.findViewWithTextOrRaise(%s).uiScrollable.%s()' % (indent, prefix, text, commandName))
elif op == Operation.TEST:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%sassertIsNotNone(%svc.findViewWithText(%s))' % (indent, prefix, prefix, text))
elif kwargs1[CulebraOptions.VERBOSE]:
warnings.warn('View with id=%s has no text' % view.getUniqueId())
def printFindViewWithContentDescription(view, useregexp, op=Operation.ASSIGN, arg=None):
'''
Prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
if isinstance(view, View):
contentDescription = view.getContentDescription()
else:
contentDescription = view.content_description
if contentDescription:
var = variableNameFromIdOrKey(view)
if useregexp:
if options[CulebraOptions.AUTO_REGEXPS]:
for r in options[CulebraOptions.AUTO_REGEXPS]:
autoRegexp = CulebraOptions.AUTO_REGEXPS_RES[r]
if autoRegexp.match(contentDescription):
contentDescription = autoRegexp.pattern
break
contentDescription = "re.compile(u'''%s''')" % contentDescription
else:
contentDescription = "u'''%s'''" % contentDescription
if op == Operation.ASSIGN:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('finding view with content-description=%s' % contentDescription)
print('%s%s = %svc.findViewWithContentDescriptionOrRaise(%s)' % (
indent, var, prefix, contentDescription))
elif op == Operation.LONG_TOUCH_VIEW:
if options[CulebraOptions.MULTI_DEVICE]:
logAction('long touch view with content-description=%s on ${serialno}' % contentDescription)
# print u'%s[_vc.findViewWithTextOrRaise(%s).touch() for _vc in %sallVcs()]' % (indent, text, root)
print('%s[_vc.findViewWithContentDescriptionOrRaise(%s).longTouch() for _vc in %sallVcs()]' % (
indent, contentDescription, prefix))
else:
logAction('long touch view with content-description=%s' % contentDescription)
print('%s%svc.findViewWithContentDescriptionOrRaise(%s).longTouch()' % (
indent, prefix, contentDescription))
elif op == Operation.TOUCH_VIEW:
if options[CulebraOptions.MULTI_DEVICE]:
logAction('touching view with content-description=%s on ${serialno}' % contentDescription)
# print u'%s[_vc.findViewWithTextOrRaise(%s).touch() for _vc in %sallVcs()]' % (indent, text, root)
print('%s[_vc.findViewWithContentDescriptionOrRaise(%s).touch() for _vc in %sallVcs()]' % (
indent, contentDescription, prefix))
else:
logAction('touching view with content-description=%s' % contentDescription)
print('%s%svc.findViewWithContentDescriptionOrRaise(%s).touch()' % (indent, prefix, contentDescription))
elif op == Operation.TYPE:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%svc.findViewWithContentDescriptionOrRaise(%s).type(u"%s")' % (
indent, prefix, contentDescription, arg))
elif op == Operation.SET_TEXT:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%svc.findViewWithContentDescriptionOrRaise(%s).setText(u"%s")' % (
indent, prefix, contentDescription, arg))
elif op == Operation.TEST:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%sassertEquals(%svc.findViewWithContentDescriptionOrRaise(%s).getText(), u\'\'\'%s\'\'\')' % (
indent, prefix, prefix, contentDescription, arg))
elif op in [Operation.FLING_BACKWARD, Operation.FLING_FORWARD, Operation.FLING_TO_BEGINNING,
Operation.FLING_TO_END]:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
commandName = Operation.toCommandName(op)
logAction('flinging view with content-description=%s %s' % (contentDescription, commandName))
print('%s%svc.findViewWithContentDescriptionOrRaise(%s).uiScrollable.%s()' % (
indent, prefix, contentDescription, commandName))
else:
error("Invalid operation in %s: %s" % (sys._getframe().f_code.co_name), op)
elif kwargs1[CulebraOptions.VERBOSE]:
warnings.warn('View with id=%s has no content-description' % view.getUniqueId())
def printFindViewById(view, op=Operation.ASSIGN, arg=None):
'''
Prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
if isinstance(view, View):
_id = view.getId() or view.getUniqueId()
else:
_id = view.resource_id or view.unique_id
var = variableNameFromIdOrKey(view)
if op == Operation.ASSIGN:
if options[CulebraOptions.MULTI_DEVICE]:
logAction('finding view with id=%s on ${serialno}' % _id)
print('%s%s = [_vc.findViewByIdOrRaise("%s") for _vc in %sallVcs()]' % (indent, var, _id, prefix))
else:
logAction('finding view with id=%s' % _id)
print('%s%s = %svc.findViewByIdOrRaise("%s")' % (indent, var, prefix, _id))
elif op == Operation.LONG_TOUCH_VIEW:
if options[CulebraOptions.MULTI_DEVICE]:
logAction('long touch view with id=%s on ${serialno}' % _id)
print('%s[_vc.findViewByIdOrRaise("%s").longTouch() for _vc in %sallVcs()]' % (indent, _id, prefix))
else:
logAction('long touch view with id=%s' % _id)
print('%s%svc.findViewByIdOrRaise("%s").longTouch()' % (indent, prefix, _id))
elif op == Operation.TOUCH_VIEW:
if options[CulebraOptions.MULTI_DEVICE]:
logAction('touching view with id=%s on ${serialno}' % _id)
print('%s[_vc.findViewByIdOrRaise("%s").touch() for _vc in %sallVcs()]' % (indent, _id, prefix))
else:
logAction('touching view with id=%s' % _id)
print('%s%svc.findViewByIdOrRaise("%s").touch()' % (indent, prefix, _id))
elif op == Operation.TYPE:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('typing "%s" on view with id=%s' % (arg, _id))
print('%s%svc.findViewByIdOrRaise("%s").type(u"%s")' % (indent, prefix, _id, arg))
elif op == Operation.SET_TEXT:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('setting text "%s" on view with id=%s' % (arg, _id))
print('%s%svc.findViewByIdOrRaise("%s").setText(u"%s")' % (indent, prefix, _id, arg))
elif op == Operation.TEST:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%sassertEquals(%svc.findViewByIdOrRaise("%s").getText(), u\'\'\'%s\'\'\')' % (
indent, prefix, prefix, _id, arg))
elif op in [Operation.FLING_BACKWARD, Operation.FLING_FORWARD, Operation.FLING_TO_BEGINNING,
Operation.FLING_TO_END]:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
commandName = Operation.toCommandName(op)
logAction('flinging view with id=%s %s' % (_id, commandName))
print('%s%svc.findViewWithIdOrRaise(u"%s").uiScrollable.%s()' % (indent, prefix, _id, commandName))
else:
error("Invalid operation in %s: %s" % (sys._getframe().f_code.co_name, op))
def printTraverse(dump=None):
'''
Prints the result of traversing the tree.
A previously obtained dump can be passed as a parameter and in such case that
tree is used.
@param dump: Dump of Views previously obtained via L{ViewClient.dump()}
@type dump: list
'''
print()
if dump:
for view in dump:
transform(view)
else:
vc.traverse(transform=transform)
print()
def printDump(window, dump=None):
'''
Prints a dump.
@param window: The window id to use to print the dump
@type window: int or str
@param dump: Dump of Views previously obtained via L{ViewClient.dump()}
@type dump: list
'''
print('🐸 culebra.printDump', file=sys.stderr)
if options[CulebraOptions.MULTI_DEVICE]:
logAction('dumping content of window=%s on ${serialno}' % window)
print('%s[_vc.dump(window=%s) for _vc in %sallVcs()]' % (indent, window, prefix))
else:
logAction('dumping content of window=%s' % window)
print('%s%svc.dump(window=%s)' % (indent, prefix, window))
if not options[CulebraOptions.DO_NOT_VERIFY_SCREEN_DUMP]:
if DEBUG:
print('printing dump: %s' % dump.__class__.__name__)
printTraverse(dump)
def printSleep(secs):
'''
Prints a sleep.
This method relies on shortcut variables being set (i.e. _s)
'''
if options[CulebraOptions.MULTI_DEVICE]:
print('%s[_vc.sleep(%s) for _vc in %sallVcs()]' % (indent, secs if secs != Operation.DEFAULT else '_s', prefix))
else:
print('%s%svc.sleep(%s)' % (indent, prefix, secs if secs != Operation.DEFAULT else '_s'))
def printSleepUiAutomatorHelper(secs=5):
"""
Prints a sleep.
"""
if options[CulebraOptions.MULTI_DEVICE]:
print(f'{indent}[_vc.sleep({secs}) for _vc in %sallVcs()]')
else:
print(f'{indent}time.sleep({secs})')
def printWake():
'''
Prints a wake.
:return:
'''
if options[CulebraOptions.MULTI_DEVICE]:
print('%s[_vc.device.wake() for _vc in %sallVcs()]' % (indent, prefix))
else:
print('%s%svc.device.wake()' % (indent, prefix))
def printSay(text):
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%sViewClient.sayText("%s")' % (indent, text))
def printPress(keycode):
'''
Prints a key press
'''
if options[CulebraOptions.MULTI_DEVICE]:
logAction('pressing key=%s on ${serialno}' % keycode)
print('%s[_d.press(\'%s\') for _d in %sallDevices()]' % (indent, keycode, prefix))
else:
logAction('pressing key=%s' % keycode)
print('%s%sdevice.press(\'%s\')' % (indent, prefix, keycode))
def printDrag(start, end, duration, steps, unit, orientation):
'''
Prints a drag
'''
if unit == Unit.PX:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%sdevice.drag(%s, %s, %d, %d, %d)' % (indent, prefix, start, end, duration, steps, orientation))
elif unit == Unit.DIP:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('%s%sdevice.dragDip(%s, %s, %d, %d, %d)' % (indent, prefix, start, end, duration, steps, orientation))
else:
raise RuntimeError('Invalid unit: %s' % unit)
def printTouch(x, y, unit, orientation):
'''
Prints a touch
'''
if unit == Unit.PX:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('touching point by PX @ (%s, %s) orientation=%s' % (x, y, orientation))
print('%s%sdevice.touch(%s, %s, %s)' % (indent, prefix, x, y, orientation))
elif unit == Unit.DIP:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('touching point by DIP @ (%s, %s) orientation=%s' % (x, y, orientation))
print('%s%sdevice.touchDip(%s, %s, %s)' % (indent, prefix, x, y, orientation))
else:
raise RuntimeError('Invalid unit: %s' % unit)
def printLongTouch(x, y, duration, unit, orientation):
'''
Prints a long touch
'''
if unit == Unit.PX:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(
'long touching point by PX @ (%s, %s) duration=%s orientation=%s' % (x, y, duration, orientation))
print('%s%sdevice.longTouch(%s, %s, %s, %s)' % (indent, prefix, x, y, duration, orientation))
elif unit == Unit.DIP:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(
'long touching point by DIP @ (%s, %s) duration=%s orientation=%s' % (x, y, duration, orientation))
print('%s%sdevice.longTouch(%s, %s, %s, %s)' % (indent, prefix, x, y, duration, orientation))
else:
raise RuntimeError('Invalid unit: %s' % unit)
def printSaveViewScreenshot(view, filename, _format):
'''
Prints the writeImageToFile for the specified L{View}.
@type view: L{View}
@param view: the View
@type filename: str
@param filename: the filename to store the image
@type _format: str
@param _format: The image format (i.e. PNG)
'''
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
# FIXME: if -u was passed in the command line then we are not saving the variables and thus
# next line will generate an error in the script as the variable is 'undefined'
print('%s%s.writeImageToFile(\'%s\', \'%s\')' % (indent, View.variableNameFromId(view), filename, _format))
def printFlingBackward(view):
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
# FIXME: if -u was passed in the command line then we are not saving the variables and thus
# next line will generate an error in the script as the variable is 'undefined'
logAction('flinging backward view with id=%s' % view.getId())
print('%s%s.uiScrollable.flingBackward()' % (indent, view.variableNameFromId()))
def printFlingForward(view):
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
# FIXME: if -u was passed in the command line then we are not saving the variables and thus
# next line will generate an error in the script as the variable is 'undefined'
logAction('flinging forward view with id=%s' % view.getId())
print('%s%s.uiScrollable.flingForward()' % (indent, view.variableNameFromId()))
def printFlingToBeginning(view):
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
# FIXME: if -u was passed in the command line then we are not saving the variables and thus
# next line will generate an error in the script as the variable is 'undefined'
logAction('flinging to beginning view with id=%s' % view.getId())
print('%s%s.uiScrollable.flingToBeginning()' % (indent, view.variableNameFromId()))
def printFlingToEnd(view):
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
# FIXME: if -u was passed in the command line then we are not saving the variables and thus
# next line will generate an error in the script as the variable is 'undefined'
logAction('flinging to end view with id=%s' % view.getId())
print('%s%s.uiScrollable.flingToEnd()' % (indent, view.variableNameFromId()))
def printOpenNotification():
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('opening Notification')
print('%s%svc.uiDevice.openNotification()' % (indent, prefix))
def printOpenQuickSettings():
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('opening Quick Settings')
print('%s%svc.uiDevice.openQuickSettings()' % (indent, prefix))
def printChangeLanguage(code):
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('Changing language to %s' % code)
print('%s%svc.uiDevice.changeLanguage("%s")' % (indent, prefix, code))
def printTakeSnapshot(filename, _format, deviceart, dropshadow, screenglare):
'''
Prints the corresponding writeImageToFile() to take a snapshot
'''
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('taking snapshot @ %s format=%s %s %s %s' % (filename, _format, deviceart, dropshadow, screenglare))
if deviceart:
deviceart = '\'%s\'' % deviceart
print('%s%svc.writeImageToFile(\'%s\', \'%s\', %s, %s, %s)' % (
indent, prefix, filename, _format, deviceart, dropshadow, screenglare))
def printTakeSnapshotUiAutomatorHelper(filename, _format='PNG'):
'''
Prints the corresponding take_screenshot() to take a snapshot
'''
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'taking screenshot @ {filename} format={_format}')
print(f'{indent}{prefix}helper.ui_device.take_screenshot(filename=f\'{filename}\')')
def traverseAndPrint(view):
'''
Traverses the View tree and prints the corresponding statement.
@type view: L{View}
@param view: the View
'''
if DEBUG:
print("🐞 culebra.traverseAndPrint(view=%s)" % view.id, file=sys.stderr)
if type(view) == WindowHierarchy:
# The root element is a WindowHierarchy (id=hierarchy)
return
if vc.uiAutomatorHelper:
printFindObjectUiAutomatorViewer(view.obtain_selector())
else:
if options[CulebraOptions.VERBOSE_COMMENTS]:
printVerboseComments(view)
if options[CulebraOptions.FIND_VIEWS_BY_ID]:
printFindViewById(view)
if options[CulebraOptions.FIND_VIEWS_WITH_TEXT]:
printFindViewWithText(view, options[CulebraOptions.USE_REGEXPS])
if options[CulebraOptions.FIND_VIEWS_WITH_CONTENT_DESCRIPTION]:
printFindViewWithContentDescription(view, options[CulebraOptions.USE_REGEXPS])
if options[CulebraOptions.SAVE_VIEW_SCREENSHOTS]:
_format = 'PNG'
filename = options[
CulebraOptions.SAVE_VIEW_SCREENSHOTS] + os.sep + View.variableNameFromId(
view) + '.' + _format.lower()
printSaveViewScreenshot(view, filename, _format)
def printStartActivity(component):
'''
Prints the corresponding startActivity().
:param component: the component
'''
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('starting activity=%s' % (component))
print('%s%sdevice.startActivity(\'%s\')' % (indent, prefix, component))
printSleep(3)
def printStartActivityUiAutomatorHelper(component):
"""
Prints the corresponding startActivity().
:param component: the component
"""
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'starting activity={component}')
pkg, cls = component.split('/')
print(f'{indent}{prefix}helper.target_context.start_activity(\'{pkg}\', \'{cls}\')')
def printTouchViewUiAutomatorHelper(selector: culebratester_client.Selector) -> None:
"""
Prints the corresponding touch
"""
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'touching by selector={selector}')
indented_line = None
indentation = indent + ' ' * 40
# FIXME: should be find_objects and before clicking we should verify the list contains
# only 1 object, otherwise we aren't sure which one is being clicked
for line in f'{indent}obj_ref = {prefix}helper.until.find_object(body={selector})'.splitlines():
if not indented_line:
indented_line = line
else:
indented_line = f'{indented_line}\n{indentation}{line}'
print('')
print(f'{indented_line}')
print(f'{indent}response = {prefix}helper.ui_device.wait(oid=obj_ref.oid)')
print(f'{indent}{prefix}helper.ui_object2.click(oid=response[\'oid\'])')
def printLongTouchViewUiAutomatorHelper(selector):
"""
Prints the corresponding long touch
"""
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'long-touching by selector={selector}')
printFindObjectUiAutomatorViewer(selector)
print(f'{indent}{prefix}helper.ui_object2.long_click(oid=obj_ref.oid)')
def printFindObjectUiAutomatorViewer(selector):
indented_line = None
indentation = indent + ' ' * 4
for line in f'{indent}obj_ref = {prefix}helper.ui_device.find_object(body={selector})'.splitlines():
if not indented_line:
indented_line = line
else:
indented_line = f'{indented_line}\n{indentation}{line}'
print(f'{indented_line}')
def printSwipeUiAutomatorHelper(startX, startY, endX, endY, steps, orientation, unit=Unit.PX):
"""
Prints a swipe
"""
if unit == Unit.PX:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
print('')
print(
f'{indent}{prefix}helper.ui_device.swipe(start_x={int(startX)}, start_y={int(startY)}, ' +
f'end_x={int(endX)}, end_y={int(endY)}, steps={int(steps)})')
elif unit == Unit.DIP:
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
warnings.warn(f'Swipe using {unit} is not implemented yet')
print('')
print(
f'{indent}{prefix}helper.ui_device.swipe(start_x={int(startX)}, start_y={int(startY)}, ' +
f'end_x={int(endX)}, end_y={int(endY)}, steps={int(steps)})')
else:
raise RuntimeError('Invalid unit: %s' % unit)
def printPressBackUiAutomatorHelper():
'''
Prints the corresponding press
'''
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('pressing BACK')
print('%s%svc.pressBack()' % (indent, prefix))
def printPressHomeUiAutomatorHelper():
'''
Prints the corresponding press
'''
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('pressing HOME')
print('%s%svc.pressHome()' % (indent, prefix))
def printPressRecentAppsUiAutomatorHelper():
'''
Prints the corresponding press
'''
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction('pressing RECENT APPS')
print('%s%svc.pressRecentApps()' % (indent, prefix))
def printLongPress(keycode, duration, dev, scancode, repeat):
'''
Prints a key long press
'''
if options[CulebraOptions.MULTI_DEVICE]:
logAction('long pressing key=%s on ${serialno}' % keycode)
print('%s[_d.longPress(\'%s\', duration=%f, dev=\'%s\', scancode=%d, repeat=%d) for _d in %sallDevices()]' % (
indent, keycode, duration, dev, scancode, repeat, prefix))
else:
logAction('long pressing key=%s' % keycode)
print('%s%sdevice.longPress(\'%s\', duration=%f, dev=\'%s\', scancode=%d, repeat=%d)' % (
indent, prefix, keycode, duration, dev, scancode, repeat))
def printPressUiAutomatorHelper(keycode):
"""
Prints the corresponding press
"""
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'pressing {keycode}')
print('')
print(f'{indent}{prefix}helper.ui_device.press_key_code(KEY_EVENT[\'{keycode}\'])')
printWaitForWindowUpdateUiAutomatorHelper()
def printWaitForIdleUiAutomatorHelper():
"""
Prints the corresponding wait for idle
"""
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'waiting for idle')
print(f'{indent}{prefix}helper.ui_device.wait_for_idle()')
def printWaitForWindowUpdateUiAutomatorHelper():
"""
Prints the corresponding wait for window update
"""
if options[CulebraOptions.MULTI_DEVICE]:
warnings.warn('Multi-device not implemented yet for this case')
else:
logAction(f'waiting for idle')