forked from AirtestProject/Airtest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui.py
309 lines (254 loc) · 10.8 KB
/
ui.py
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
# coding=utf-8
__author__ = 'lxn3032'
import time
import traceback
from pprint import pprint
import airtest.cli.runner
import airtest.core.api
from airtest.core.api import set_serialno, snapshot, logwrap
from airtest.core.helper import log_in_func,G
from uiautomator import AutomatorDevice
__all__ = ['UiAutomator']
PRIMARY_ACTION = ['click', 'long_click', 'swipe', 'drag', 'fling', 'scroll', 'press', 'clear_text', 'set_text', 'assert']
SECONDARY_ACTIONS = {
'press': ['home', 'back', 'left', 'right', 'up', 'down', 'center', 'menu', 'search', 'enter', 'delete', 'del',
'volumn_up', 'volumn_down', 'volumn_mute', 'camera', 'power'],
'swipe': ['left', 'right', 'top', 'bottom'],
'drag': ['to'],
'open': ['notification', 'quick_settings'],
'click': ['bottomright', 'topleft', 'wait'],
'long_click': ['bottomright', 'topleft'],
'pinch': ['In', 'Out'],
'wait': ['exists', 'gone'],
'fling': ['forward', 'backward', 'toBeginning', 'toEnd'],
'scroll': ['forward', 'backward', 'toBeginning', 'toEnd', 'to'],
'gesture': ['to'],
}
TERTIARY_ACTION = {
'fling': {
'horiz': ['forward', 'backward', 'toBeginning', 'toEnd'],
'vert': ['forward', 'backward', 'toBeginning', 'toEnd'],
},
'scroll': {
'horiz': ['forward', 'backward', 'toBeginning', 'toEnd', 'to'],
'vert': ['forward', 'backward', 'toBeginning', 'toEnd', 'to'],
}
}
SELECTOR_ARGS = ['text', 'textContains', 'textMatches', 'textStartsWith',
'className', 'classNameMatches',
'description', 'descriptionContains', 'descriptionMatches', 'descriptionStartsWith',
'checkable', 'checked', 'clickable', 'longClickable',
'scrollable', 'enabled', 'focusable', 'focused', 'selected',
'packageName', 'packageNameMatches',
'resourceId', 'resourceIdMatches',
'index', 'instance']
QUERY_ACTION = ['info', 'exists', 'count', 'dump', 'screenshot', 'freeze_rotation'] + SELECTOR_ARGS
log = []
action_stack = []
def genlog(action, params, uiobj=None):
global log, action_stack
# transform action names
# avoid conflicting with airtest actions
if action == 'swipe':
action = 'ui.swipe'
pprint(log)
@logwrap
def command_layer(action, params):
traverse_layer(action, params)
log_in_func({"name": action, 'ret': None})
@logwrap
def traverse_layer(action, params):
snapshot()
if uiobj and 'visibleBounds' in uiobj:
b = uiobj['visibleBounds']['bottom']
l = uiobj['visibleBounds']['left']
r = uiobj['visibleBounds']['right']
t = uiobj['visibleBounds']['top']
if params and params[-1] == "topleft": # 点击识别区域的左上角
x, y = l, t
elif params and params[-1] == "bottomright": # 点击识别区域的右下角
x, y = r, b
else: # 点击中间位置
x, y = (l + r) / 2, (b + t) / 2
log_in_func({
"cv": {"confidence": 1, "result": [x, y], "rectangle": [[l, t], [l, b], [r, b], [r, t]]},
'ret': [x, y],
})
command_layer(action, params)
log = []
action_stack = []
def try_call(f, action, *args, **kwargs):
try:
return f(*args, **kwargs)
except Exception:
log_error(action, traceback.format_exc(), *args, **kwargs)
raise
def try_getattr(obj, attr, action, *args, **kwargs):
try:
return getattr(obj, attr)
except Exception:
log_error(action, traceback.format_exc(), *args, **kwargs)
raise
def log_error(action, tb, *args, **kwargs):
logger = airtest.core.api.LOGGER
start = time.time()
fndata = {'name': action, 'args': args, 'kwargs': kwargs}
logger.running_stack.append(fndata)
fndata.update({"traceback": tb, "time_used": time.time() - start})
logger.log("error", fndata)
logger.running_stack.pop()
class AutomatorAssertionFail(Exception):
pass
class AutomatorWrapper(object):
def __init__(self, obj, parent=None, assertion=None):
super(AutomatorWrapper, self).__init__()
self.obj = obj
self.parent = parent # prev layer obj
self.selectors = None
self.select_action = None
self.assertion = assertion
def __getattr__(self, action):
global log, action_stack
assertion = None
if action.startswith('assert_not_'):
assertion = 'assert_not_'
action = action[len(assertion):]
elif action.startswith('assert_'):
assertion = 'assert_'
action = action[len(assertion):]
important = True
is_key_action = False
if action in PRIMARY_ACTION:
is_key_action = True
if action in QUERY_ACTION and not assertion:
important = False
if important:
action_stack.append(action)
if is_key_action:
log.append({'primary-action': action})
else:
log.append({'action': action})
attr = getattr(self.obj, action)
if callable(attr) or assertion:
return self.__class__(attr, self, assertion=assertion)
else:
return attr
def __call__(self, *args, **kwargs):
global log, action_stack
calling = None
# handle assertion expr
assert_value = False if self.assertion == 'assert_not_' else True
if self.assertion:
action = action_stack[-1]
assert_result = self.obj == assert_value
prev_selector_obj = self._get_selector_obj()
# 必须预先判断所选对象是否存在,不存在的对象调用info属性时会抛出uiautomator.UiObjectNotFoundException
# 因为即使是assert_not_checked时,也是可以获取对象info的
if prev_selector_obj.obj.exists:
uiobj = prev_selector_obj.obj.info
else:
uiobj = None
assert_action = self.assertion + action
genlog('assert', [assert_action, prev_selector_obj.selectors, assert_result] + list(args), uiobj)
if not assert_result:
try:
raise AutomatorAssertionFail('assert failed of {}, require {}, got {}'.format(assert_action, assert_value, self.obj))
except AutomatorAssertionFail:
log_error('assert', traceback.format_exc(), assert_action, prev_selector_obj.selectors, assert_result, *args, **kwargs)
raise
return None
# handle selector expr
if args or kwargs:
if all([k in SELECTOR_ARGS for k in kwargs]):
# get this select action name
if len(action_stack) >= 1:
action = action_stack[-1]
else:
action = 'global'
# relative selector
prev_selector_obj = self._get_selector_obj()
if prev_selector_obj:
uiobj = try_getattr(prev_selector_obj.obj, 'info', prev_selector_obj.select_action, prev_selector_obj.selectors)
genlog('select', [prev_selector_obj.select_action, prev_selector_obj.selectors], uiobj)
calling = try_call(self.obj, action, *args, **kwargs)
ret = self.__class__(calling, self)
ret.selectors = (args, kwargs) if args else kwargs
ret.select_action = action
return ret
# 其他操作的log记录
action, params = None, None
if args or kwargs:
last_log = list(args) or kwargs.values()
else:
last_log = []
if len(action_stack) >= 3 and action_stack[-3] in TERTIARY_ACTION:
taction = TERTIARY_ACTION[action_stack[-3]]
if action_stack[-2] in taction:
saction = taction[action_stack[-2]]
if action_stack[-1] in saction:
action = action_stack[-3]
params = action_stack[-2:] + last_log
if len(action_stack) >= 2 and action_stack[-2] in SECONDARY_ACTIONS:
secondary_action = SECONDARY_ACTIONS[action_stack[-2]]
if action_stack[-1] in secondary_action:
action = action_stack[-2]
params = action_stack[-1:] + last_log
if len(action_stack) >= 1 and action_stack[-1] in PRIMARY_ACTION:
action = action_stack[-1]
params = last_log
if action:
# select操作log记录
selector_obj = self._get_selector_obj()
uiobj = None
if selector_obj:
uiobj = try_getattr(selector_obj.obj, 'info', selector_obj.select_action, selector_obj.selectors)
genlog('select', [selector_obj.select_action, selector_obj.selectors], uiobj)
genlog(action, params, uiobj)
if not calling:
calling = try_call(self.obj, 'action', *args, **kwargs)
return self.__class__(calling, self)
def __len__(self):
return len(self.obj)
def __nonzero__(self):
""" python 2 only, for python 3, please override __bool__
"""
return bool(self.obj)
def __getitem__(self, item):
return self.__class__(self.obj[item], self)
def __iter__(self):
objs, length = self, len(self)
class Iter(object):
def __init__(self):
self.index = -1
def next(self):
self.index += 1
if self.index < length:
return objs[self.index]
else:
raise StopIteration()
__next__ = next
return Iter()
def _get_selector_obj(self):
# 下面的is not None的判断方法有点特殊
# 因为该类实现了bool隐式转换接口,如果不这样判断的话,在and表达式返回时,还会自动bool隐式转换一次
# 导致条件判断非预期
ret = None
if self.selectors:
ret = self
elif (self.parent and self.parent.selectors) is not None:
ret = self.parent
elif (self.parent and self.parent.parent and self.parent.parent.selectors) is not None:
ret = self.parent.parent
elif (self.parent and self.parent.parent and self.parent.parent.parent and self.parent.parent.parent.selectors) is not None:
ret = self.parent.parent.parent
return ret
def end(self):
time.sleep(1)
genlog('end', [], None)
def UiAutomator():
current_device = airtest.cli.runner.device()
if not current_device:
set_serialno()
current_device = airtest.cli.runner.device()
dev = AutomatorDevice(current_device.serialno)
return AutomatorWrapper(dev)