-
Notifications
You must be signed in to change notification settings - Fork 1
/
appium_client.py
executable file
·493 lines (402 loc) · 17.8 KB
/
appium_client.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
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
import urllib3
import json
import os
from datetime import datetime, timedelta
class ElementNotFoundException(Exception):
'''
An exception thrown when the element can not be found.
:arg details: A free form text message.
'''
def __init__(self, details):
if isinstance(details, str):
details = {'message': details}
Exception.__init__(self, details)
class UnknownUiServerException(Exception):
'''
An exception thrown when in below situation:
- The given Ui Selector can not be parsed
- Requested attribute {0} not supported
- Unknown internal server error
:arg details: A free form text message.
'''
def __init__(self, details):
if isinstance(details, str):
details = {'message': details}
Exception.__init__(self, details)
class InvalidCoordinatesException(Exception):
'''
An exception thrown when the coordinates provided to an interactions
operation are invalid.
:arg details: A free form text message.
'''
def __init__(self, details):
if isinstance(details, str):
details = {'message': details}
Exception.__init__(self, details)
class JsonDecoderError(Exception):
'''
An exception thrown when could not decode action/params of command
:arg details: A free form text message.
'''
def __init__(self, details):
if isinstance(details, str):
details = {'message': details}
Exception.__init__(self, details)
class ByText(dict):
def __init__(self, varg):
self['strategy'] = '-android uiautomator'
self['selector'] = 'new UiSelector().text(\"%s\");' % varg
class ById(dict):
def __init__(self, varg):
self['strategy'] = 'id'
self['selector'] = varg
class ByDesc(dict):
def __init__(self, varg):
self['strategy'] = 'accessibility id'
self['selector'] = varg
class ByClass(dict):
def __init__(self, varg):
self['strategy'] = 'class name'
self['selector'] = varg
class ByXpath(dict):
def __init__(self, varg):
self['strategy'] = 'xpath'
self['selector'] = varg
class ByUiautomator(dict):
def __init__(self, varg):
self['strategy'] = '-android uiautomator'
self['selector'] = varg
class RequestHandler(object):
base_url = 'http://localhost:'
pool = None
headers = {"Content-Type": "application/json"}
def __init__(self, port):
self.base_url = self.base_url + port
self.pool = urllib3.PoolManager()
def get(self, path):
url = self.base_url + path
return self.request_handler('GET', url)
def post(self, path, body):
url = self.base_url + path
return self.request_handler('POST', url, body=body)
def delete(self, path, body):
url = self.base_url + path
return self.request_handler('DELETE', url, body=body)
def wait_for_netty(self):
limit = datetime.now() + timedelta(seconds=30)
unsuccessful = True
while True:
try:
self.get('/wd/hub/status')
unsuccessful = False
except Exception:
# Waiting for server ...
pass
if not unsuccessful or datetime.now() > limit:
break
if unsuccessful:
raise Exception("Failed to contact io.appium.uiautomator2.server on " + self.base_url)
def netty(self):
try:
self.get('/wd/hub/status')
return True
finally:
return False
def request_handler(self, method, url, body=None):
try:
if method == 'GET':
r = self.pool.urlopen('GET', url, headers=self.headers)
else:
r = self.pool.urlopen(method, url, body=body, headers=self.headers)
except Exception as e:
raise Exception("Failed to connect Appium Server: %s" % e)
if r.status == 200:
return r.data.decode('utf8')
elif r.status == 301:
raise Exception('The request: %s %s moved Permanently') % (method, url)
elif r.status == 404:
raise Exception('The request: %s %s not found.') % (method, url)
elif r.status == 500:
data = json.loads(r.data.decode('utf8'))
if data['status'] == 7:
raise ElementNotFoundException('Could not locate the element: %s' % body)
elif data['status'] in [9, 10, 13, 21, 23, 32]:
msg = {'method': '%s "%s" ' % (method, url), 'body': body.decode('utf-8'), 'status': data['status'],
'error': data['value']}
raise UnknownUiServerException(json.dumps(msg).encode('utf-8'))
elif data['status'] == 29:
msg = {'method': '%s "%s" ' % (method, url), 'body': body.decode('utf-8'), 'error': data['value']}
raise InvalidCoordinatesException(json.dumps(msg).encode('utf-8'))
elif data['status'] == 35:
msg = {'method': '%s "%s" ' % (method, url), 'body': body.decode('utf-8'), 'error': data['value']}
raise JsonDecoderError(json.dumps(msg).encode('utf-8'))
class AppiumClient(object):
prefix_path = '/wd/hub/session'
base_path = None
rpc = None
def __init__(self, port=6790):
self.rpc = RequestHandler(port)
self.base_path = os.path.join(self.prefix_path, self._create_session())
def netty(self):
return self.rpc.netty()
def find_element(self, data):
url = self.base_path + '/element'
data['context'] = ''
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']['ELEMENT']
def find_elements(self, data):
url = self.base_path + '/elements'
data['context'] = ''
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
element_ids = []
for element in json.loads(response)['value']:
element_ids.append(element['ELEMENT'])
return element_ids
def find_child_element(self, f_data, c_data):
url = self.base_path + '/element'
c_data['context'] = self.find_element(f_data)
encoded_data = json.dumps(c_data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']['ELEMENT']
def find_child_elements(self, f_data, c_data):
url = self.base_path + '/elements'
c_data['context'] = self.find_element(f_data)
encoded_data = json.dumps(c_data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
element_ids = []
for element in json.loads(response)['value']:
element_ids.append(element['ELEMENT'])
return element_ids
def click_element(self, element_id):
url = self.base_path + '/element/' + element_id + '/click'
data = {'element': element_id}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def scroll_forward_on_element(self, element_id, is_vertical_list=True):
url = self.base_path + '/element/' + element_id + '/scroll_forward_on_view'
data = {'is_vertical_list': is_vertical_list}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def scroll_backward_on_element(self, element_id, is_vertical_list=True):
url = self.base_path + '/element/' + element_id + '/scroll_backward_on_view'
data = {'is_vertical_list': is_vertical_list}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def scroll_to_text_on_element(self, element_id, text, is_vertical_list=True):
url = self.base_path + '/element/' + element_id + '/scroll_to_text_on_view'
data = {'text': text, 'is_vertical_list': is_vertical_list}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def scroll_to_sub_text_on_element(self, element_id, text, is_vertical_list=True):
url = self.base_path + '/element/' + element_id + '/scroll_to_sub_text_on_view'
data = {'text': text, 'is_vertical_list': is_vertical_list}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def scroll_to_text_regex_on_element(self, element_id, regex, is_vertical_list=True):
url = self.base_path + '/element/' + element_id + '/scroll_to_text_reg_on_view'
data = {'regex': regex, 'is_vertical_list': is_vertical_list}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def wait_for_element(self, by, timeout):
limit = datetime.now() + timedelta(seconds=timeout)
found_status = False
while True:
try:
self.find_element(by)
found_status = True
except ElementNotFoundException:
pass
finally:
raise
if found_status or datetime.now() > limit:
break
return found_status
def wait_for_element_invisible(self, by, timeout):
limit = datetime.now() + timedelta(seconds=timeout)
exist = True
while True:
try:
self.find_element(by)
except ElementNotFoundException:
exist = False
finally:
raise
if not exist or datetime.now() > limit:
break
return not exist
def delete_session(self):
data = {}
encoded_data = json.dumps(data).encode('utf-8')
return self.rpc.delete(self.base_path, encoded_data)
def _create_session(self):
data = {'desiredCapabilities': {}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post('/wd/hub/session', encoded_data)
return json.loads(response)['sessionId']
def wait_for_netty(self):
self.rpc.wait_for_netty()
def get_size(self, element_id):
url = self.base_path + '/element/' + element_id + '/size'
response = self.rpc.get(url)
return json.loads(response)['value']
def get_text(self, element_id):
url = self.base_path + '/element/' + element_id + '/text'
response = self.rpc.get(url)
return json.loads(response)['value']
def long_click(self, element_id, duration=1):
url = self.base_path + '/touch/longclick'
data = {'params': {'element': element_id, 'duration': duration * 1000}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
if json.loads(response)['status'] == 0:
return True
else:
return False
def rotate_screen(self, orientation):
if orientation.upper() not in ['LANDSCAPE', 'PORTRAIT']:
raise Exception('the para is not right, it must be \'LANDSCAPE\' or \'PORTRAIT\'')
url = self.base_path + '/orientation'
data = {'orientation': orientation}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def scroll_to(self, scroll_to_text, index=0, is_vertical_list=True):
url = self.base_path + '/touch/scroll'
data = {'text': scroll_to_text, 'index': index, 'is_vertical_list': is_vertical_list}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def scroll_on_screen(self, direction, index=0, is_vertical_list=True):
url = self.base_path + '/touch/scroll_on_screen'
data = {'direction': direction, 'index': index, 'is_vertical_list': is_vertical_list}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
if json.loads(response)['status'] == 0:
return True
else:
return False
def set_text(self, element_id, text):
url = self.base_path + '/element/' + element_id + '/value'
data = {'element': element_id, 'text': text, 'replace': False}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
if json.loads(response)['status'] == 0:
return True
else:
return False
def set_rotation(self, z):
if z not in [0, 90, 180, 270]:
raise Exception('the para is not right, it must be in (0, 90, 180, 270)')
url = self.base_path + '/rotation'
data = {'x': 0, 'y': 0, 'z': z}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def tap(self, x, y):
url = self.base_path + '/appium/tap'
data = {'x': x, 'y': y}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def swipe(self, x1, y1, x2, y2, steps):
url = self.base_path + '/touch/perform'
data = {'startX': x1, 'startY': y1, 'endX': x2, 'endY': y2, 'steps': steps}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def touch_down_element(self, element_id):
url = self.base_path + '/touch/down'
data = {'params': {'element': element_id}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def touch_up_element(self, element_id):
url = self.base_path + '/touch/up'
data = {'params': {'element': element_id}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def touch_move_element(self, element_id):
url = self.base_path + '/touch/move'
data = {'params': {'element': element_id}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def touch_down(self, x, y):
url = self.base_path + '/touch/down'
data = {'params': {'x': x, 'y': y}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def touch_up(self, x, y):
url = self.base_path + '/touch/up'
data = {'params': {'x': x, 'y': y}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def touch_move(self, x, y):
url = self.base_path + '/touch/move'
data = {'params': {'x': x, 'y': y}}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def dump_hierarchy(self):
url = self.base_path + '/source'
response = self.rpc.get(url)
return json.loads(response)['value']
def multi_pointer_gesture(self, body):
url = self.base_path + '/touch/multi/perform'
return self.rpc.post(url, body)
def flick_on_element(self, element_id, xoffset, yoffset, speed):
url = self.base_path + '/touch/flick'
data = {'element': element_id, 'xoffset': xoffset, 'yoffset': yoffset, 'speed': speed}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def flick_on_position(self, xspeed, yspeed):
url = self.base_path + '/touch/flick'
data = {'xSpeed': xspeed, 'ySpeed': yspeed}
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
def get_attribute(self, element_id, attribute):
response = self.rpc.get(self.base_path + "/element/" + element_id + "/attribute/" + attribute)
return json.loads(response)['value']
def get_device_size(self):
response = self.rpc.get(self.base_path + "/window/current/size")
return json.loads(response)['value']
def get_location(self, element_id):
response = self.rpc.get(self.base_path + "/element/" + element_id + "/location")
value = json.loads(response)['value']
return value['x'], value['y']
def get_desc(self, element_id):
response = self.rpc.get(self.base_path + "/element/" + element_id + "/name")
return json.loads(response)['value']
def get_rotation(self):
response = self.rpc.get(self.base_path + "/rotation")
value = json.loads(response)['value']
return value['z']
def get_screen_orientation(self):
response = self.rpc.get(self.base_path + "/orientation")
return json.loads(response)['value']
def open_notification(self):
url = self.base_path + '/appium/device/open_notifications'
response = self.rpc.post(url, '{}')
return json.loads(response)['value']
def enable_logging(self, enabled):
url = self.base_path + '/enable_logging'
data = dict()
data['enabled'] = enabled
encoded_data = json.dumps(data).encode('utf-8')
response = self.rpc.post(url, encoded_data)
return json.loads(response)['value']
client = AppiumClient()
client.click_element(client.find_element(ByText("test")))