forked from openatx/uiautomator2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
1385 lines (1190 loc) · 46.4 KB
/
__init__.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
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 python
# -*- coding: utf-8 -*-
"""
::Timeout
atx-agent:ReverseProxy use http.DefaultTransport. Default Timeout: 30s
|-- Dial --|-- TLS handshake --|-- Request --|-- Resp.headers --|-- Respose.body --|
|------------------------------ http.Client.Timeout -------------------------------|
Refs:
- https://golang.org/pkg/net/http/#RoundTripper
- http://colobu.com/2016/07/01/the-complete-guide-to-golang-net-http-timeouts
"""
from __future__ import absolute_import, print_function
import functools
import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import warnings
from collections import namedtuple
from datetime import datetime
from typing import Optional
import humanize
import progress.bar
import requests
import six
import six.moves.urllib.parse as urlparse
from retry import retry
from urllib3.util.retry import Retry
import adbutils
from deprecated import deprecated
from logzero import logger
from . import xpath
from .utils import list2cmdline
from .exceptions import (BaseError, ConnectError, GatewayError, JsonRpcError,
NullObjectExceptionError, NullPointerExceptionError,
SessionBrokenError, StaleObjectExceptionError,
UiaError, UiAutomationNotConnectedError,
UiObjectNotFoundError)
from .init import Initer
from .session import Session, set_fail_prompt # noqa: F401
from .utils import cache_return
from .version import __atx_agent_version__
if six.PY2:
FileNotFoundError = OSError
DEBUG = False
HTTP_TIMEOUT = 60
class _ProgressBar(progress.bar.Bar):
message = "progress"
suffix = '%(percent)d%% [%(eta_td)s, %(speed)s]'
@property
def speed(self):
return humanize.naturalsize(self.elapsed and self.index / self.elapsed,
gnu=True) + '/s'
def log_print(s):
thread_name = threading.current_thread().getName()
print(thread_name + ": " + datetime.now().strftime('%H:%M:%S,%f')[:-3] +
" " + s)
def fix_wifi_addr(addr: str) -> Optional[str]:
if not addr:
return None
if re.match(r"^https?://", addr): # eg: http://example.org
return addr
# make a request
# eg: 10.0.0.1, 10.0.0.1:7912
if ':' not in addr:
addr += ":7912" # make default port 7912
try:
r = requests.get("http://" + addr + "/version", timeout=2)
r.raise_for_status()
return "http://" + addr
except:
return None
def connect(addr=None):
"""
Args:
addr (str): uiautomator server address or serial number. default from env-var ANDROID_DEVICE_IP
Returns:
Device
Raises:
ConnectError
Example:
connect("10.0.0.1:7912")
connect("10.0.0.1") # use default 7912 port
connect("http://10.0.0.1")
connect("http://10.0.0.1:7912")
connect("cff1123ea") # adb device serial number
"""
if not addr or addr == '+':
addr = os.getenv('ANDROID_DEVICE_IP') or os.getenv("ANDROID_SERIAL")
wifi_addr = fix_wifi_addr(addr)
if wifi_addr:
return connect_wifi(addr)
return connect_usb(addr)
def connect_adb_wifi(addr):
"""
Run adb connect, and then call connect_usb(..)
Args:
addr: ip+port which can be used for "adb connect" argument
Raises:
ConnectError
"""
assert isinstance(addr, six.string_types)
subprocess.call([adbutils.adb_path(), "connect", addr])
try:
subprocess.call([adbutils.adb_path(), "-s", addr, "wait-for-device"],
timeout=2)
except subprocess.TimeoutExpired:
raise ConnectError("Fail execute", "adb connect " + addr)
return connect_usb(addr)
def connect_usb(serial=None, healthcheck=False, init=True):
"""
Args:
serial (str): android device serial
healthcheck (bool): start uiautomator if not ready
init (bool): initial with apk and atx-agent
Returns:
Device
Raises:
ConnectError
"""
adb = adbutils.AdbClient()
if not serial:
device = adb.device()
else:
device = adbutils.AdbDevice(adb, serial)
lport = device.forward_port(7912)
d = connect_wifi('127.0.0.1:' + str(lport))
d._serial = device.serial
if not d.agent_alive or not d.alive:
initer = Initer(device)
if not initer.check_install():
if not init:
raise RuntimeError(
"Device need to be init with command: uiautomator2 init -s "
+ device.serial)
initer.install() # same as run cli: uiautomator2 init
elif not d.agent_alive:
warnings.warn("start atx-agent ...", RuntimeWarning)
# TODO: /data/local/tmp might not be execuable and atx-agent can be somewhere else
device.shell(
["/data/local/tmp/atx-agent", "server", "--nouia", "-d"])
deadline = time.time() + 3
while time.time() < deadline:
if d.agent_alive:
break
else:
raise RuntimeError("atx-agent recover failed")
if healthcheck:
if not d.alive:
warnings.warn("start uiautomator2 ...", RuntimeWarning)
d.healthcheck()
return d
def connect_wifi(addr: str) -> "Device":
"""
Args:
addr (str) uiautomator server address.
Returns:
Device
Raises:
ConnectError
Examples:
connect_wifi("10.0.0.1")
"""
if not re.match(r"^https?://", addr):
addr = "http://" + addr
# fixed_addr = fix_wifi_addr(addr)
# if fixed_addr is None:
# raise ConnectError("addr is invalid or atx-agent is not running", addr)
u = urlparse.urlparse(addr)
host = u.hostname
port = u.port or 7912
return Device(host, port)
class TimeoutRequestsSession(requests.Session):
def __init__(self):
super(TimeoutRequestsSession, self).__init__()
retries = Retry(total=3, connect=3, backoff_factor=0.5)
# refs: https://stackoverflow.com/questions/33895739/python-requests-cant-load-any-url-remote-end-closed-connection-without-respo
# refs: https://stackoverflow.com/questions/15431044/can-i-set-max-retries-for-requests-request
adapter = requests.adapters.HTTPAdapter(max_retries=retries)
self.mount("http://", adapter)
self.mount("https://", adapter)
def request(self, method, url, **kwargs):
if 'timeout' not in kwargs:
kwargs['timeout'] = HTTP_TIMEOUT
verbose = hasattr(self, 'debug') and self.debug
if verbose:
data = kwargs.get('data') or '""'
if isinstance(data, dict):
data = json.dumps(data)
time_start = time.time()
print(
datetime.now().strftime("%H:%M:%S.%f")[:-3],
"$ curl -X {method} -d '{data}' '{url}'".format(
method=method, url=url, data=data)) # yaml: disable
try:
resp = super(TimeoutRequestsSession,
self).request(method, url, **kwargs)
except requests.ConnectionError as e:
# High possibly atx-agent is down
raise
else:
if verbose:
print(
datetime.now().strftime("%H:%M:%S.%f")[:-3],
"Response (%d ms) >>>\n" %
((time.time() - time_start) * 1000) + resp.text.rstrip() +
"\n<<< END")
from types import MethodType
def raise_for_status(_self):
if _self.status_code != 200:
raise requests.HTTPError(_self.status_code, _self.text)
resp.raise_for_status = MethodType(raise_for_status, resp)
return resp
def plugin_register(name, plugin, *args, **kwargs):
"""
Add plugin into Device
Args:
name: string
plugin: class or function which take d as first parameter
Example:
def upload_screenshot(d):
def inner():
d.screenshot("tmp.jpg")
# use requests.post upload tmp.jpg
return inner
plugin_register("upload_screenshot", save_screenshot)
d = u2.connect()
d.ext_upload_screenshot()
"""
Device.plugins()[name] = (plugin, args, kwargs)
def plugin_clear():
Device.plugins().clear()
class Device(object):
__isfrozen = False
__plugins = {}
def __init__(self, host, port=7912):
"""
Args:
host (str): host address
port (int): port number
Raises:
EnvironmentError
"""
self._host = host
self._port = port
self._serial = None
self._reqsess = TimeoutRequestsSession(
) # use requests.Session to enable HTTP Keep-Alive
self._server_url = 'http://{}:{}'.format(host, port)
self._server_jsonrpc_url = self._server_url + "/jsonrpc/0"
self._default_session = Session(self, None)
self._cached_plugins = {}
self._hooks = {}
self.__devinfo = None
self.__uiautomator_failed = False
self.__uiautomator_lock = threading.Lock()
self.platform = None # hot fix for weditor
self.ash = AdbShell(self.shell) # the powerful adb shell
self.wait_timeout = 20.0 # wait element timeout
self.click_post_delay = None # wait after each click
self._freeze() # prevent creating new attrs
# self._atx_agent_check()
def _freeze(self):
self.__isfrozen = True
@staticmethod
def plugins():
return Device.__plugins
def __setattr__(self, key, value):
""" Prevent creating new attributes outside __init__ """
if self.__isfrozen and not hasattr(self, key):
raise TypeError("Key %s does not exist in class %r" % (key, self))
object.__setattr__(self, key, value)
def __str__(self):
return 'uiautomator2 object for %s:%d' % (self._host, self._port)
def __repr__(self):
return str(self)
def _atx_agent_check(self):
""" check atx-agent health status and version """
try:
version = self._reqsess.get(self.path2url('/version'),
timeout=5).text
if version != __atx_agent_version__:
warnings.warn('Version dismatch, expect "%s" actually "%s"' %
(__atx_agent_version__, version),
Warning,
stacklevel=2)
# Cancel bellow code to make connect() return faster.
# launch service to prevent uiautomator killed by Android system
# self.adb_shell('am', 'startservice', '-n', 'com.github.uiautomator/.Service')
except (requests.ConnectionError, ) as e:
raise EnvironmentError(
"atx-agent is not responding, need to init device first")
@property
def debug(self):
return hasattr(self._reqsess, 'debug') and self._reqsess.debug
@debug.setter
def debug(self, value):
self._reqsess.debug = bool(value)
@property
def serial(self):
return self._serial
#return self.shell(['getprop', 'ro.serialno'])[0].strip()
@property
def address(self):
return f"http://{self._host}:{self._port}"
@property
def jsonrpc(self):
"""
Make jsonrpc call easier
For example:
self.jsonrpc.pressKey("home")
"""
return self.setup_jsonrpc()
def path2url(self, path):
return urlparse.urljoin(self._server_url, path)
def window_size(self):
""" return (width, height) """
info = self._reqsess.get(self.path2url('/info')).json()
w, h = info['display']['width'], info['display']['height']
if (w > h) != (self.info["displayRotation"] % 2 == 1):
w, h = h, w
return w, h
def hooks_register(self, func):
"""
Args:
func: should accept 3 args. func_name:string, args:tuple, kwargs:dict
"""
self._hooks[func] = True
def hooks_apply(self, stage, func_name, args=(), kwargs={}, ret=None):
"""
Args:
stage(str): one of "before" or "after"
"""
for fn in self._hooks.keys():
fn(stage, func_name, args, kwargs, ret)
def setup_jsonrpc(self, jsonrpc_url=None):
"""
Wrap jsonrpc call into object
Usage example:
self.setup_jsonrpc().pressKey("home")
"""
if not jsonrpc_url:
jsonrpc_url = self._server_jsonrpc_url
class JSONRpcWrapper():
def __init__(self, server):
self.server = server
self.method = None
def __getattr__(self, method):
self.method = method # jsonrpc function name
return self
def __call__(self, *args, **kwargs):
http_timeout = kwargs.pop('http_timeout', HTTP_TIMEOUT)
params = args if args else kwargs
return self.server.jsonrpc_retry_call(jsonrpc_url, self.method,
params, http_timeout)
return JSONRpcWrapper(self)
@retry((EnvironmentError, GatewayError, UiAutomationNotConnectedError,
NullObjectExceptionError, NullPointerExceptionError,
StaleObjectExceptionError),
delay=3.0,
jitter=0.5,
tries=3)
def jsonrpc_retry_call(self, *args,
**kwargs): # method, params=[], http_timeout=60):
if self.__uiautomator_failed:
self.reset_uiautomator()
try:
return self.jsonrpc_call(*args, **kwargs)
except (GatewayError, ):
warnings.warn(
"uiautomator2 is not reponding, restart uiautomator2 automatically",
RuntimeWarning,
stacklevel=1)
self.__uiautomator_failed = True
raise
except UiAutomationNotConnectedError:
logger.debug("UiAutomation not connected, restart uiautomator")
# warnings.warn("UiAutomation not connected, restart uiautoamtor",
# RuntimeWarning,
# stacklevel=1)
self.__uiautomator_failed = True
raise
except (NullObjectExceptionError, NullPointerExceptionError,
StaleObjectExceptionError) as e:
if args[1] != 'dumpWindowHierarchy': # args[1] method
warnings.warn(
"uiautomator2 raise exception %s, and run code again" % e,
RuntimeWarning,
stacklevel=1)
time.sleep(1)
return self.jsonrpc_call(*args, **kwargs)
def jsonrpc_call(self, jsonrpc_url, method, params=[], http_timeout=60):
""" jsonrpc2 call
Refs:
- http://www.jsonrpc.org/specification
"""
request_start = time.time()
data = {
"jsonrpc": "2.0",
"id": self._jsonrpc_id(method),
"method": method,
"params": params,
}
data = json.dumps(data).encode('utf-8')
res = self._reqsess.post(
jsonrpc_url, # +"?m="+method, #?method is for debug
headers={"Content-Type": "application/json"},
timeout=http_timeout,
data=data)
if DEBUG:
print("Shell$ curl -X POST -d '{}' {}".format(data, jsonrpc_url))
print("Output> " + res.text)
if res.status_code == 502:
raise GatewayError(
res, "gateway error, time used %.1fs" %
(time.time() - request_start))
if res.status_code == 410: # http status gone: session broken
raise SessionBrokenError("app quit or crash", jsonrpc_url,
res.text)
if res.status_code != 200:
raise UiaError(jsonrpc_url, data, res.status_code, res.text,
"HTTP Return code is not 200", res.text)
jsondata = res.json()
error = jsondata.get('error')
if not error:
return jsondata.get('result')
# error happends
err = JsonRpcError(error, method)
if isinstance(
err.data,
six.string_types) and 'UiAutomation not connected' in err.data:
err.__class__ = UiAutomationNotConnectedError
elif err.message:
if 'uiautomator.UiObjectNotFoundException' in err.message:
err.__class__ = UiObjectNotFoundError
elif 'android.support.test.uiautomator.StaleObjectException' in err.message:
# StaleObjectException
# https://developer.android.com/reference/android/support/test/uiautomator/StaleObjectException.html
# A StaleObjectException exception is thrown when a UiObject2 is used after the underlying View has been destroyed.
# In this case, it is necessary to call findObject(BySelector) to obtain a new UiObject2 instance.
err.__class__ = StaleObjectExceptionError
elif 'java.lang.NullObjectException' in err.message:
err.__class__ = NullObjectExceptionError
elif 'java.lang.NullPointerException' == err.message:
err.__class__ = NullPointerExceptionError
raise err
def _jsonrpc_id(self, method):
m = hashlib.md5()
m.update(("%s at %f" % (method, time.time())).encode("utf-8"))
return m.hexdigest()
@property
def agent_alive(self):
try:
r = self._reqsess.get(self.path2url('/version'), timeout=2)
if r.status_code == 200:
return True
except (requests.HTTPError, requests.ConnectionError) as e:
return False
@property
def alive(self):
try:
r = self._reqsess.get(self.path2url('/ping'), timeout=2)
if r.status_code != 200:
return False
r = self._reqsess.post(self.path2url('/jsonrpc/0'),
data=json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": "deviceInfo"
}),
timeout=2)
if r.status_code != 200:
return False
if r.json().get('error'):
# logger.debug("alive error:", r.json().get('error'))
return False
return True
except requests.exceptions.ReadTimeout:
return False
except EnvironmentError:
return False
def service(self, name):
""" Manage service start or stop
Example:
d.service("uiautomator").start()
d.service("uiautomator").stop()
"""
u2obj = self
class _Service(object):
def __init__(self, name):
self.name = name
# FIXME(ssx): support other service: minicap, minitouch
assert name == 'uiautomator'
def start(self):
res = u2obj._reqsess.post(u2obj.path2url('/uiautomator'))
res.raise_for_status()
def stop(self):
res = u2obj._reqsess.delete(u2obj.path2url('/uiautomator'))
if res.status_code != 200:
warnings.warn(res.text)
def running(self) -> bool:
res = u2obj._reqsess.get(u2obj.path2url("/uiautomator"))
res.raise_for_status()
return res.json().get("running")
return _Service(name)
@property
def uiautomator(self):
return self.service("uiautomator")
def reset_uiautomator(self):
"""
Reset uiautomator
Raises:
RuntimeError
Notes:
OnePlus(China) need to treat specially.
1. stop uiautomator keeper
2. start ATX app
3. stop uiautomator keeper (ATX app will be killed by uiautomator)
4. start ATX app again. (ATX app will be killed again by uiautomator)
5. uiautomator will go back to normal
"""
with self.__uiautomator_lock:
if self.alive:
return
logger.debug("force reset uiautomator")
return self._force_reset_uiautomator()
def _force_reset_uiautomator(self):
brand = self.shell("getprop ro.product.brand").output.strip()
logger.debug("Product-brand: %s", brand)
# self.uiautomator.stop() # stop uiautomator keeper first
# self.app_stop("com.github.uiautomator")
# self.shell('am startservice -n com.github.uiautomator/.Service')
if brand.lower() == "oneplus":
self.app_start("com.github.uiautomator", launch_timeout=10)
self.uiautomator.start()
time.sleep(1.5)
self.app_start("com.github.uiautomator")
else:
self.uiautomator.start()
self.app_start("com.github.uiautomator")
# wait until uiautomator2 service working
deadline = time.time() + 20.0
while time.time() < deadline:
# print(time.strftime("[%Y-%m-%d %H:%M:%S]"),
# "uiautomator is starting ...")
logger.debug("uiautomator is starting ...")
if not self.uiautomator.running():
break
if self.alive:
# keyevent BACK if current is com.github.uiautomator
# XiaoMi uiautomator will kill the app(com.github.uiautomator) when launch
# it is better to start a service to make uiautomator live longer
#if self.app_current()['package'] != 'com.github.uiautomator':
# self.shell([
# 'am', 'startservice', '-n',
# 'com.github.uiautomator/.Service'
# ])
# time.sleep(1.5)
#else:
# time.sleep(.5)
if self.app_current()['package'] == 'com.github.uiautomator':
self.shell(['input', 'keyevent', 'BACK'])
logger.info("uiautomator back to normal")
self.__uiautomator_failed = False
return True
time.sleep(1)
self.uiautomator.stop()
raise EnvironmentError(
"Uiautomator started failed. Find solutions in https://github.com/openatx/uiautomator2/wiki/Common-issues"
)
def healthcheck(self):
"""
Reset device into health state
Raises:
RuntimeError
"""
sh = self.ash
if not sh.is_screen_on():
print(time.strftime("[%Y-%m-%d %H:%M:%S]"), "wakeup screen")
sh.keyevent("WAKEUP")
sh.keyevent("HOME")
sh.swipe(0.1, 0.9, 0.9, 0.1) # swipe to unlock
sh.keyevent("HOME")
sh.keyevent("BACK")
self.reset_uiautomator()
def app_install(self, url, installing_callback=None, server=None):
"""
{u'message': u'downloading', "progress": {u'totalSize': 407992690, u'copiedSize': 49152}}
Returns:
packageName
Raises:
RuntimeError
"""
r = self._reqsess.post(self.path2url('/install'), data={'url': url})
if r.status_code != 200:
raise RuntimeError("app install error:", r.text)
id = r.text.strip()
print(time.strftime('%H:%M:%S'), "id:", id)
return self._wait_install_finished(id, installing_callback)
def _wait_install_finished(self, id, installing_callback):
bar = None
downloaded = True
while True:
resp = self._reqsess.get(self.path2url('/install/' + id))
resp.raise_for_status()
jdata = resp.json()
message = jdata['message']
pg = jdata.get('progress')
def notty_print_progress(pg):
written = pg['copiedSize']
total = pg['totalSize']
print(
time.strftime('%H:%M:%S'), 'downloading %.1f%% [%s/%s]' %
(100.0 * written / total,
humanize.naturalsize(written, gnu=True),
humanize.naturalsize(total, gnu=True)))
if message == 'downloading':
downloaded = False
if pg: # if there is a progress
if hasattr(sys.stdout, 'isatty'):
if sys.stdout.isatty():
if not bar:
bar = _ProgressBar(time.strftime('%H:%M:%S') +
' downloading',
max=pg['totalSize'])
written = pg['copiedSize']
bar.next(written - bar.index)
else:
notty_print_progress(pg)
else:
pass
else:
print(time.strftime('%H:%M:%S'), "download initialing")
else:
if not downloaded:
downloaded = True
if bar: # bar only set in atty
bar.next(pg['copiedSize'] - bar.index) if pg else None
bar.finish()
else:
print(time.strftime('%H:%M:%S'), "download 100%")
print(time.strftime('%H:%M:%S'), message)
if message == 'installing':
if callable(installing_callback):
installing_callback(self)
if message == 'success installed':
return jdata.get('packageName')
if jdata.get('error'):
raise RuntimeError("error", jdata.get('error'))
try:
time.sleep(1)
except KeyboardInterrupt:
bar.finish() if bar else None
print("keyboard interrupt catched, cancel install id", id)
self._reqsess.delete(self.path2url('/install/' + id))
raise
def shell(self, cmdargs, stream=False, timeout=60):
"""
Run adb shell command with arguments and return its output. Require atx-agent >=0.3.3
Args:
cmdargs: str or list, example: "ls -l" or ["ls", "-l"]
timeout: seconds of command run, works on when stream is False
stream: bool used for long running process.
Returns:
(output, exit_code) when stream is False
requests.Response when stream is True, you have to close it after using
Raises:
RuntimeError
For atx-agent is not support return exit code now.
When command got something wrong, exit_code is always 1, otherwise exit_code is always 0
"""
cmdline = list2cmdline(cmdargs) if isinstance(cmdargs, (list, tuple)) else cmdargs
if stream:
return self._reqsess.get(self.path2url("/shell/stream"),
params={"command": cmdline},
timeout=None,
stream=True)
ret = self._reqsess.post(self.path2url('/shell'),
data={
'command': cmdline,
'timeout': str(timeout)
},
timeout=timeout + 10)
if ret.status_code != 200:
raise RuntimeError(
"device agent responds with an error code %d" %
ret.status_code, ret.text)
resp = ret.json()
exit_code = 1 if resp.get('error') else 0
exit_code = resp.get('exitCode', exit_code)
shell_response = namedtuple("ShellResponse", ("output", "exit_code"))
return shell_response(resp.get('output'), exit_code)
def adb_shell(self, *args):
"""
Example:
adb_shell('pwd')
adb_shell('ls', '-l')
adb_shell('ls -l')
Returns:
string for stdout merged with stderr, after the entire shell command is completed.
"""
# print(
# "DeprecatedWarning: adb_shell is deprecated, use: output, exit_code = shell(['ls', '-l']) instead"
# )
cmdline = args[0] if len(args) == 1 else list2cmdline(args)
return self.shell(cmdline)[0]
def app_start(self,
package_name,
activity=None,
extras={},
wait=False,
stop=False,
unlock=False,
launch_timeout=None,
use_monkey=False):
""" Launch application
Args:
package_name (str): package name
activity (str): app activity
stop (bool): Stop app before starting the activity. (require activity)
use_monkey (bool): use monkey command to start app when activity is not given
wait (bool): wait until app started. default False
Raises:
SessionBrokenError
"""
if unlock:
self.unlock()
if stop:
self.app_stop(package_name)
if use_monkey:
self.shell([
'monkey', '-p', package_name, '-c',
'android.intent.category.LAUNCHER', '1'
])
if wait:
self.app_wait(package_name)
return
if not activity:
info = self.app_info(package_name)
activity = info['mainActivity']
if activity.find(".") == -1:
activity = "." + activity
# -D: enable debugging
# -W: wait for launch to complete
# -S: force stop the target app before starting the activity
# --user <USER_ID> | current: Specify which user to run as; if not
# specified then run as the current user.
# -e <EXTRA_KEY> <EXTRA_STRING_VALUE>
# --ei <EXTRA_KEY> <EXTRA_INT_VALUE>
# --ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE>
args = [
'am', 'start', '-a', 'android.intent.action.MAIN', '-c',
'android.intent.category.LAUNCHER'
]
args += ['-n', '{}/{}'.format(package_name, activity)]
# -e --ez
extra_args = []
for k, v in extras.items():
if isinstance(v, bool):
extra_args.extend(['--ez', k, 'true' if v else 'false'])
elif isinstance(v, int):
extra_args.extend(['--ei', k, str(v)])
else:
extra_args.extend(['-e', k, v])
args += extra_args
self.shell(args)
if wait:
self.app_wait(package_name)
@deprecated(version="2.0.0", reason="You should use app_current instead")
def current_app(self):
return self.app_current()
@retry(EnvironmentError, delay=.5, tries=3, jitter=.1)
def app_current(self):
"""
Returns:
dict(package, activity, pid?)
Raises:
EnvironementError
For developer:
Function reset_uiautomator need this function, so can't use jsonrpc here.
"""
# Related issue: https://github.com/openatx/uiautomator2/issues/200
# $ adb shell dumpsys window windows
# Example output:
# mCurrentFocus=Window{41b37570 u0 com.incall.apps.launcher/com.incall.apps.launcher.Launcher}
# mFocusedApp=AppWindowToken{422df168 token=Token{422def98 ActivityRecord{422dee38 u0 com.example/.UI.play.PlayActivity t14}}}
# Regexp
# r'mFocusedApp=.*ActivityRecord{\w+ \w+ (?P<package>.*)/(?P<activity>.*) .*'
# r'mCurrentFocus=Window{\w+ \w+ (?P<package>.*)/(?P<activity>.*)\}')
_focusedRE = re.compile(
r'mCurrentFocus=Window{.*\s+(?P<package>[^\s]+)/(?P<activity>[^\s]+)\}'
)
m = _focusedRE.search(self.shell(['dumpsys', 'window', 'windows'])[0])
if m:
return dict(package=m.group('package'),
activity=m.group('activity'))
# try: adb shell dumpsys activity top
_activityRE = re.compile(
r'ACTIVITY (?P<package>[^\s]+)/(?P<activity>[^/\s]+) \w+ pid=(?P<pid>\d+)'
)
output, _ = self.shell(['dumpsys', 'activity', 'top'])
ms = _activityRE.finditer(output)
ret = None
for m in ms:
ret = dict(package=m.group('package'),
activity=m.group('activity'),
pid=int(m.group('pid')))
if ret: # get last result
return ret
raise EnvironmentError("Couldn't get focused app")
def wait_activity(self, activity, timeout=10):
""" wait activity
Args:
activity (str): name of activity
timeout (float): max wait time
Returns:
bool of activity
"""
deadline = time.time() + timeout
while time.time() < deadline:
current_activity = self.app_current().get('activity')
if activity == current_activity:
return True
time.sleep(.5)
return False
def app_wait(self, package_name: str, timeout: float = 20.0,
front=False) -> int:
""" Wait until app launched
Args:
package_name (str): package name
timeout (float): maxium wait time
front (bool): wait until app is current app
Returns:
pid (int) 0 if launch failed
"""
pid = None
deadline = time.time() + timeout
while time.time() < deadline:
if front:
if self.app_current()['package'] == package_name:
pid = self._pidof_app(package_name)
break
else:
if package_name in self.app_list_running():
pid = self._pidof_app(package_name)
break
time.sleep(1)
return pid or 0
def app_list_running(self) -> list:
"""
Returns:
list of running apps
"""