id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
3,400
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/rotation.py
airtest.core.ios.rotation.XYTransformer
class XYTransformer(object): """ transform the coordinates (x, y) by orientation (upright <--> original) """ @staticmethod def up_2_ori(tuple_xy, tuple_wh, orientation): """ Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orientation Returns: transformed coordinates (x, y) """ x, y = tuple_xy w, h = tuple_wh # no need to do changing # ios touch point same way of image if orientation == wda.LANDSCAPE: x, y = h-y, x elif orientation == wda.LANDSCAPE_RIGHT: x, y = y, w-x elif orientation == wda.PORTRAIT_UPSIDEDOWN: x, y = w-x, h-y elif orientation == wda.PORTRAIT: x, y = x, y return x, y @staticmethod def ori_2_up(tuple_xy, tuple_wh, orientation): """ Transform the coordinates original --> upright Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orientation Returns: transformed coordinates (x, y) """ x, y = tuple_xy w, h = tuple_wh # Only in the ipad+home interface, # the vertical screen coordinates need to be converted to display coordinates if orientation == wda.LANDSCAPE: x, y = y, h - x elif orientation == wda.LANDSCAPE_RIGHT: x, y = w - y, x elif orientation == wda.PORTRAIT_UPSIDEDOWN: x, y = w - x, h - y return x, y
class XYTransformer(object): ''' transform the coordinates (x, y) by orientation (upright <--> original) ''' @staticmethod def up_2_ori(tuple_xy, tuple_wh, orientation): ''' Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orientation Returns: transformed coordinates (x, y) ''' pass @staticmethod def ori_2_up(tuple_xy, tuple_wh, orientation): ''' Transform the coordinates original --> upright Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orientation Returns: transformed coordinates (x, y) ''' pass
5
3
27
5
11
11
5
1
1
0
0
0
0
0
2
2
61
11
25
9
20
25
18
7
15
5
1
1
9
3,401
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/relay.py
airtest.core.ios.relay.ThreadedTCPServer
class ThreadedTCPServer(SocketServer.ThreadingMixIn, TCPServer): # 显式指定为True,否则脚本运行完毕时,因为连接没有断开,导致线程不会终止 daemon_threads = True
class ThreadedTCPServer(SocketServer.ThreadingMixIn, TCPServer): pass
1
0
0
0
0
0
0
0.5
2
0
0
0
0
0
0
28
3
0
2
2
1
1
2
2
1
0
3
0
0
3,402
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/relay.py
airtest.core.ios.relay.TCPServer
class TCPServer(SocketServer.TCPServer): allow_reuse_address = True
class TCPServer(SocketServer.TCPServer): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
25
2
0
2
2
1
0
2
2
1
0
2
0
0
3,403
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/relay.py
airtest.core.ios.relay.TCPRelay
class TCPRelay(SocketServer.BaseRequestHandler): def handle(self): dev = self.server.device dsock = dev.create_inner_connection(self.server.rport)._sock lsock = self.request LOGGING.info("Connection established, relaying data") try: fwd = SocketRelay(dsock, lsock, self.server.bufsize * 1024) fwd.handle() finally: dsock.close() lsock.close() LOGGING.info("Connection closed")
class TCPRelay(SocketServer.BaseRequestHandler): def handle(self): pass
2
0
12
0
12
0
1
0
1
1
1
0
1
0
1
5
13
0
13
6
11
0
12
6
10
1
1
1
1
3,404
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/relay.py
airtest.core.ios.relay.SocketRelay
class SocketRelay(object): def __init__(self, a, b, maxbuf=65535): self.a = a self.b = b self.atob = b"" self.btoa = b"" self.maxbuf = maxbuf def handle(self): while True: rlist = [] wlist = [] xlist = [self.a, self.b] if self.atob: wlist.append(self.b) if self.btoa: wlist.append(self.a) if len(self.atob) < self.maxbuf: rlist.append(self.a) if len(self.btoa) < self.maxbuf: rlist.append(self.b) rlo, wlo, xlo = select.select(rlist, wlist, xlist) if xlo: return if self.a in wlo: n = self.a.send(self.btoa) self.btoa = self.btoa[n:] if self.b in wlo: n = self.b.send(self.atob) self.atob = self.atob[n:] if self.a in rlo: s = self.a.recv(self.maxbuf - len(self.atob)) if not s: return self.atob += s if self.b in rlo: s = self.b.recv(self.maxbuf - len(self.btoa)) if not s: return self.btoa += s
class SocketRelay(object): def __init__(self, a, b, maxbuf=65535): pass def handle(self): pass
3
0
19
0
19
0
7
0
1
0
0
0
2
5
2
2
40
1
39
14
36
0
39
14
36
13
1
3
14
3,405
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_minitouch.py
tests.test_minitouch.TestMiniTouchSetup
class TestMiniTouchSetup(TestMiniTouchBase): def test_0_install(self): self.minitouch.uninstall() self.minitouch.install() def test_teardown(self): self.minitouch.touch((0, 0)) cnt = self._count_server_proc() self.minitouch.teardown() self.assertEqual(self._count_server_proc(), cnt - 1)
class TestMiniTouchSetup(TestMiniTouchBase): def test_0_install(self): pass def test_teardown(self): pass
3
0
4
0
4
0
1
0
1
0
0
0
2
0
2
77
11
2
9
4
6
0
9
4
6
1
3
0
2
3,406
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_minitouch.py
tests.test_minitouch.TestMiniTouchBase
class TestMiniTouchBase(unittest.TestCase): @classmethod def setUpClass(cls): cls.adb = ADB() devices = cls.adb.devices() if not devices: raise RuntimeError("At lease one adb device required") cls.adb.serialno = devices[0][0] cls.minitouch = Minitouch(cls.adb) @classmethod def tearDownClass(cls): cls.minitouch.teardown() def _count_server_proc(self): output = self.adb.raw_shell("ps").strip() cnt = 0 for line in output.splitlines(): if "minitouch" in line and line.split(" ")[-2] not in ["Z", "T", "X"]: # 进程状态是睡眠或运行 cnt += 1 return cnt
class TestMiniTouchBase(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def _count_server_proc(self): pass
6
0
6
0
5
0
2
0.05
1
3
2
2
1
0
3
75
23
3
19
10
13
1
17
8
13
3
2
2
6
3,407
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/keypoint_matching.py
airtest.aircv.keypoint_matching.BRISKMatching
class BRISKMatching(KeypointMatching): """BRISK Matching.""" METHOD_NAME = "BRISK" # 日志中的方法名 def init_detector(self): """Init keypoint detector object.""" self.detector = cv2.BRISK_create() # create BFMatcher object: self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)
class BRISKMatching(KeypointMatching): '''BRISK Matching.''' def init_detector(self): '''Init keypoint detector object.''' pass
2
2
5
0
3
3
1
1
1
0
0
0
1
2
1
17
10
2
5
5
3
5
5
5
3
1
2
0
1
3,408
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_minitouch.py
tests.test_minitouch.TestMiniTouchBackend
class TestMiniTouchBackend(TestMiniTouch): @classmethod def setUpClass(cls): cls.adb = ADB() devices = cls.adb.devices() if not devices: raise RuntimeError("At lease one adb device required") cls.adb.serialno = devices[0][0] cls.minitouch = Minitouch(cls.adb, backend=True)
class TestMiniTouchBackend(TestMiniTouch): @classmethod def setUpClass(cls): pass
3
0
7
0
7
0
2
0
1
3
2
0
0
0
1
81
10
1
9
4
6
0
8
3
6
2
4
1
2
3,409
AirtestProject/Airtest
AirtestProject_Airtest/benchmark/profile_recorder.py
profile_recorder.CheckKeypointResult
class CheckKeypointResult(object): """查看基于特征点的图像结果.""" RGB = False THRESHOLD = 0.7 MATCHING_METHODS = { "kaze": KAZEMatching, "brisk": BRISKMatching, "akaze": AKAZEMatching, "orb": ORBMatching, "sift": SIFTMatching, "surf": SURFMatching, "brief": BRIEFMatching, } def __init__(self, im_search, im_source, threshold=0.8, rgb=True): super(CheckKeypointResult, self).__init__() self.im_source = im_source self.im_search = im_search self.threshold = threshold or self.THRESHOLD self.rgb = rgb or self.RGB # 初始化方法对象 self.refresh_method_objects() def refresh_method_objects(self): """初始化方法对象.""" self.method_object_dict = {} for key, method in self.MATCHING_METHODS.items(): method_object = method(self.im_search, self.im_source, self.threshold, self.rgb) self.method_object_dict.update({key: method_object}) def _get_result(self, method_name="kaze"): """获取特征点.""" method_object = self.method_object_dict.get(method_name) # 提取结果和特征点: try: result = method_object.find_best_result() except Exception: import traceback traceback.print_exc() return [], [], [], None return method_object.kp_sch, method_object.kp_src, method_object.good, result def get_and_plot_keypoints(self, method_name, plot=False): """获取并且绘制出特征点匹配结果.""" if method_name not in self.method_object_dict.keys(): print("'%s' is not in MATCHING_METHODS" % method_name) return None kp_sch, kp_src, good, result = self._get_result(method_name) if not plot or result is None: return kp_sch, kp_src, good, result else: im_search, im_source = deepcopy(self.im_search), deepcopy(self.im_source) # 绘制特征点识别情况、基于特征的图像匹配结果: h_sch, w_sch = im_search.shape[:2] h_src, w_src = im_source.shape[:2] # init the plot image: plot_img = np.zeros([max(h_sch, h_src), w_sch + w_src, 3], np.uint8) plot_img[:h_sch, :w_sch, :] = im_search plot_img[:h_src, w_sch:, :] = im_source # plot good matche points: for m in good: color = tuple([int(random() * 255) for _ in range(3)]) # 随机颜色画线 cv2.line(plot_img, (int(kp_sch[m.queryIdx].pt[0]), int(kp_sch[m.queryIdx].pt[1])), (int(kp_src[m.trainIdx].pt[0] + w_sch), int(kp_src[m.trainIdx].pt[1])), color) # plot search_image for kp in kp_sch: color = tuple([int(random() * 255) for _ in range(3)]) # 随机颜色画点 pos = (int(kp.pt[0]), int(kp.pt[1])) mark_point(im_search, pos, circle=False, color=color, radius=5) # plot source_image for kp in kp_src: color = tuple([int(random() * 255) for _ in range(3)]) # 随机颜色画点 pos = (int(kp.pt[0]), int(kp.pt[1])) mark_point(im_source, pos, circle=False, color=color, radius=10) from airtest.aircv import show show(plot_img) show(im_search) show(im_source)
class CheckKeypointResult(object): '''查看基于特征点的图像结果.''' def __init__(self, im_search, im_source, threshold=0.8, rgb=True): pass def refresh_method_objects(self): '''初始化方法对象.''' pass def _get_result(self, method_name="kaze"): '''获取特征点.''' pass def get_and_plot_keypoints(self, method_name, plot=False): '''获取并且绘制出特征点匹配结果.''' pass
5
4
16
1
13
3
3
0.23
1
5
0
0
4
5
4
4
81
8
62
28
55
14
53
28
46
6
1
2
11
3,410
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/constant.py
airtest.core.ios.constant.IME_METHOD
class IME_METHOD(object): WDAIME = "WDAIME"
class IME_METHOD(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
3,411
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/bytecode.py
airtest.utils.apkparser.bytecode.SV
class SV: """SV is used to handle more easily a value""" def __init__(self, size, buff): self.__size = size self.__value = unpack(self.__size, buff)[0] def _get(self): return pack(self.__size, self.__value) def __str__(self): return "0x%x" % self.__value def __int__(self): return self.__value def get_value_buff(self): return self._get() def get_value(self): return self.__value def set_value(self, attr): self.__value = attr
class SV: '''SV is used to handle more easily a value''' def __init__(self, size, buff): pass def _get(self): pass def __str__(self): pass def __int__(self): pass def get_value_buff(self): pass def get_value_buff(self): pass def set_value(self, attr): pass
8
1
2
0
2
0
1
0.06
0
0
0
0
7
2
7
7
23
6
16
10
8
1
16
10
8
1
0
0
7
3,412
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/bytecode.py
airtest.utils.apkparser.bytecode.SVs
class SVs: """SVs is used to handle more easily a structure of different values""" def __init__(self, size, ntuple, buff): self.__size = size self.__value = ntuple._make(unpack(self.__size, buff)) def _get(self): l = [] for i in self.__value._fields: l.append(getattr(self.__value, i)) return pack(self.__size, *l) def _export(self): return [ x for x in self.__value._fields ] def get_value_buff(self): return self._get() def get_value(self): return self.__value def set_value(self, attr): self.__value = self.__value._replace(**attr) def __str__(self): return self.__value.__str__()
class SVs: '''SVs is used to handle more easily a structure of different values''' def __init__(self, size, ntuple, buff): pass def _get(self): pass def _export(self): pass def get_value_buff(self): pass def get_value_buff(self): pass def set_value(self, attr): pass def __str__(self): pass
8
1
3
0
3
0
1
0.05
0
0
0
0
7
2
7
7
27
7
19
12
11
1
19
12
11
2
0
1
8
3,413
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/bytecode.py
airtest.utils.apkparser.bytecode.XREF
class XREF: pass
class XREF: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
3,414
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_screen_proxy.py
tests.test_screen_proxy.TestScreenProxy
class TestScreenProxy(unittest.TestCase): @classmethod def setUpClass(cls): cls.dev = Android() cls.dev.rotation_watcher.get_ready() def test_setup(self): # 测试默认的初始化 screen_proxy = ScreenProxy.auto_setup(self.dev.adb, rotation_watcher=self.dev.rotation_watcher, display_id=self.dev.display_id, ori_function=lambda: self.dev.display_info) self.assertIsNotNone(screen_proxy) screen_proxy.teardown_stream() # 测试指定默认类型初始化 default_screen = ScreenProxy.auto_setup(self.dev.adb, default_method="MINICAP") self.assertEqual(default_screen.method_name, "MINICAP") default_screen.teardown_stream() minicap = Minicap(self.dev.adb) default_screen2 = ScreenProxy.auto_setup(self.dev.adb, default_method=minicap) self.assertEqual(default_screen2.method_name, "MINICAP") def test_snapshot(self): for name, method in ScreenProxy.SCREEN_METHODS.items(): # 把所有的截图方法遍历一次,各截一次图片 cap_method = method(self.dev.adb) screen_proxy = ScreenProxy(cap_method) img = screen_proxy.snapshot() self.assertIsInstance(img, ndarray) screen_proxy.teardown_stream() def test_get_deprecated_var(self): """ dev.minicap -> dev.screen_proxy dev.minicap.get_frame_from_stream() -> dev.screen_proxy.get_frame_from_stream() Returns: """ for name in ["minicap", "javacap"]: obj = getattr(self.dev, name) self.assertIsInstance(obj, ScreenProxy) self.assertIsInstance(obj.snapshot(), ndarray) def test_cap_method(self): self.assertIn(self.dev.cap_method, ScreenProxy.SCREEN_METHODS.keys()) def test_set_projection(self): # 目前暂时只支持minicap设置projection参数 if self.dev.cap_method == "MINICAP": self.dev.keyevent("HOME") default_height = 800 height = self.dev.display_info.get("height") width = self.dev.display_info.get("width") scale_factor = min(default_height, height) / height projection = (scale_factor * width, scale_factor * height) screen = string_2_img(self.dev.screen_proxy.get_frame(projection=projection)) self.assertEqual(screen.shape[0], default_height) def test_custom_cap_method(self): """ Test adding a custom screenshot method 测试添加一个自定义的截图方法 Returns: """ from airtest.core.android.cap_methods.base_cap import BaseCap class TestCap(BaseCap): def get_frame_from_stream(self): return b"frame" ScreenProxy.register_method("TESTCAP", TestCap) # 默认优先初始化为自定义的TestCap cap = ScreenProxy.auto_setup(self.dev.adb) self.assertIsInstance(cap.screen_method, TestCap) ScreenProxy.SCREEN_METHODS.pop("TESTCAP") @classmethod def tearDownClass(cls): cls.dev.rotation_watcher.teardown()
class TestScreenProxy(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_setup(self): pass def test_snapshot(self): pass def test_get_deprecated_var(self): ''' dev.minicap -> dev.screen_proxy dev.minicap.get_frame_from_stream() -> dev.screen_proxy.get_frame_from_stream() Returns: ''' pass def test_cap_method(self): pass def test_set_projection(self): pass def test_custom_cap_method(self): ''' Test adding a custom screenshot method 测试添加一个自定义的截图方法 Returns: ''' pass class TestCap(BaseCap): def get_frame_from_stream(self): pass @classmethod def tearDownClass(cls): pass
13
2
9
1
6
2
1
0.27
1
5
5
0
6
0
8
80
87
17
55
31
41
15
49
29
37
2
2
1
12
3,415
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_tidevice.py
tests.test_tidevice.TIDeviceTests
class TIDeviceTests(unittest.TestCase): def setUp(self): devices_list = TIDevice.devices() self.udid = devices_list[0] def test_devices(self): devices_list = TIDevice.devices() self.assertIsInstance(devices_list, list) if len(devices_list) > 0: print(devices_list) self.assertIsInstance(devices_list[0], str) self.udid = devices_list[0] def test_list_app(self): app_list = TIDevice.list_app(self.udid) print(app_list) self.assertIsInstance(app_list, list) if len(app_list) > 0: self.assertEqual(len(app_list[0]), 3) def test_list_app_type(self): app_list = TIDevice.list_app(self.udid, app_type='system') print(app_list) self.assertIsInstance(app_list, list) if len(app_list) > 0: self.assertEqual(len(app_list[0]), 3) app_list_all = TIDevice.list_app(self.udid, app_type='all') self.assertGreater(len(app_list_all), len(app_list)) def test_list_wda(self): wda_list = TIDevice.list_wda(self.udid) print(wda_list) self.assertIsInstance(wda_list, list) def test_device_info(self): device_info = TIDevice.device_info(self.udid) print(device_info) self.assertIsInstance(device_info, dict) def test_start_app(self): TIDevice.start_app(self.udid, "com.apple.mobilesafari") def test_stop_app(self): TIDevice.stop_app(self.udid, "com.apple.mobilesafari") def test_ps(self): ps = TIDevice.ps(self.udid) print(ps) self.assertIsInstance(ps, list) def test_ps_wda(self): ps_wda = TIDevice.ps_wda(self.udid) print(ps_wda) self.assertIsInstance(ps_wda, list) def test_xctest(self): wda_bundle_id = TIDevice.list_wda(self.udid)[0] # 创建一个线程,执行xctest t = threading.Thread(target=TIDevice.xctest, args=(self.udid, wda_bundle_id), daemon=True) t.start() time.sleep(5) ps_wda = TIDevice.ps_wda(self.udid) print(ps_wda) self.assertIn(wda_bundle_id, ps_wda) time.sleep(5) # 终止线程 t.join(timeout=3)
class TIDeviceTests(unittest.TestCase): def setUp(self): pass def test_devices(self): pass def test_list_app(self): pass def test_list_app_type(self): pass def test_list_wda(self): pass def test_device_info(self): pass def test_start_app(self): pass def test_stop_app(self): pass def test_ps(self): pass def test_ps_wda(self): pass def test_xctest(self): pass
12
0
5
0
5
0
1
0.04
1
5
1
0
11
1
11
83
69
12
55
25
43
2
55
25
43
2
2
1
14
3,416
AirtestProject/Airtest
AirtestProject_Airtest/playground/ui.py
ui.AutomatorAssertionFail
class AutomatorAssertionFail(Exception): pass
class AutomatorAssertionFail(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
3,417
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/constant.py
airtest.core.ios.constant.CAP_METHOD
class CAP_METHOD(object): MINICAP = "MINICAP" WDACAP = "WDACAP" MJPEG = "MJPEG"
class CAP_METHOD(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
3,418
AirtestProject/Airtest
AirtestProject_Airtest/playground/poco.py
poco.PocoReport
class PocoReport(report.LogToHtml): def translate(self, step): if step["is_poco"] is True: return self.translate_poco_step(step) else: return super(PocoReport, self).translate(step) def translate_poco_step(self, step): """ 处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤 Parameters ---------- step 一个完整的操作,如click prev_step 前一个步骤,应该是截图 Returns ------- """ ret = {} prev_step = self._steps[-1] if prev_step: ret.update(prev_step) ret['type'] = step[1].get("name", "") if step.get('trace'): ret['trace'] = step['trace'] ret['traceback'] = step.get('traceback') if ret['type'] == 'touch': # 取出点击位置 if step[1]['args'] and len(step[1]['args'][0]) == 2: pos = step[1]['args'][0] ret['target_pos'] = [int(pos[0]), int(pos[1])] ret['top'] = ret['target_pos'][1] ret['left'] = ret['target_pos'][0] elif ret['type'] == 'swipe': if step[1]['args'] and len(step[1]['args'][0]) == 2: pos = step[1]['args'][0] ret['target_pos'] = [int(pos[0]), int(pos[1])] ret['top'] = ret['target_pos'][1] ret['left'] = ret['target_pos'][0] # swipe 需要显示一个方向 vector = step[1]["kwargs"].get("vector") if vector: ret['swipe'] = self.dis_vector(vector) ret['vector'] = vector ret['desc'] = self.func_desc_poco(ret) ret['title'] = self._translate_title(ret) return ret def func_desc_poco(self, step): """ 把对应的poco操作显示成中文""" desc = { "touch": u"点击UI组件 {name}".format(name=step.get("text", "")), } if step['type'] in desc: return desc.get(step['type']) else: return self._translate_desc(step)
class PocoReport(report.LogToHtml): def translate(self, step): pass def translate_poco_step(self, step): ''' 处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤 Parameters ---------- step 一个完整的操作,如click prev_step 前一个步骤,应该是截图 Returns ------- ''' pass def func_desc_poco(self, step): ''' 把对应的poco操作显示成中文''' pass
4
2
19
1
14
4
4
0.29
1
2
0
0
3
0
3
27
60
6
42
9
38
12
37
9
33
8
2
2
12
3,419
AirtestProject/Airtest
AirtestProject_Airtest/benchmark/plot.py
plot.PlotResult
class PlotResult(object): """绘制单张图片的方法对比结果.""" def __init__(self, dir_path="", file_name=""): super(PlotResult, self).__init__() # 提取数据: if file_name: file_path = os.path.join(dir_path, file_name) self.data = self.load_file(file_path) self.extract_data() else: raise Exception("Profile result file not exists..") def load_file(self, file, print_info=True): if print_info: print("loading config from :", repr(file)) try: config = anyconfig.load(file, ignore_missing=True) return config except ValueError: print("loading config failed...") return {} def extract_data(self): """从数据中获取到绘图相关的有用信息.""" self.time_axis = [] self.cpu_axis = [] self.mem_axis = [] self.timestamp_list = [] plot_data = self.data.get("plot_data", []) # 按照时间分割线,划分成几段数据,取其中的最值 for i in plot_data: timestamp = i["timestamp"] self.timestamp_list.append(timestamp) timestamp = round(timestamp, 1) cpu_percent = i["cpu_percent"] mem_gb_num = i["mem_gb_num"] date = datetime.fromtimestamp(timestamp) # 添加坐标轴 self.time_axis.append(date) self.cpu_axis.append(cpu_percent) self.mem_axis.append(mem_gb_num) # 获取各种方法执行过程中的cpu和内存极值: self.get_each_method_maximun_cpu_mem() def get_each_method_maximun_cpu_mem(self): """获取每个方法中的cpu和内存耗费最值点.""" # 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点 self.method_exec_info = deepcopy(self.data.get("method_exec_info", [])) method_exec_info = deepcopy(self.method_exec_info) # 用来辅助循环 method_index, cpu_max, cpu_max_time, mem_max, mem_max_time = 0, 0, 0, 0, 0 # 临时变量 self.max_mem = 0 for index, timestamp in enumerate(self.timestamp_list): # method_exec_info是按顺序的,逐个遍历找出每个method_exec_info中的cpu和mem的最值点和timestamp: start, end = method_exec_info[0]["start_time"], method_exec_info[0]["end_time"] if timestamp < start: # 方法正式start之前的数据,不能参与方法内的cpu、mem计算,直接忽略此条数据 continue elif timestamp <= end: # 方法执行期间的数据,纳入最值比较: if self.cpu_axis[index] > cpu_max: cpu_max, cpu_max_time = self.cpu_axis[index], timestamp if self.mem_axis[index] > mem_max: mem_max, mem_max_time = self.mem_axis[index], timestamp continue else: # 本次方法筛选完毕,保存本方法的最值cpu和mem if cpu_max_time != 0 and mem_max_time != 0: self.method_exec_info[method_index].update({"cpu_max": cpu_max, "mem_max": mem_max, "cpu_max_time": cpu_max_time, "mem_max_time": mem_max_time}) # 保存最大的内存,后面绘图时用 if mem_max > self.max_mem: self.max_mem = mem_max cpu_max, mem_max = 0, 0 # 临时变量 # 准备进行下一个方法的检查,发现已经检查完则正式结束 del method_exec_info[0] if method_exec_info: method_index += 1 # 进行下一个方法时:当前方法的序号+1 continue else: break def _get_graph_title(self): """获取图像的title.""" start_time = datetime.fromtimestamp(int(self.timestamp_list[0])) end_time = datetime.fromtimestamp(int(self.timestamp_list[-1])) end_time = end_time.strftime('%H:%M:%S') title = "Timespan: %s —— %s" % (start_time, end_time) return title def plot_cpu_mem_keypoints(self): """绘制CPU/Mem/特征点数量.""" plt.figure(1) # 开始绘制子图: plt.subplot(311) title = self._get_graph_title() plt.title(title, loc="center") # 设置绘图的标题 mem_ins = plt.plot(self.time_axis, self.mem_axis, "-", label="Mem(MB)", color='deepskyblue', linestyle='-', marker=',') # 设置数字标签 plt.legend(mem_ins, ["Mem(MB)"], loc='upper right') # 说明标签的位置 plt.grid() # 加网格 plt.ylabel("Mem(MB)") plt.ylim(bottom=0) for method_exec in self.method_exec_info: start_date = datetime.fromtimestamp(method_exec["start_time"]) end_date = datetime.fromtimestamp(method_exec["end_time"]) plt.vlines(start_date, 0, self.max_mem, colors="c", linestyles="dashed") # vlines(x, ymin, ymax) plt.vlines(end_date, 0, self.max_mem, colors="c", linestyles="dashed") # vlines(x, ymin, ymax) # 绘制mem文字: x = datetime.fromtimestamp(method_exec["mem_max_time"]) text = "%s: %d MB" % (method_exec["name"], method_exec["mem_max"]) plt.text(x, method_exec["mem_max"], text, ha="center", va="bottom", fontsize=10) plt.plot(x, method_exec["mem_max"], 'bo', label="point") # 绘制点 # 绘制子图2 plt.subplot(312) cpu_ins = plt.plot(self.time_axis, self.cpu_axis, "-", label="CPU(%)", color='red', linestyle='-', marker=',') plt.legend(cpu_ins, ["CPU(%)"], loc='upper right') # 说明标签的位置 plt.grid() # 加网格 plt.xlabel("Time(s)") plt.ylabel("CPU(%)") plt.ylim(0, 120) for method_exec in self.method_exec_info: start_date = datetime.fromtimestamp(method_exec["start_time"]) end_date = datetime.fromtimestamp(method_exec["end_time"]) plt.vlines(start_date, 0, 100, colors="c", linestyles="dashed") # vlines(x, ymin, ymax) plt.vlines(end_date, 0, 100, colors="c", linestyles="dashed") # vlines(x, ymin, ymax) # 绘制mem文字: x = datetime.fromtimestamp(method_exec["cpu_max_time"]) text = "%s: %d%%" % (method_exec["name"], method_exec["cpu_max"]) plt.text(x, method_exec["cpu_max"], text, ha="center", va="bottom", fontsize=10) plt.plot(x, method_exec["cpu_max"], 'ro', label="point") # 绘制点 # 绘制子图3 plt.subplot(313) # 绘制一下柱状图(关键点) # 设置轴向标签 plt.xlabel('methods') plt.ylabel('keypoints number') method_list, method_pts_length_list, color_list = [], [], [] for method_exec in self.method_exec_info: for item in ["kp_sch", "kp_src", "good"]: method_list.append("%s-%s" % (method_exec["name"], item)) method_pts_length_list.append(method_exec[item]) if method_exec["result"]: color_list.append(["palegreen", "limegreen", "deepskyblue"][["kp_sch", "kp_src", "good"].index(item)]) else: color_list.append("tomato") method_x = np.arange(len(method_list)) + 1 plt.bar(method_x, method_pts_length_list, width=0.35, align='center', color=color_list, alpha=0.8) plt.xticks(method_x, method_list, size='small', rotation=30) # 设置数字标签 for x, y in zip(method_x, method_pts_length_list): plt.text(x, y + 10, "%d" % y, ha="center", va="bottom", fontsize=7) plt.ylim(0, max(method_pts_length_list) * 1.2) # 显示图像 plt.show()
class PlotResult(object): '''绘制单张图片的方法对比结果.''' def __init__(self, dir_path="", file_name=""): pass def load_file(self, file, print_info=True): pass def extract_data(self): '''从数据中获取到绘图相关的有用信息.''' pass def get_each_method_maximun_cpu_mem(self): '''获取每个方法中的cpu和内存耗费最值点.''' pass def _get_graph_title(self): '''获取图像的title.''' pass def plot_cpu_mem_keypoints(self): '''绘制CPU/Mem/特征点数量.''' pass
7
5
25
1
20
7
4
0.34
1
7
0
0
6
7
6
6
159
12
122
41
115
41
117
41
110
9
1
3
24
3,420
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/transform.py
airtest.utils.transform.TargetPos
class TargetPos(object): """ 点击目标图片的不同位置,默认为中心点0 1 2 3 4 0 6 7 8 9 """ LEFTUP, UP, RIGHTUP = 1, 2, 3 LEFT, MID, RIGHT = 4, 5, 6 LEFTDOWN, DOWN, RIGHTDOWN = 7, 8, 9 def getXY(self, cvret, pos): if pos == 0 or pos == self.MID: return cvret["result"] rect = cvret.get("rectangle") if not rect: print("could not get rectangle, use mid point instead") return cvret["result"] w = rect[2][0] - rect[0][0] h = rect[2][1] - rect[0][1] if pos == self.LEFTUP: return rect[0] elif pos == self.LEFTDOWN: return rect[1] elif pos == self.RIGHTDOWN: return rect[2] elif pos == self.RIGHTUP: return rect[3] elif pos == self.LEFT: return rect[0][0], rect[0][1] + h / 2 elif pos == self.UP: return rect[0][0] + w / 2, rect[0][1] elif pos == self.RIGHT: return rect[2][0], rect[2][1] - h / 2 elif pos == self.DOWN: return rect[2][0] - w / 2, rect[2][1] else: print("invalid target_pos:%s, use mid point instead" % pos) return cvret["result"]
class TargetPos(object): ''' 点击目标图片的不同位置,默认为中心点0 1 2 3 4 0 6 7 8 9 ''' def getXY(self, cvret, pos): pass
2
1
28
0
28
0
11
0.19
1
0
0
0
1
0
1
1
39
1
32
8
30
6
24
8
22
11
1
1
11
3,421
AirtestProject/Airtest
AirtestProject_Airtest/benchmark/profile_recorder.py
profile_recorder.ProfileRecorder
class ProfileRecorder(object): """帮助用户记录性能数据.""" def __init__(self, profile_interval=0.1): super(ProfileRecorder, self).__init__() self.record_thread = RecordThread() self.record_thread.set_interval(profile_interval) def load_images(self, search_file, source_file): """加载待匹配图片.""" self.search_file, self.source_file = search_file, source_file self.im_search, self.im_source = imread(self.search_file), imread(self.source_file) # 初始化对象 self.check_macthing_object = CheckKeypointResult(self.im_search, self.im_source) def profile_methods(self, method_list): """帮助函数执行时记录数据.""" self.method_exec_info = [] # 开始数据记录进程 self.record_thread.stop_flag = False self.record_thread.start() for name in method_list: if name not in self.check_macthing_object.MATCHING_METHODS.keys(): continue time.sleep(3) # 留出绘图空白区 start_time = time.time() # 记录开始时间 print("--->>> start '%s' matching:\n" % name) kp_sch, kp_src, good, result = self.check_macthing_object.get_and_plot_keypoints(name) # 根据方法名绘制对应的识别结果 print("\n\n\n") end_time = time.time() # 记录结束时间 time.sleep(3) # 留出绘图空白区 # 记录本次匹配的相关数据 ret_info = { "name": name, "start_time": start_time, "end_time": end_time, "result": result, "kp_sch": len(kp_sch), "kp_src": len(kp_src), "good": len(good)} self.method_exec_info.append(ret_info) self.record_thread.stop_flag = True def wite_to_json(self, dir_path="", file_name=""): """将性能数据写入文件.""" # 提取数据 data = { "plot_data": self.record_thread.profile_data, "method_exec_info": self.method_exec_info, "search_file": self.search_file, "source_file": self.source_file} # 写入文件 file_path = os.path.join(dir_path, file_name) if not os.path.exists(dir_path): os.makedirs(dir_path) json.dump(data, open(file_path, "w+"), indent=4)
class ProfileRecorder(object): '''帮助用户记录性能数据.''' def __init__(self, profile_interval=0.1): pass def load_images(self, search_file, source_file): '''加载待匹配图片.''' pass def profile_methods(self, method_list): '''帮助函数执行时记录数据.''' pass def wite_to_json(self, dir_path="", file_name=""): '''将性能数据写入文件.''' pass
5
4
13
1
11
3
2
0.33
1
3
2
0
4
7
4
4
59
7
43
17
38
14
32
17
27
3
1
2
7
3,422
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/threadsafe.py
airtest.utils.threadsafe.ThreadSafeIter
class ThreadSafeIter: """ Takes an iterator/generator and makes it thread-safe by serializing call to the `next` method of given iterator/generator. """ def __init__(self, it): self.it = it self.lock = threading.Lock() if getattr(self.it, "__next__", None) is None: # for py2 self._next = self.it.next else: self._next = self.it.__next__ # py3 def __iter__(self): return self def __next__(self): with self.lock: return self._next() def send(self, *args): with self.lock: return self.it.send(*args) next = __next__
class ThreadSafeIter: ''' Takes an iterator/generator and makes it thread-safe by serializing call to the `next` method of given iterator/generator. ''' def __init__(self, it): pass def __iter__(self): pass def __next__(self): pass def send(self, *args): pass
5
1
4
0
4
1
1
0.41
0
0
0
0
4
3
4
4
25
4
17
8
12
7
16
8
11
2
0
1
5
3,423
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/selenium_proxy.py
airtest.utils.selenium_proxy.Element
class Element(WebElement): def __init__(self, _obj): super(Element, self).__init__(parent=_obj._parent, id_=_obj._id, w3c=_obj._w3c) @logwrap def click(self): super(Element, self).click() time.sleep(0.5) @logwrap def send_keys(self, text, keyborad=None): log_in_func({"func_args": text}) if keyborad: super(Element, self).send_keys(text, keyborad) else: super(Element, self).send_keys(text) time.sleep(0.5) @logwrap def assert_text(self, text): log_in_func({"func_args": text}) assert text in self.text.encode("utf-8") time.sleep(0.5)
class Element(WebElement): def __init__(self, _obj): pass @logwrap def click(self): pass @logwrap def send_keys(self, text, keyborad=None): pass @logwrap def assert_text(self, text): pass
8
0
4
0
4
0
1
0
1
1
0
0
4
0
4
4
24
4
20
8
12
0
16
5
11
2
1
1
5
3,424
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/safesocket.py
airtest.utils.safesocket.SafeSocket
class SafeSocket(object): """safe and exact recv & send""" def __init__(self, sock=None): if sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock self.buf = b"" def __enter__(self): try: return self.sock.__enter__() except AttributeError: return self.sock def __exit__(self, exc_type, exc_val, exc_tb): try: return self.sock.__exit__(exc_type, exc_val, exc_tb) except AttributeError: self.sock.close() # PEP 3113 -- Removal of Tuple Parameter Unpacking # https://www.python.org/dev/peps/pep-3113/ def connect(self, tuple_hp): host, port = tuple_hp self.sock.connect((host, port)) def send(self, msg): totalsent = 0 while totalsent < len(msg): sent = self.sock.send(msg[totalsent:]) if sent == 0: raise socket.error("socket connection broken") totalsent += sent def recv(self, size): while len(self.buf) < size: trunk = self.sock.recv(min(size-len(self.buf), 4096)) if trunk == b"": raise socket.error("socket connection broken") self.buf += trunk ret, self.buf = self.buf[:size], self.buf[size:] return ret def recv_with_timeout(self, size, timeout=2): self.sock.settimeout(timeout) try: ret = self.recv(size) except socket.timeout: ret = None finally: self.sock.settimeout(None) return ret def recv_nonblocking(self, size): self.sock.settimeout(0) try: ret = self.recv(size) except(socket.error) as e: #10035 no data when nonblocking if e.args[0] == 10035: #errno.EWOULDBLOCK: 尼玛errno似乎不一致 ret = None #10053 connection abort by client #10054 connection reset by peer elif e.args[0] in [10053, 10054]: #errno.ECONNABORTED: raise else: raise return ret def close(self): if hasattr(self.sock, "_closed") and not self.sock._closed: try: self.sock.shutdown(socket.SHUT_RDWR) except OSError as e: if e.errno != errno.ENOTCONN: # 'Socket is not connected' raise self.sock.close() else: self.sock.close()
class SafeSocket(object): '''safe and exact recv & send''' def __init__(self, sock=None): pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass def connect(self, tuple_hp): pass def send(self, msg): pass def recv(self, size): pass def recv_with_timeout(self, size, timeout=2): pass def recv_nonblocking(self, size): pass def close(self): pass
10
1
8
0
7
1
3
0.14
1
3
0
1
9
2
9
9
80
8
66
21
56
9
61
19
51
4
1
3
23
3,425
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/nbsp.py
airtest.utils.nbsp.UnexpectedEndOfStream
class UnexpectedEndOfStream(Exception): pass
class UnexpectedEndOfStream(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
3,426
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/nbsp.py
airtest.utils.nbsp.NonBlockingStreamReader
class NonBlockingStreamReader: def __init__(self, stream, raise_EOF=False, print_output=True, print_new_line=True, name=None, auto_kill=False): ''' stream: the stream to read from. Usually a process' stdout or stderr. raise_EOF: if True, raise an UnexpectedEndOfStream when stream is EOF before kill print_output: if True, print when readline ''' self._s = stream self._q = queue.Queue() self._lastline = None self.name = name or id(self) def _populateQueue(stream, queue, kill_event): ''' Collect lines from 'stream' and put them in 'queue'. ''' while not kill_event.is_set(): line = stream.readline() if line is not None: queue.put(line) if print_output: # print only new line if print_new_line and line == self._lastline: continue self._lastline = line LOGGING.debug("[%s]%s" % (self.name, repr(line.strip()))) if auto_kill and line == b"": self.kill() elif kill_event.is_set(): break elif raise_EOF: raise UnexpectedEndOfStream else: break self._kill_event = Event() self._t = Thread(target=_populateQueue, args=(self._s, self._q, self._kill_event), name="nbsp_%s"%self.name) self._t.daemon = True self._t.start() # start collecting lines from the stream def readline(self, timeout=None): try: return self._q.get(block=timeout is not None, timeout=timeout) except queue.Empty: return None def read(self, timeout=0): time.sleep(timeout) lines = [] while True: line = self.readline() if line is None: break lines.append(line) return b"".join(lines) def kill(self): self._kill_event.set()
class NonBlockingStreamReader: def __init__(self, stream, raise_EOF=False, print_output=True, print_new_line=True, name=None, auto_kill=False): ''' stream: the stream to read from. Usually a process' stdout or stderr. raise_EOF: if True, raise an UnexpectedEndOfStream when stream is EOF before kill print_output: if True, print when readline ''' pass def _populateQueue(stream, queue, kill_event): ''' Collect lines from 'stream' and put them in 'queue'. ''' pass def readline(self, timeout=None): pass def readline(self, timeout=None): pass def kill(self): pass
6
2
16
0
12
3
3
0.27
0
3
1
0
4
6
4
4
61
6
44
15
38
12
41
15
35
8
0
4
15
3,427
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/logwraper.py
airtest.utils.logwraper.AirtestLogger
class AirtestLogger(object): """logger """ def __init__(self, logfile): super(AirtestLogger, self).__init__() self.running_stack = [] self.logfile = None self.logfd = None self.set_logfile(logfile) reg_cleanup(self.handle_stacked_log) def set_logfile(self, logfile): if logfile: self.logfile = os.path.realpath(logfile) self.logfd = open(self.logfile, "w") else: # use G.LOGGER.set_logfile(None) to reset logfile self.logfile = None if self.logfd: self.logfd.close() self.logfd = None @staticmethod def _dumper(obj): if hasattr(obj, "to_json"): try: return obj.to_json() except: repr(obj) try: d = copy(obj.__dict__) try: d["__class__"] = obj.__class__.__name__ except AttributeError: pass return d except (AttributeError, TypeError): # use d = obj.__dict__.copy() to avoid TypeError: can't pickle mappingproxy objects # but repr(obj) is simpler in the report return repr(obj) def log(self, tag, data, depth=None, timestamp=None): ''' Not thread safe ''' # LOGGING.debug("%s: %s" % (tag, data)) if depth is None: depth = len(self.running_stack) if self.logfd: # 如果timestamp为None,或不是float,就设为默认值time.time() try: timestamp = float(timestamp) except (ValueError, TypeError): timestamp = time.time() try: log_data = json.dumps({'tag': tag, 'depth': depth, 'time': timestamp, 'data': data}, default=self._dumper) except UnicodeDecodeError: # PY2 log_data = json.dumps({'tag': tag, 'depth': depth, 'time': timestamp, 'data': data}, default=self._dumper, ensure_ascii=False) self.logfd.write(log_data + '\n') self.logfd.flush() def handle_stacked_log(self): # 处理stack中的log while self.running_stack: # 先取最后一个,记了log之后再pop,避免depth错误 log_stacked = self.running_stack[-1] try: self.log("function", log_stacked) except Exception as e: LOGGING.error("log_stacked error: %s" % e) LOGGING.error(traceback.format_exc()) self.running_stack.pop()
class AirtestLogger(object): '''logger ''' def __init__(self, logfile): pass def set_logfile(self, logfile): pass @staticmethod def _dumper(obj): pass def log(self, tag, data, depth=None, timestamp=None): ''' Not thread safe ''' pass def handle_stacked_log(self): pass
7
2
13
0
11
2
3
0.17
1
7
0
0
4
3
5
5
72
4
58
14
51
10
54
12
48
5
1
2
17
3,428
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/stringblock.py
airtest.utils.apkparser.stringblock.StringBlock
class StringBlock: """ axml format translated from: http://code.google.com/p/android4me/source/browse/src/android/content/res/AXmlResourceParser.java """ def __init__(self, buff): buff.read(4) self.chunkSize = SV('<L', buff.read(4)) self.stringCount = SV('<L', buff.read(4)) self.styleOffsetCount = SV('<L', buff.read(4)) # unused value ? buff.read(4) # ? self.stringsOffset = SV('<L', buff.read(4)) self.stylesOffset = SV('<L', buff.read(4)) self.m_stringOffsets = [] self.m_styleOffsets = [] self.m_strings = [] self.m_styles = [] for i in range(0, self.stringCount.get_value()): self.m_stringOffsets.append(SV('<L', buff.read(4))) for i in range(0, self.styleOffsetCount.get_value()): self.m_stylesOffsets.append(SV('<L', buff.read(4))) size = self.chunkSize.get_value() - self.stringsOffset.get_value() if self.stylesOffset.get_value() != 0: size = self.stylesOffset.get_value() - self.stringsOffset.get_value() # FIXME if (size % 4) != 0: pass for i in range(0, int(size / 4)): self.m_strings.append(SV('=L', buff.read(4))) if self.stylesOffset.get_value() != 0: size = self.chunkSize.get_value() - self.stringsOffset.get_value() # FIXME if (size % 4) != 0: pass for i in range(0, size / 4): self.m_styles.append(SV('=L', buff.read(4))) def getRaw(self, idx): if idx < 0 or self.m_stringOffsets == [] or idx >= len(self.m_stringOffsets): return None offset = self.m_stringOffsets[ idx ].get_value() length = self.getShort(self.m_strings, offset) data = "" while length > 0: offset += 2 # get the unicode character as the apk might contain non-ASCII label data += six.unichr(self.getShort(self.m_strings, offset)) # FIXME if data[-1] == "&": data = data[:-1] length -= 1 return data def getShort(self, array, offset): value = array[int(offset / 4)].get_value() if (int((offset % 4)) / 2) == 0: return value & 0xFFFF else: return value >> 16
class StringBlock: ''' axml format translated from: http://code.google.com/p/android4me/source/browse/src/android/content/res/AXmlResourceParser.java ''' def __init__(self, buff): pass def getRaw(self, idx): pass def getShort(self, array, offset): pass
4
1
24
6
16
2
5
0.2
0
3
1
0
3
9
3
3
78
20
49
19
45
10
48
19
44
9
0
2
15
3,429
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/apkparser/bytecode.py
airtest.utils.apkparser.bytecode._Bytecode
class _Bytecode(object): def __init__(self, buff): try: import psyco psyco.full() except ImportError: pass self.__buff = buff self.__idx = 0 def read(self, size): if isinstance(size, SV): size = size.value buff = self.__buff[ self.__idx: self.__idx + size ] self.__idx += size return buff def readat(self, off): if isinstance(off, SV): off = off.value return self.__buff[ off: ] def read_b(self, size): return self.__buff[ self.__idx: self.__idx + size ] def set_idx(self, idx): if isinstance(idx, SV): self.__idx = idx.value else: self.__idx = idx def get_idx(self): return self.__idx def add_idx(self, idx): self.__idx += idx def register(self, type_register, fct): self.__registers[ type_register ].append(fct) def get_buff(self): return self.__buff def length_buff(self): return len(self.__buff) def save(self, filename): fd = open(filename, "w") buff = self._save() fd.write(buff) fd.close()
class _Bytecode(object): def __init__(self, buff): pass def read(self, size): pass def readat(self, off): pass def read_b(self, size): pass def set_idx(self, idx): pass def get_idx(self): pass def add_idx(self, idx): pass def register(self, type_register, fct): pass def get_buff(self): pass def length_buff(self): pass def save(self, filename): pass
12
0
4
0
4
0
1
0
1
2
1
0
11
2
11
11
55
14
41
18
28
0
40
18
27
2
1
1
15
3,430
AirtestProject/Airtest
AirtestProject_Airtest/airtest/utils/selenium_proxy.py
airtest.utils.selenium_proxy.WebChrome
class WebChrome(Chrome): def __init__(self, chrome_options=None): if "darwin" in sys.platform: os.environ['PATH'] += ":/Applications/AirtestIDE.app/Contents/Resources/selenium_plugin" super(WebChrome, self).__init__(chrome_options=chrome_options) self.father_number = {0: 0} self.number = 0 self.operation_to_func = {"xpath": self.find_element_by_xpath, "id": self.find_element_by_id, "name": self.find_element_by_name} def find_element_by_xpath(self, xpath): web_element = super(WebChrome, self).find_element_by_xpath(xpath) self.gen_screen_log(web_element) return Element(web_element) def find_element_by_id(self, id): web_element = super(WebChrome, self).find_element_by_id(id) self.gen_screen_log(web_element) return Element(web_element) def find_element_by_name(self, name): web_element = super(WebChrome, self).find_element_by_name(name) self.gen_screen_log(web_element) return Element(web_element) def switch_to_latest_window(self): _father = self.number self.number = len(self.window_handles) - 1 self.father_number[self.number] = _father self.switch_to_window(self.window_handles[self.number]) time.sleep(0.5) def assert_exist(self, path, operation): try: func = self.operation_to_func[operation] except Exception: print("There was no operation: ", operation) return False try: func(path) except Exception as e: return False return True def switch_to_last_window(self): self.number = self.father_number[self.number] self.switch_to_window(self.window_handles[self.number]) time.sleep(0.5) def snapshot(self): self.gen_screen_log() @logwrap def get(self, address): super(WebChrome, self).get(address) log_in_func({"args": address}) time.sleep(2) @logwrap def back(self): super(WebChrome, self).back() log_in_func({"args": ""}) time.sleep(1) @logwrap def forward(self): super(WebChrome, self).forward() log_in_func({"args": ""}) time.sleep(1) def gen_screen_log(self, element=None): if ST.LOG_DIR is None: return None jpg_file_name = str(int(time.time())) + '.jpg' jpg_path = os.path.join(ST.LOG_DIR, jpg_file_name) self.save_screenshot(jpg_path) saved = {"screen": jpg_file_name} if element: size = element.size location = element.location x = size['width'] / 2 + location['x'] y = size['height'] / 2 + location['y'] if "darwin" in sys.platform: x, y = x * 2, y * 2 saved.update({"args": [[x, y]],}) log_in_func(saved)
class WebChrome(Chrome): def __init__(self, chrome_options=None): pass def find_element_by_xpath(self, xpath): pass def find_element_by_id(self, id): pass def find_element_by_name(self, name): pass def switch_to_latest_window(self): pass def assert_exist(self, path, operation): pass def switch_to_last_window(self): pass def snapshot(self): pass @logwrap def get(self, address): pass @logwrap def back(self): pass @logwrap def forward(self): pass def gen_screen_log(self, element=None): pass
16
0
6
0
6
0
2
0
1
6
2
0
12
3
12
12
87
12
75
32
59
0
71
28
58
4
1
2
18
3,431
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/ios/ios.py
airtest.core.ios.ios.TIDevice
class TIDevice: """Below staticmethods are provided by Tidevice. """ @staticmethod def devices(): """ Get all available devices connected by USB, return a list of UDIDs. Returns: list: A list of UDIDs. e.g. ['539c5fffb18f2be0bf7f771d68f7c327fb68d2d9'] """ return Usbmux().device_udid_list() @staticmethod def list_app(udid, app_type="user"): """ Returns a list of installed applications on the device. Args: udid (str): The unique identifier of the device. app_type (str, optional): The type of applications to list. Defaults to "user". Possible values are "user", "system", or "all". Returns: list: A list of tuples containing the bundle ID, display name, and version of the installed applications. e.g. [('com.apple.mobilesafari', 'Safari', '8.0'), ...] """ app_type = { "user": "User", "system": "System", "all": None, }.get(app_type.lower(), None) app_list = [] for info in BaseDevice(udid, Usbmux()).installation.iter_installed(app_type=app_type): bundle_id = info['CFBundleIdentifier'] try: display_name = info['CFBundleDisplayName'] version = info.get('CFBundleShortVersionString', '') app_list.append((bundle_id, display_name, version)) except BrokenPipeError: break return app_list @staticmethod def list_wda(udid): """Get all WDA on device that meet certain naming rules. Returns: List of WDA bundleID. """ app_list = TIDevice.list_app(udid) wda_list = [] for app in app_list: bundle_id, display_name, _ = app if (bundle_id.startswith('com.') and bundle_id.endswith(".xctrunner")) or display_name == "WebDriverAgentRunner-Runner": wda_list.append(bundle_id) return wda_list @staticmethod def device_info(udid): """ Retrieves device information based on the provided UDID. Args: udid (str): The unique device identifier. Returns: dict: A dictionary containing selected device information. The keys include: - productVersion (str): The version of the product. - productType (str): The type of the product. - modelNumber (str): The model number of the device. - serialNumber (str): The serial number of the device. - phoneNumber (str): The phone number associated with the device. - timeZone (str): The time zone of the device. - uniqueDeviceID (str): The unique identifier of the device. - marketName (str): The market name of the device. """ device_info = BaseDevice(udid, Usbmux()).device_info() tmp_dict = {} # chose some useful device info from tidevice """ 'DeviceName', 'ProductVersion', 'ProductType', 'ModelNumber', 'SerialNumber', 'PhoneNumber', 'CPUArchitecture', 'ProductName', 'ProtocolVersion', 'RegionInfo', 'TimeIntervalSince1970', 'TimeZone', 'UniqueDeviceID', 'WiFiAddress', 'BluetoothAddress', 'BasebandVersion' """ for attr in ('ProductVersion', 'ProductType', 'ModelNumber', 'SerialNumber', 'PhoneNumber', 'TimeZone', 'UniqueDeviceID'): key = attr[0].lower() + attr[1:] if attr in device_info: tmp_dict[key] = device_info[attr] try: tmp_dict["marketName"] = MODELS.get(device_info['ProductType']) except: tmp_dict["marketName"] = "" return tmp_dict @staticmethod def install_app(udid, file_or_url): BaseDevice(udid, Usbmux()).app_install(file_or_url) @staticmethod def uninstall_app(udid, bundle_id): BaseDevice(udid, Usbmux()).app_uninstall(bundle_id=bundle_id) @staticmethod def start_app(udid, bundle_id): BaseDevice(udid, Usbmux()).app_start(bundle_id=bundle_id) @staticmethod def stop_app(udid, bundle_id): # Note: seems not work. BaseDevice(udid, Usbmux()).app_stop(pid_or_name=bundle_id) @staticmethod def ps(udid): """ Retrieves the process list of the specified device. Parameters: udid (str): The unique device identifier. Returns: list: A list of dictionaries containing information about each process. Each dictionary contains the following keys: - pid (int): The process ID. - name (str): The name of the process. - bundle_id (str): The bundle identifier of the process. - display_name (str): The display name of the process. e.g. [{'pid': 1, 'name': 'MobileSafari', 'bundle_id': 'com.apple.mobilesafari', 'display_name': 'Safari'}, ...] """ with BaseDevice(udid, Usbmux()).connect_instruments() as ts: app_infos = list(BaseDevice(udid, Usbmux()).installation.iter_installed(app_type=None)) ps = list(ts.app_process_list(app_infos)) ps_list = [] keys = ['pid', 'name', 'bundle_id', 'display_name'] for p in ps: if not p['isApplication']: continue ps_list.append({key: p[key] for key in keys}) return ps_list @staticmethod def ps_wda(udid): """Get all running WDA on device that meet certain naming rules. Returns: List of running WDA bundleID. """ with BaseDevice(udid, Usbmux()).connect_instruments() as ts: app_infos = list(BaseDevice(udid, Usbmux()).installation.iter_installed(app_type=None)) ps = list(ts.app_process_list(app_infos)) ps_wda_list = [] for p in ps: if not p['isApplication']: continue if ".xctrunner" in p['bundle_id'] or p['display_name'] == "WebDriverAgentRunner-Runner": ps_wda_list.append(p['bundle_id']) else: continue return ps_wda_list @staticmethod def xctest(udid, wda_bundle_id): try: return BaseDevice(udid, Usbmux()).xctest(fuzzy_bundle_id=wda_bundle_id, logger=setup_logger(level=logging.INFO)) except Exception as e: print( f"Failed to run tidevice xctest function for {wda_bundle_id}.Try to run tidevice runwda function for {wda_bundle_id}.") try: return BaseDevice(udid, Usbmux()).runwda(fuzzy_bundle_id=wda_bundle_id) except Exception as e: print(f"Failed to run tidevice runwda function for {wda_bundle_id}.") # 先不抛出异常,ios17的兼容未合并进来,ios17设备一定会报错 # raise AirtestError(f"Failed to start XCTest for {wda_bundle_id}.") @staticmethod def push(udid, local_path, device_path, bundle_id=None, timeout=None): """ Pushes a file or a directory from the local machine to the iOS device. Args: udid (str): The UDID of the iOS device. device_path (str): The directory path on the iOS device where the file or directory will be pushed. local_path (str): The local path of the file or directory to be pushed. bundle_id (str, optional): The bundle ID of the app. If provided, the file or directory will be pushed to the app's sandbox container. Defaults to None. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Examples: Push a file to the DCIM directory:: >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/Pictures/photo.jpg", "/DCIM") >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/Pictures/photo.jpg", "/DCIM/photo.jpg") Push a directory to the Documents directory of the Keynote app:: >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/test.key", "/Documents", "com.apple.Keynote") >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/test.key", "/Documents/test.key", "com.apple.Keynote") """ try: if not os.path.exists(local_path): raise AirtestError(f"Local path {local_path} does not exist.") if bundle_id: sync = BaseDevice(udid, Usbmux()).app_sync(bundle_id) else: sync = BaseDevice(udid, Usbmux()).sync if device_path.endswith("/") or device_path.endswith("\\"): device_path = device_path[:-1] if os.path.isfile(local_path): file_name = os.path.basename(local_path) # 如果device_path有后缀则认为是文件,和本地文件名不一样视为需要重命名 if not os.path.splitext(device_path)[1]: if os.path.basename(device_path) != file_name: device_path = os.path.join(device_path, file_name) device_path = device_path.replace("\\", "/") # Create the directory if it does not exist sync.mkdir(os.path.dirname(device_path)) with open(local_path, "rb") as f: content = f.read() sync.push_content(device_path, content) elif os.path.isdir(local_path): device_path = os.path.join(device_path, os.path.basename(local_path)) device_path = device_path.replace("\\", "/") sync.mkdir(device_path) for root, dirs, files in os.walk(local_path): # 创建文件夹 for directory in dirs: dir_path = os.path.join(root, directory) relative_dir_path = os.path.relpath(dir_path, local_path) device_dir_path = os.path.join(device_path, relative_dir_path) device_dir_path = device_dir_path.replace("\\", "/") sync.mkdir(device_dir_path) # 上传文件 for file_name in files: file_path = os.path.join(root, file_name) relative_path = os.path.relpath(file_path, local_path) device_file_path = os.path.join(device_path, relative_path) device_file_path = device_file_path.replace("\\", "/") with open(file_path, "rb") as f: content = f.read() sync.push_content(device_file_path, content) print(f"pushed {local_path} to {device_path}") except Exception as e: raise AirtestError( f"Failed to push {local_path} to {device_path}. If push a FILE, please check if there is a DIRECTORY with the same name already exists. If push a DIRECTORY, please check if there is a FILE with the same name already exists, and try again.") @staticmethod def pull(udid, device_path, local_path, bundle_id=None, timeout=None): """ Pulls a file or directory from the iOS device to the local machine. Args: udid (str): The UDID of the iOS device. device_path (str): The path of the file or directory on the iOS device. Remote devices can only be file paths. local_path (str): The destination path on the local machine. Remote devices can only be file paths. bundle_id (str, optional): The bundle ID of the app. If provided, the file or directory will be pulled from the app's sandbox. Defaults to None. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Examples: Pull a file from the DCIM directory:: >>> TIDevice.pull("00008020-001270842E88002E", "/DCIM/photo.jpg", "C:/Users/username/Pictures/photo.jpg") >>> TIDevice.pull("00008020-001270842E88002E", "/DCIM/photo.jpg", "C:/Users/username/Pictures") Pull a directory from the Documents directory of the Keynote app:: >>> TIDevice.pull("00008020-001270842E88002E", "/Documents", "C:/Users/username/Documents", "com.apple.Keynote") >>> TIDevice.pull("00008020-001270842E88002E", "/Documents", "C:/Users/username/Documents", "com.apple.Keynote") """ try: if bundle_id: sync = BaseDevice(udid, Usbmux()).app_sync(bundle_id) else: sync = BaseDevice(udid, Usbmux()).sync if TIDevice.is_dir(udid, device_path, bundle_id): os.makedirs(local_path, exist_ok=True) src = pathlib.Path(device_path) dst = pathlib.Path(local_path) if dst.is_dir() and src.name and sync.stat(src).is_dir(): dst = dst.joinpath(src.name) sync.pull(src, dst) print("pulled", src, "->", dst) except Exception as e: raise AirtestError(f"Failed to pull {device_path} to {local_path}.") @staticmethod def rm(udid, remote_path, bundle_id=None): """ Removes a file or directory from the iOS device. Args: udid (str): The UDID of the iOS device. remote_path (str): The path of the file or directory on the iOS device. bundle_id (str, optional): The bundle ID of the app. If provided, the file or directory will be removed from the app's sandbox. Defaults to None. Examples: Remove a file from the DCIM directory:: >>> TIDevice.rm("00008020-001270842E88002E", "/DCIM/photo.jpg") >>> TIDevice.rm("00008020-001270842E88002E", "/DCIM/photo.jpg", "com.apple.Photos") Remove a directory from the Documents directory of the Keynote app:: >>> TIDevice.rm("00008020-001270842E88002E", "/Documents", "com.apple.Keynote") """ def _check_status(status, path): if status == 0: print("removed", path) else: raise AirtestError(f"<{status.name} {status.value}> Failed to remove {path}") def _remove_folder(udid, folder_path, bundle_id): folder_path = folder_path.replace("\\", "/") for file_info in TIDevice.ls(udid, folder_path, bundle_id): if file_info['type'] == 'Directory': _remove_folder(udid, os.path.join(folder_path, file_info['name']), bundle_id) else: status = sync.remove(os.path.join(folder_path, file_info['name'])) _check_status(status, os.path.join(folder_path, file_info['name'])) # remove the folder itself status = sync.remove(folder_path) _check_status(status, folder_path) if bundle_id: sync = BaseDevice(udid, Usbmux()).app_sync(bundle_id) else: sync = BaseDevice(udid, Usbmux()).sync if TIDevice.is_dir(udid, remote_path, bundle_id): if not remote_path.endswith("/"): remote_path += "/" _remove_folder(udid, remote_path, bundle_id) else: status = sync.remove(remote_path) _check_status(status, remote_path) @staticmethod def ls(udid, remote_path, bundle_id=None): """ List files and directories in the specified path on the iOS device. Args: udid (str): The UDID of the iOS device. remote_path (str): The path on the iOS device. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Returns: list: A list of files and directories in the specified path. Examples: List files and directories in the DCIM directory:: >>> print(TIDevice.ls("00008020-001270842E88002E", "/DCIM")) [{'type': 'Directory', 'size': 96, 'last_modified': '2021-12-01 15:30:13', 'name': '100APPLE/'}, {'type': 'Directory', 'size': 96, 'last_modified': '2021-07-20 17:29:01', 'name': '.MISC/'}] List files and directories in the Documents directory of the Keynote app:: >>> print(TIDevice.ls("00008020-001270842E88002E", "/Documents", "com.apple.Keynote")) [{'type': 'File', 'size': 302626, 'last_modified': '2024-06-25 11:25:25', 'name': '演示文稿.key'}] """ try: file_list = [] if bundle_id: sync = BaseDevice(udid, Usbmux()).app_sync(bundle_id) else: sync = BaseDevice(udid, Usbmux()).sync if remote_path.endswith("/") or remote_path.endswith("\\"): remote_path = remote_path[:-1] for file_info in sync.listdir_info(remote_path): filename = file_info.st_name if file_info.is_dir(): filename = filename + "/" file_list.append(['d' if file_info.is_dir() else '-', file_info.st_size, file_info.st_mtime, filename]) file_list = format_file_list(file_list) return file_list except Exception as e: raise AirtestError(f"Failed to list files and directories in {remote_path}.") @staticmethod def mkdir(udid, remote_path, bundle_id=None): """ Create a directory on the iOS device. Args: udid (str): The UDID of the iOS device. remote_path (str): The path of the directory to be created on the iOS device. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Examples: Create a directory in the DCIM directory:: >>> TIDevice.mkdir("00008020-001270842E88002E", "/DCIM/test") Create a directory in the Documents directory of the Keynote app:: >>> TIDevice.mkdir("00008020-001270842E88002E", "/Documents/test", "com.apple.Keynote") """ if bundle_id: sync = BaseDevice(udid, Usbmux()).app_sync(bundle_id) else: sync = BaseDevice(udid, Usbmux()).sync status = sync.mkdir(remote_path) if int(status) == 0: print("created", remote_path) else: raise AirtestError(f"<{status.name} {status.value}> Failed to create directory {remote_path}") @staticmethod def is_dir(udid, remote_path, bundle_id): """ Check if the specified path on the iOS device is a directory. Args: udid (str): The UDID of the iOS device. remote_path (str): The path on the iOS device. bundle_id (str): The bundle ID of the app. Returns: bool: True if the path is a directory, False otherwise. Examples: Check if the DCIM directory is a directory:: >>> TIDevice.is_dir("00008020-001270842E88002E", "/DCIM") True Check if the Documents directory of the Keynote app is a directory:: >>> TIDevice.is_dir("00008020-001270842E88002E", "/Documents", "com.apple.Keynote") True >>> TIDevice.is_dir("00008020-001270842E88002E", "/Documents/test.key", "com.apple.Keynote") False """ try: remote_path = remote_path.rstrip("\\/") remote_path_dir, remote_path_base = os.path.split(remote_path) file_info = TIDevice.ls(udid, remote_path_dir, bundle_id) for info in file_info: # Remove the trailing slash. if info['name'].endswith("/"): info['name'] = info['name'][:-1] if info['name'] == f"{remote_path_base}": return info['type'] == 'Directory' except Exception as e: raise AirtestError( f"Failed to check if {remote_path} is a directory. Please check the path exist and try again.")
class TIDevice: '''Below staticmethods are provided by Tidevice. ''' @staticmethod def devices(): ''' Get all available devices connected by USB, return a list of UDIDs. Returns: list: A list of UDIDs. e.g. ['539c5fffb18f2be0bf7f771d68f7c327fb68d2d9'] ''' pass @staticmethod def list_app(udid, app_type="user"): ''' Returns a list of installed applications on the device. Args: udid (str): The unique identifier of the device. app_type (str, optional): The type of applications to list. Defaults to "user". Possible values are "user", "system", or "all". Returns: list: A list of tuples containing the bundle ID, display name, and version of the installed applications. e.g. [('com.apple.mobilesafari', 'Safari', '8.0'), ...] ''' pass @staticmethod def list_wda(udid): '''Get all WDA on device that meet certain naming rules. Returns: List of WDA bundleID. ''' pass @staticmethod def device_info(udid): ''' Retrieves device information based on the provided UDID. Args: udid (str): The unique device identifier. Returns: dict: A dictionary containing selected device information. The keys include: - productVersion (str): The version of the product. - productType (str): The type of the product. - modelNumber (str): The model number of the device. - serialNumber (str): The serial number of the device. - phoneNumber (str): The phone number associated with the device. - timeZone (str): The time zone of the device. - uniqueDeviceID (str): The unique identifier of the device. - marketName (str): The market name of the device. ''' pass @staticmethod def install_app(udid, file_or_url): pass @staticmethod def uninstall_app(udid, bundle_id): pass @staticmethod def start_app(udid, bundle_id): pass @staticmethod def stop_app(udid, bundle_id): pass @staticmethod def ps(udid): ''' Retrieves the process list of the specified device. Parameters: udid (str): The unique device identifier. Returns: list: A list of dictionaries containing information about each process. Each dictionary contains the following keys: - pid (int): The process ID. - name (str): The name of the process. - bundle_id (str): The bundle identifier of the process. - display_name (str): The display name of the process. e.g. [{'pid': 1, 'name': 'MobileSafari', 'bundle_id': 'com.apple.mobilesafari', 'display_name': 'Safari'}, ...] ''' pass @staticmethod def ps_wda(udid): '''Get all running WDA on device that meet certain naming rules. Returns: List of running WDA bundleID. ''' pass @staticmethod def xctest(udid, wda_bundle_id): pass @staticmethod def push(udid, local_path, device_path, bundle_id=None, timeout=None): ''' Pushes a file or a directory from the local machine to the iOS device. Args: udid (str): The UDID of the iOS device. device_path (str): The directory path on the iOS device where the file or directory will be pushed. local_path (str): The local path of the file or directory to be pushed. bundle_id (str, optional): The bundle ID of the app. If provided, the file or directory will be pushed to the app's sandbox container. Defaults to None. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Examples: Push a file to the DCIM directory:: >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/Pictures/photo.jpg", "/DCIM") >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/Pictures/photo.jpg", "/DCIM/photo.jpg") Push a directory to the Documents directory of the Keynote app:: >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/test.key", "/Documents", "com.apple.Keynote") >>> TIDevice.push("00008020-001270842E88002E", "C:/Users/username/test.key", "/Documents/test.key", "com.apple.Keynote") ''' pass @staticmethod def pull(udid, device_path, local_path, bundle_id=None, timeout=None): ''' Pulls a file or directory from the iOS device to the local machine. Args: udid (str): The UDID of the iOS device. device_path (str): The path of the file or directory on the iOS device. Remote devices can only be file paths. local_path (str): The destination path on the local machine. Remote devices can only be file paths. bundle_id (str, optional): The bundle ID of the app. If provided, the file or directory will be pulled from the app's sandbox. Defaults to None. timeout (int, optional): The timeout in seconds for the remote device operation. Defaults to None. Examples: Pull a file from the DCIM directory:: >>> TIDevice.pull("00008020-001270842E88002E", "/DCIM/photo.jpg", "C:/Users/username/Pictures/photo.jpg") >>> TIDevice.pull("00008020-001270842E88002E", "/DCIM/photo.jpg", "C:/Users/username/Pictures") Pull a directory from the Documents directory of the Keynote app:: >>> TIDevice.pull("00008020-001270842E88002E", "/Documents", "C:/Users/username/Documents", "com.apple.Keynote") >>> TIDevice.pull("00008020-001270842E88002E", "/Documents", "C:/Users/username/Documents", "com.apple.Keynote") ''' pass @staticmethod def rm(udid, remote_path, bundle_id=None): ''' Removes a file or directory from the iOS device. Args: udid (str): The UDID of the iOS device. remote_path (str): The path of the file or directory on the iOS device. bundle_id (str, optional): The bundle ID of the app. If provided, the file or directory will be removed from the app's sandbox. Defaults to None. Examples: Remove a file from the DCIM directory:: >>> TIDevice.rm("00008020-001270842E88002E", "/DCIM/photo.jpg") >>> TIDevice.rm("00008020-001270842E88002E", "/DCIM/photo.jpg", "com.apple.Photos") Remove a directory from the Documents directory of the Keynote app:: >>> TIDevice.rm("00008020-001270842E88002E", "/Documents", "com.apple.Keynote") ''' pass def _check_status(status, path): pass def _remove_folder(udid, folder_path, bundle_id): pass @staticmethod def ls(udid, remote_path, bundle_id=None): ''' List files and directories in the specified path on the iOS device. Args: udid (str): The UDID of the iOS device. remote_path (str): The path on the iOS device. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Returns: list: A list of files and directories in the specified path. Examples: List files and directories in the DCIM directory:: >>> print(TIDevice.ls("00008020-001270842E88002E", "/DCIM")) [{'type': 'Directory', 'size': 96, 'last_modified': '2021-12-01 15:30:13', 'name': '100APPLE/'}, {'type': 'Directory', 'size': 96, 'last_modified': '2021-07-20 17:29:01', 'name': '.MISC/'}] List files and directories in the Documents directory of the Keynote app:: >>> print(TIDevice.ls("00008020-001270842E88002E", "/Documents", "com.apple.Keynote")) [{'type': 'File', 'size': 302626, 'last_modified': '2024-06-25 11:25:25', 'name': '演示文稿.key'}] ''' pass @staticmethod def mkdir(udid, remote_path, bundle_id=None): ''' Create a directory on the iOS device. Args: udid (str): The UDID of the iOS device. remote_path (str): The path of the directory to be created on the iOS device. bundle_id (str, optional): The bundle ID of the app. Defaults to None. Examples: Create a directory in the DCIM directory:: >>> TIDevice.mkdir("00008020-001270842E88002E", "/DCIM/test") Create a directory in the Documents directory of the Keynote app:: >>> TIDevice.mkdir("00008020-001270842E88002E", "/Documents/test", "com.apple.Keynote") ''' pass @staticmethod def is_dir(udid, remote_path, bundle_id): ''' Check if the specified path on the iOS device is a directory. Args: udid (str): The UDID of the iOS device. remote_path (str): The path on the iOS device. bundle_id (str): The bundle ID of the app. Returns: bool: True if the path is a directory, False otherwise. Examples: Check if the DCIM directory is a directory:: >>> TIDevice.is_dir("00008020-001270842E88002E", "/DCIM") True Check if the Documents directory of the Keynote app is a directory:: >>> TIDevice.is_dir("00008020-001270842E88002E", "/Documents", "com.apple.Keynote") True >>> TIDevice.is_dir("00008020-001270842E88002E", "/Documents/test.key", "com.apple.Keynote") False ''' pass
37
13
24
3
12
9
3
0.72
0
6
1
0
0
0
17
17
470
77
228
94
191
165
190
69
170
12
0
5
66
3,432
AirtestProject/Airtest
AirtestProject_Airtest/benchmark/profile_recorder.py
profile_recorder.RecordThread
class RecordThread(threading.Thread): """记录CPU和内存数据的thread.""" def __init__(self, interval=0.1): super(RecordThread, self).__init__() self.pid = os.getpid() self.interval = interval self.cpu_num = psutil.cpu_count() self.process = psutil.Process(self.pid) self.profile_data = [] self.stop_flag = False def set_interval(self, interval): """设置数据采集间隔.""" self.interval = interval def run(self): """开始线程.""" while not self.stop_flag: timestamp = time.time() cpu_percent = self.process.cpu_percent() / self.cpu_num # mem_percent = mem = self.process.memory_percent() mem_info = dict(self.process.memory_info()._asdict()) mem_gb_num = mem_info.get('rss', 0) / 1024 / 1024 # 记录类变量 self.profile_data.append({"mem_gb_num": mem_gb_num, "cpu_percent": cpu_percent, "timestamp": timestamp}) # 记录cpu和mem_gb_num time.sleep(self.interval)
class RecordThread(threading.Thread): '''记录CPU和内存数据的thread.''' def __init__(self, interval=0.1): pass def set_interval(self, interval): '''设置数据采集间隔.''' pass def run(self): '''开始线程.''' pass
4
3
8
1
6
2
1
0.32
1
3
0
0
3
6
3
28
30
5
19
14
15
6
19
14
15
2
1
1
4
3,433
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_adb.py
tests.test_adb.TestADBWithoutDevice
class TestADBWithoutDevice(unittest.TestCase): @classmethod def setUpClass(cls): cls.adb = ADB() def test_adb_path(self): self.assertTrue(os.path.exists(self.adb.builtin_adb_path())) def test_start_server(self): self.adb.start_server() def test_version(self): self.assertIn("1.0.40", self.adb.version()) def test_other_adb_server(self): adb = ADB(server_addr=("localhost", 5037)) self.assertIn("1.0.40", adb.version()) def test_start_cmd(self): proc = self.adb.start_cmd("devices", device=False) self.assertIsInstance(proc, subprocess.Popen) self.assertIsNotNone(proc.stdin) self.assertIsNotNone(proc.stdout) self.assertIsNotNone(proc.stderr) out, err = proc.communicate() self.assertIsInstance(out, str) self.assertIsInstance(err, str) def test_cmd(self): output = self.adb.cmd("devices", device=False) self.assertIsInstance(output, text_type) with self.assertRaises(AdbError): self.adb.cmd("wtf", device=False) def test_devices(self): all_devices = self.adb.devices() self.assertIsInstance(all_devices, list)
class TestADBWithoutDevice(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_adb_path(self): pass def test_start_server(self): pass def test_version(self): pass def test_other_adb_server(self): pass def test_start_cmd(self): pass def test_cmd(self): pass def test_devices(self): pass
10
0
4
0
4
0
1
0
1
5
2
0
7
0
8
80
39
9
30
15
20
0
29
14
20
1
2
1
8
3,434
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.SiftResultCheckError
class SiftResultCheckError(BaseError): """Exception raised for errors 0 sift points found in the input images."""
class SiftResultCheckError(BaseError): '''Exception raised for errors 0 sift points found in the input images.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,435
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.NoSiftMatchPointError
class NoSiftMatchPointError(BaseError): """Exception raised for errors 0 sift points found in the input images."""
class NoSiftMatchPointError(BaseError): '''Exception raised for errors 0 sift points found in the input images.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,436
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.NoSIFTModuleError
class NoSIFTModuleError(BaseError): """Resolution input is not right."""
class NoSIFTModuleError(BaseError): '''Resolution input is not right.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,437
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.NoModuleError
class NoModuleError(BaseError): """Resolution input is not right."""
class NoModuleError(BaseError): '''Resolution input is not right.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,438
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.NoMatchPointError
class NoMatchPointError(BaseError): """Exception raised for errors 0 keypoint found in the input images."""
class NoMatchPointError(BaseError): '''Exception raised for errors 0 keypoint found in the input images.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,439
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.MatchResultCheckError
class MatchResultCheckError(BaseError): """Exception raised for errors 0 keypoint found in the input images."""
class MatchResultCheckError(BaseError): '''Exception raised for errors 0 keypoint found in the input images.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,440
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.HomographyError
class HomographyError(BaseError): """In homography, find no mask, should kill points which is duplicate."""
class HomographyError(BaseError): '''In homography, find no mask, should kill points which is duplicate.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,441
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.FileNotExistError
class FileNotExistError(BaseError): """Image does not exist."""
class FileNotExistError(BaseError): '''Image does not exist.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,442
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.BaseError
class BaseError(Exception): """Base class for exceptions in this module.""" def __init__(self, message=""): self.message = message def __repr__(self): return repr(self.message)
class BaseError(Exception): '''Base class for exceptions in this module.''' def __init__(self, message=""): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.2
1
0
0
9
2
1
2
12
8
2
5
4
2
1
5
4
2
1
3
0
2
3,443
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/android/rotation.py
airtest.core.android.rotation.RotationWatcher
class RotationWatcher(object): """ RotationWatcher class """ def __init__(self, adb, ori_method=ORI_METHOD.MINICAP): self.adb = adb self.ow_proc = None self.nbsp = None self.ow_callback = [] self.ori_method = ori_method self._t = None self._t_kill_event = threading.Event() self.current_orientation = None self.path_in_android = "/data/local/tmp/" + \ os.path.basename(ROTATIONWATCHER_JAR) reg_cleanup(self.teardown) @on_method_ready('start') def get_ready(self): pass def install(self): """ Install the RotationWatcher package Returns: None """ try: exists_file = self.adb.file_size(self.path_in_android) except: pass else: local_minitouch_size = int(os.path.getsize(ROTATIONWATCHER_JAR)) if exists_file and exists_file == local_minitouch_size: LOGGING.debug("install_rotationwatcher skipped") return self.uninstall() self.adb.push(ROTATIONWATCHER_JAR, self.path_in_android) self.adb.shell("chmod 755 %s" % self.path_in_android) LOGGING.info("install rotationwacher finished") def uninstall(self): """ Uninstall the RotationWatcher package Returns: None """ self.adb.raw_shell("rm %s" % self.path_in_android) def setup_server(self): """ Setup rotation wacher server Returns: server process """ self.install() if self.ow_proc: self.ow_proc.kill() self.ow_proc = None p = self.adb.start_shell( "app_process -Djava.class.path={0} /data/local/tmp com.example.rotationwatcher.Main".format( self.path_in_android)) self.nbsp = NonBlockingStreamReader( p.stdout, name="rotation_server", auto_kill=True) if p.poll() is not None: # server setup error, may be already setup by others # subprocess exit immediately raise RuntimeError("rotation watcher server quit immediately") self.ow_proc = p return p def teardown(self): self._t_kill_event.set() if self.ow_proc: kill_proc(self.ow_proc) if self.nbsp: self.nbsp.kill() self.ow_callback = [] setattr(self, "_start_ready", None) def start(self): """ Start the RotationWatcher daemon thread Returns: initial orientation """ if self.ori_method == ORI_METHOD.MINICAP: try: self.setup_server() except: # install or setup failed LOGGING.error(traceback.format_exc()) LOGGING.error( "RotationWatcher setup failed, use ADBORI instead.") self.ori_method = ORI_METHOD.ADB def _refresh_by_ow(): # 在产生旋转时,nbsp读取到的内容为b"90\r\n",平时读到的是空数据None,进程结束时读到的是b"" line = self.nbsp.readline() if line is not None: if line == b"": self.teardown() if LOGGING is not None: # may be None atexit LOGGING.debug("orientationWatcher has ended") else: print("orientationWatcher has ended") return None ori = int(int(line) / 90) return ori # 每隔1秒读取一次 time.sleep(1) def _refresh_by_adb(): ori = self.adb.getDisplayOrientation() return ori def _run(kill_event): while not kill_event.is_set(): if self.ori_method == ORI_METHOD.ADB: ori = _refresh_by_adb() if self.current_orientation == ori: time.sleep(3) continue else: ori = _refresh_by_ow() if ori is None: # 以前ori=None是进程结束,现在屏幕方向不变时会返回None continue LOGGING.info('update orientation %s->%s' % (self.current_orientation, ori)) self.current_orientation = ori if is_exiting(): self.teardown() for cb in self.ow_callback: try: cb(ori) except: LOGGING.error("cb: %s error" % cb) traceback.print_exc() self.current_orientation = _refresh_by_ow( ) if self.ori_method != ORI_METHOD.ADB else _refresh_by_adb() self._t = threading.Thread(target=_run, args=( self._t_kill_event, ), name="rotationwatcher") self._t.daemon = True self._t.start() return self.current_orientation def reg_callback(self, ow_callback): """ Args: ow_callback: Returns: """ """方向变化的时候的回调函数,参数一定是ori,如果断掉了,ori传None""" if ow_callback not in self.ow_callback: self.ow_callback.append(ow_callback)
class RotationWatcher(object): ''' RotationWatcher class ''' def __init__(self, adb, ori_method=ORI_METHOD.MINICAP): pass @on_method_ready('start') def get_ready(self): pass def install(self): ''' Install the RotationWatcher package Returns: None ''' pass def uninstall(self): ''' Uninstall the RotationWatcher package Returns: None ''' pass def setup_server(self): ''' Setup rotation wacher server Returns: server process ''' pass def teardown(self): pass def start(self): ''' Start the RotationWatcher daemon thread Returns: initial orientation ''' pass def _refresh_by_ow(): pass def _refresh_by_adb(): pass def _run(kill_event): pass def reg_callback(self, ow_callback): ''' Args: ow_callback: Returns: ''' pass
13
6
18
2
13
3
3
0.34
1
6
2
0
8
9
8
8
169
29
105
30
92
36
100
29
88
8
1
3
31
3,444
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/android/recorder.py
airtest.core.android.recorder.Recorder
class Recorder(Yosemite): """Screen recorder""" def __init__(self, adb): super(Recorder, self).__init__(adb) self.recording_proc = None self.recording_file = None @on_method_ready('install_or_upgrade') @retries(max_tries=2) def start_recording(self, max_time=1800, bit_rate=None, bool_is_vertical="off"): """ Start screen recording Args: max_time: maximum screen recording time, default is 1800 bit_rate: bit rate value, 450000-8000000, default is None(6000000) Raises: RuntimeError: if any error occurs while setup the recording Returns: None if recording did not start, otherwise True """ if getattr(self, "recording_proc", None): raise AirtestError("recording_proc has already started") pkg_path = self.adb.path_app(YOSEMITE_PACKAGE) max_time_param = "-Dduration=%d" % max_time if max_time else "" # The higher the bitrate, the clearer the video, the default value is 6000000 bit_rate_param = "-Dbitrate=%d" % bit_rate if bit_rate else "" bool_is_vertical_param = "-Dvertical=%s" % bool_is_vertical # The video size is square, compatible with horizontal and vertical screens p = self.adb.start_shell('CLASSPATH=%s exec app_process %s %s %s /system/bin %s.Recorder --start-record' % (pkg_path, max_time_param, bit_rate_param, bool_is_vertical_param, YOSEMITE_PACKAGE)) nbsp = NonBlockingStreamReader( p.stdout, name="start_recording_" + str(id(self))) # 进程p必须要保留到stop_recording执行时、或是退出前才进行清理,否则会导致录屏进程提前终止 reg_cleanup(kill_proc, p) while True: line = nbsp.readline(timeout=5) if line is None: nbsp.kill() kill_proc(p) raise RuntimeError("start recording error") if six.PY3: line = line.decode("utf-8") # 如果上次录屏被强制中断,可能会导致无法开始下一次录屏,额外发一个停止录屏指令 if re.search("Record has already started", line): self.stop_recording(is_interrupted=True) continue m = re.match( "start result: Record start success! File path:(.*\.mp4)", line.strip()) if m: output = m.group(1) self.recording_proc = p self.recording_file = output nbsp.kill() return True @on_method_ready('install_or_upgrade') def stop_recording(self, output="screen.mp4", is_interrupted=False): """ Stop screen recording Args: output: default file is `screen.mp4` is_interrupted: True or False. Stop only, no pulling recorded file from device. Raises: AirtestError: if recording was not started before Returns: None """ pkg_path = self.adb.path_app(YOSEMITE_PACKAGE) p = self.adb.start_shell( 'CLASSPATH=%s exec app_process /system/bin %s.Recorder --stop-record' % (pkg_path, YOSEMITE_PACKAGE)) p.wait() if self.recording_proc: kill_proc(self.recording_proc) self.recording_proc = None if is_interrupted: kill_proc(p) return for line in p.stdout.readlines(): if line is None: break if six.PY3: line = line.decode("utf-8") m = re.match( "stop result: Stop ok! File path:(.*\.mp4)", line.strip()) if m: self.recording_file = m.group(1) kill_proc(p) self.adb.pull(self.recording_file, output) return True kill_proc(p) raise AirtestError("start_recording first") def pull_last_recording_file(self, output='screen.mp4'): """ Pull the latest recording file from device. Error raises if no recording files on device. Args: output: default file is `screen.mp4` """ recording_file = self.recording_file or 'mnt/sdcard/test.mp4' self.adb.pull(recording_file, output)
class Recorder(Yosemite): '''Screen recorder''' def __init__(self, adb): pass @on_method_ready('install_or_upgrade') @retries(max_tries=2) def start_recording(self, max_time=1800, bit_rate=None, bool_is_vertical="off"): ''' Start screen recording Args: max_time: maximum screen recording time, default is 1800 bit_rate: bit rate value, 450000-8000000, default is None(6000000) Raises: RuntimeError: if any error occurs while setup the recording Returns: None if recording did not start, otherwise True ''' pass @on_method_ready('install_or_upgrade') def stop_recording(self, output="screen.mp4", is_interrupted=False): ''' Stop screen recording Args: output: default file is `screen.mp4` is_interrupted: True or False. Stop only, no pulling recorded file from device. Raises: AirtestError: if recording was not started before Returns: None ''' pass def pull_last_recording_file(self, output='screen.mp4'): ''' Pull the latest recording file from device. Error raises if no recording files on device. Args: output: default file is `screen.mp4` ''' pass
8
4
25
3
15
7
5
0.48
1
5
2
0
4
2
4
9
107
14
63
23
55
30
59
21
54
9
2
2
18
3,445
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/android/cap_methods/javacap.py
airtest.core.android.cap_methods.javacap.Javacap
class Javacap(Yosemite, BaseCap): """ This is another screencap class, it is slower in performance than minicap, but it provides the better compatibility """ APP_PKG = "com.netease.nie.yosemite" SCREENCAP_SERVICE = "com.netease.nie.yosemite.Capture" RECVTIMEOUT = None def __init__(self, adb, *args, **kwargs): super(Javacap, self).__init__(adb) self.frame_gen = None self.cleanup_func = [] @on_method_ready('install_or_upgrade') def _setup_stream_server(self): """ Setup stream server Returns: adb shell process, non-blocking stream reader and local port """ localport, deviceport = self.adb.setup_forward( "localabstract:javacap_{}".format) deviceport = deviceport[len("localabstract:"):] # setup agent proc apkpath = self.adb.path_app(self.APP_PKG) cmds = ["CLASSPATH=" + apkpath, 'exec', 'app_process', '/system/bin', self.SCREENCAP_SERVICE, "--scale", "100", "--socket", "%s" % deviceport, "-lazy", "2>&1"] proc = self.adb.start_shell(cmds) # check proc output nbsp = NonBlockingStreamReader( proc.stdout, print_output=True, name="javacap_sever", auto_kill=True) while True: line = nbsp.readline(timeout=5.0) if line is None: raise ScreenError("javacap server setup timeout") if b"Capture server listening on" in line: break if b"Address already in use" in line: raise ScreenError("javacap server setup error: %s" % line) reg_cleanup(kill_proc, proc) return proc, nbsp, localport @threadsafe_generator def get_frames(self): """ Get the screen frames Returns: None """ proc, nbsp, localport = self._setup_stream_server() s = SafeSocket() s.connect((self.adb.host, localport)) try: t = s.recv(24) except Exception as e: # On some phones, the connection can be established successfully, # but an error is reported when starting to fetch data raise ScreenError(e) # javacap header LOGGING.debug(struct.unpack("<2B5I2B", t)) stopping = False # reg_cleanup(s.close) self.cleanup_func.append(s.close) self.cleanup_func.append(nbsp.kill) self.cleanup_func.append(partial(kill_proc, proc)) self.cleanup_func.append( partial(self.adb.remove_forward, "tcp:%s" % localport)) while not stopping: s.send(b"1") # recv frame header, count frame_size if self.RECVTIMEOUT is not None: header = s.recv_with_timeout(4, self.RECVTIMEOUT) else: header = s.recv(4) if header is None: LOGGING.error("javacap header is None") # recv timeout, if not frame updated, maybe screen locked stopping = yield None else: frame_size = struct.unpack("<I", header)[0] frame_data = s.recv(frame_size) stopping = yield frame_data LOGGING.debug("javacap stream ends") self._cleanup() def get_frame_from_stream(self): """ Get frame from the stream Returns: frame """ if self.frame_gen is None: self.frame_gen = self.get_frames() return self.frame_gen.send(None) def _cleanup(self): """ Cleanup javacap process and stream reader Returns: """ for func in self.cleanup_func: func() self.cleanup_func = [] def teardown_stream(self): """ End stream Returns: None """ self._cleanup() if not self.frame_gen: return try: self.frame_gen.send(1) except (TypeError, StopIteration): pass else: LOGGING.warn("%s tear down failed" % self.frame_gen) self.frame_gen = None
class Javacap(Yosemite, BaseCap): ''' This is another screencap class, it is slower in performance than minicap, but it provides the better compatibility ''' def __init__(self, adb, *args, **kwargs): pass @on_method_ready('install_or_upgrade') def _setup_stream_server(self): ''' Setup stream server Returns: adb shell process, non-blocking stream reader and local port ''' pass @threadsafe_generator def get_frames(self): ''' Get the screen frames Returns: None ''' pass def get_frame_from_stream(self): ''' Get frame from the stream Returns: frame ''' pass def _cleanup(self): ''' Cleanup javacap process and stream reader Returns: ''' pass def teardown_stream(self): ''' End stream Returns: None ''' pass
9
6
19
2
12
5
3
0.46
2
8
3
0
6
2
6
16
132
21
76
29
67
35
71
26
64
5
2
2
18
3,446
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/android/adb.py
airtest.core.android.adb.ADB
class ADB(object): """adb client object class""" _instances = [] status_device = "device" status_offline = "offline" SHELL_ENCODING = "utf-8" def __init__(self, serialno=None, adb_path=None, server_addr=None, display_id=None, input_event=None): self.serialno = serialno self.adb_path = adb_path or self.get_adb_path() self.display_id = display_id self.input_event = input_event self._set_cmd_options(server_addr) self.connect() self._sdk_version = None self._line_breaker = None self._display_info = {} self._display_info_lock = threading.Lock() self._forward_local_using = [] self.__class__._instances.append(self) @staticmethod def get_adb_path(): """ Returns the path to the adb executable. Checks if adb process is running, returns the running process path. If adb process is not running, checks if ANDROID_HOME environment variable is set. Constructs the adb path using ANDROID_HOME and returns it if set. If adb process is not running and ANDROID_HOME is not set, uses built-in adb path. Returns: str: The path to the adb executable. """ if platform.system() == "Windows": ADB_NAME = "adb.exe" else: ADB_NAME = "adb" # Check if adb process is already running try: for process in psutil.process_iter(['name', 'exe']): if process.info['name'] == ADB_NAME and process.info['exe'] and os.path.exists(process.info['exe']): return process.info['exe'] except: # maybe OSError pass # Check if ANDROID_HOME environment variable exists android_home = os.environ.get('ANDROID_HOME') if android_home: adb_path = os.path.join(android_home, 'platform-tools', ADB_NAME) if os.path.exists(adb_path): return adb_path # Use airtest builtin adb path builtin_adb_path = ADB.builtin_adb_path() return builtin_adb_path @staticmethod def builtin_adb_path(): """ Return built-in adb executable path Returns: adb executable path """ system = platform.system() machine = platform.machine() adb_path = DEFAULT_ADB_PATH.get('{}-{}'.format(system, machine)) if not adb_path: adb_path = DEFAULT_ADB_PATH.get(system) if not adb_path: raise RuntimeError( "No adb executable supports this platform({}-{}).".format(system, machine)) if system != "Windows": # chmod +x adb make_file_executable(adb_path) return adb_path def _set_cmd_options(self, server_addr=None): """ Set communication parameters (host and port) between adb server and adb client Args: server_addr: adb server address, default is ["127.0.0.1", 5037] Returns: None """ self.host = server_addr[0] if server_addr else "127.0.0.1" self.port = server_addr[1] if server_addr else 5037 self.cmd_options = [self.adb_path] if self.host not in ("localhost", "127.0.0.1"): self.cmd_options += ['-H', self.host] if self.port != 5037: self.cmd_options += ['-P', str(self.port)] def start_server(self): """ Perform `adb start-server` command to start the adb server Returns: None """ return self.cmd("start-server", device=False) def kill_server(self): """ Perform `adb kill-server` command to kill the adb server Returns: None """ return self.cmd("kill-server", device=False) def version(self): """ Perform `adb version` command and return the command output Returns: command output """ return self.cmd("version", device=False).strip() def start_cmd(self, cmds, device=True): """ Start a subprocess with adb command(s) Args: cmds: command(s) to be run device: if True, the device serial number must be specified by `-s serialno` argument Raises: RuntimeError: if `device` is True and serialno is not specified Returns: a subprocess """ if device: if not self.serialno: raise RuntimeError("please set serialno first") cmd_options = self.cmd_options + ['-s', self.serialno] else: cmd_options = self.cmd_options cmds = cmd_options + split_cmd(cmds) LOGGING.debug(" ".join(cmds)) if not PY3: cmds = [c.encode(get_std_encoding(sys.stdin)) for c in cmds] proc = subprocess.Popen( cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=SUBPROCESS_FLAG ) return proc def cmd(self, cmds, device=True, ensure_unicode=True, timeout=None): """ Run the adb command(s) in subprocess and return the standard output Args: cmds: command(s) to be run device: if True, the device serial number must be specified by -s serialno argument ensure_unicode: encode/decode unicode of standard outputs (stdout, stderr) timeout: timeout in seconds Raises: DeviceConnectionError: if any error occurs when connecting the device AdbError: if any other adb error occurs Returns: command(s) standard output (stdout) """ proc = self.start_cmd(cmds, device) if timeout: stdout, stderr = proc_communicate_timeout(proc, timeout) else: stdout, stderr = proc.communicate() if ensure_unicode: stdout = stdout.decode(get_std_encoding(sys.stdout)) stderr = stderr.decode(get_std_encoding(sys.stderr)) if proc.returncode > 0: # adb connection error pattern = DeviceConnectionError.DEVICE_CONNECTION_ERROR if isinstance(stderr, binary_type): pattern = pattern.encode("utf-8") if re.search(pattern, stderr): raise DeviceConnectionError(stderr) else: raise AdbError(stdout, stderr) return stdout def close_proc_pipe(self, proc): """close stdin/stdout/stderr of subprocess.Popen.""" def close_pipe(pipe): if pipe: pipe.close() close_pipe(proc.stdin) close_pipe(proc.stdout) close_pipe(proc.stderr) def devices(self, state=None): """ Perform `adb devices` command and return the list of adb devices Args: state: optional parameter to filter devices in specific state Returns: list od adb devices """ patten = re.compile(r'[\w\d.:-]+\t[\w]+$') device_list = [] # self.start_server() output = self.cmd("devices", device=False) for line in output.splitlines(): line = line.strip() if not line or not patten.match(line): continue serialno, cstate = line.split('\t') if state and cstate != state: continue device_list.append((serialno, cstate)) return device_list def connect(self, force=False): """ Perform `adb connect` command, remote devices are preferred to connect first Args: force: force connection, default is False Returns: None """ if self.serialno and ":" in self.serialno and (force or self.get_status() != "device"): connect_result = self.cmd("connect %s" % self.serialno) LOGGING.info(connect_result) def disconnect(self): """ Perform `adb disconnect` command Returns: None """ if ":" in self.serialno: self.cmd("disconnect %s" % self.serialno) def get_status(self): """ Perform `adb get-state` and return the device status Raises: AdbError: if status cannot be obtained from the device Returns: None if status is `not found`, otherwise return the standard output from `adb get-state` command """ proc = self.start_cmd("get-state") stdout, stderr = proc.communicate() stdout = stdout.decode(get_std_encoding(sys.stdout)) stderr = stderr.decode(get_std_encoding(sys.stdout)) if proc.returncode == 0: return stdout.strip() elif "not found" in stderr: return None else: raise AdbError(stdout, stderr) def wait_for_device(self, timeout=5): """ Perform `adb wait-for-device` command Args: timeout: time interval in seconds to wait for device Raises: DeviceConnectionError: if device is not available after timeout Returns: None """ try: self.cmd("wait-for-device", timeout=timeout) except RuntimeError as e: raisefrom(DeviceConnectionError, "device not ready", e) def start_shell(self, cmds): """ Handle `adb shell` command(s) Args: cmds: adb shell command(s) Returns: None """ cmds = ['shell'] + split_cmd(cmds) return self.start_cmd(cmds) def raw_shell(self, cmds, ensure_unicode=True): """ Handle `adb shell` command(s) with unicode support Args: cmds: adb shell command(s) ensure_unicode: decode/encode unicode True or False, default is True Returns: command(s) output """ cmds = ['shell'] + split_cmd(cmds) out = self.cmd(cmds, ensure_unicode=False) if not ensure_unicode: return out # use shell encoding to decode output try: return out.decode(self.SHELL_ENCODING) except UnicodeDecodeError: warnings.warn("shell output decode {} fail. repr={}".format( self.SHELL_ENCODING, repr(out))) return text_type(repr(out)) def shell(self, cmd): """ Run the `adb shell` command on the device Args: cmd: a command to be run Raises: AdbShellError: if command return value is non-zero or if any other `AdbError` occurred Returns: command output """ if self.sdk_version < SDK_VERISON_ANDROID7: # for sdk_version < 25, adb shell do not raise error # https://stackoverflow.com/questions/9379400/adb-error-codes cmd = split_cmd(cmd) + [";", "echo", "---$?---"] out = self.raw_shell(cmd).rstrip() m = re.match("(.*)---(\d+)---$", out, re.DOTALL) if not m: warnings.warn("return code not matched") stdout = out returncode = 0 else: stdout = m.group(1) returncode = int(m.group(2)) if returncode > 0: raise AdbShellError("", stdout) return stdout else: try: out = self.raw_shell(cmd) except AdbError as err: raise AdbShellError(err.stdout, err.stderr) else: return out def keyevent(self, keyname): """ Perform `adb shell input keyevent` command on the device Args: keyname: key event name Returns: None """ self.shell(["input", "keyevent", keyname.upper()]) def getprop(self, key, strip=True): """ Perform `adb shell getprop` on the device Args: key: key value for property strip: True or False to strip the return carriage and line break from returned string Returns: propery value """ prop = self.raw_shell(['getprop', key]) if strip: if "\r\r\n" in prop: # Some mobile phones will output multiple lines of extra log prop = prop.split("\r\r\n") if len(prop) > 1: prop = prop[-2] else: prop = prop[-1] else: prop = prop.strip("\r\n") return prop @property @retries(max_tries=3) def sdk_version(self): """ Get the SDK version from the device Returns: SDK version """ if self._sdk_version is None: keyname = 'ro.build.version.sdk' self._sdk_version = int(self.getprop(keyname)) return self._sdk_version def push(self, local, remote): """ Push file or folder to the specified directory to the device Args: local: local file or folder to be copied to the device remote: destination on the device where the file will be copied Returns: The file path saved in the phone may be enclosed in quotation marks, eg. '"test\ file.txt"' Examples: >>> adb = device().adb >>> adb.push("test.txt", "/data/local/tmp") >>> new_name = adb.push("test space.txt", "/data/local/tmp") # test the space in file name >>> print(new_name) "/data/local/tmp/test\ space.txt" >>> adb.shell("rm " + new_name) >>> adb.push("test_dir", "/sdcard/Android/data/com.test.package/files") >>> adb.push("test_dir", "/sdcard/Android/data/com.test.package/files/test_dir") """ _, ext = os.path.splitext(remote) if ext: # The target path is a file dst_parent = os.path.dirname(remote) else: dst_parent = remote # If the target file already exists, delete it first to avoid overwrite failure src_filename = os.path.basename(local) _, src_ext = os.path.splitext(local) if src_ext: dst_path = f"{dst_parent}/{src_filename}" else: if src_filename == os.path.basename(remote): dst_path = remote else: dst_path = f"{dst_parent}/{src_filename}" try: self.shell(f"rm -r {dst_path}") except: pass # If the target folder has multiple levels that have never been created, try to create them try: self.shell(f"mkdir -p {dst_parent}") except: pass # Push the file to the tmp directory to avoid permission issues tmp_path = f"{TMP_PATH}/{src_filename}" try: self.cmd(["push", local, tmp_path]) except: self.cmd(["push", local, dst_parent]) else: try: if src_ext: try: self.shell(f'mv "{tmp_path}" "{remote}"') except: self.shell(f'mv "{tmp_path}" "{remote}"') else: try: self.shell(f'cp -frp "{tmp_path}/*" "{remote}"') except: self.shell(f'mv "{tmp_path}" "{remote}"') finally: try: if TMP_PATH != dst_parent: self.shell(f'rm -r "{tmp_path}"') except: pass return dst_path def pull(self, remote, local=""): """ Perform `adb pull` command Args: remote: remote file to be downloaded from the device local: local destination where the file will be downloaded from the device Note: If <=PY3, the path in Windows cannot be the root directory, and cannot contain symbols such as /g in the path 注意:如果低于PY3,windows中路径不能为根目录,并且不能包含/g等符号在路径里 Returns: None """ if not local: local = os.path.basename(remote) local = decode_path(local) # py2 if PY3: # If python3, use Path to force / convert to \ from pathlib import Path local = Path(local).as_posix() self.cmd(["pull", remote, local], ensure_unicode=False) def forward(self, local, remote, no_rebind=True): """ Perform `adb forward` command Args: local: local tcp port to be forwarded remote: tcp port of the device where the local tcp port will be forwarded no_rebind: True or False Returns: None """ cmds = ['forward'] if no_rebind: cmds += ['--no-rebind'] self.cmd(cmds + [local, remote]) # register for cleanup atexit if local not in self._forward_local_using: self._forward_local_using.append(local) def get_forwards(self): """ Perform `adb forward --list`command Yields: serial number, local tcp port, remote tcp port Returns: None """ out = self.cmd(['forward', '--list']) for line in out.splitlines(): line = line.strip() if not line: continue cols = line.split() if len(cols) != 3: continue serialno, local, remote = cols yield serialno, local, remote @classmethod def get_available_forward_local(cls): """ Generate a pseudo random number between 11111 and 20000 that will be used as local forward port Returns: integer between 11111 and 20000 Note: use `forward --no-rebind` to check if port is available """ return random.randint(11111, 20000) @retries(3) def setup_forward(self, device_port, no_rebind=True): """ Generate pseudo random local port and check if the port is available. Args: device_port: it can be string or the value of the `function(localport)`, e.g. `"tcp:5001"` or `"localabstract:{}".format` no_rebind: adb forward --no-rebind option Returns: local port and device port """ localport = self.get_available_forward_local() if callable(device_port): device_port = device_port(localport) self.forward("tcp:%s" % localport, device_port, no_rebind=no_rebind) return localport, device_port def remove_forward(self, local=None): """ Perform `adb forward --remove` command Args: local: local tcp port Returns: None """ if local: cmds = ["forward", "--remove", local] else: cmds = ["forward", "--remove-all"] try: self.cmd(cmds) except AdbError as e: # ignore if already removed or disconnected if "not found" in (repr(e.stdout) + repr(e.stderr)): pass except DeviceConnectionError: pass # unregister for cleanup if local in self._forward_local_using: self._forward_local_using.remove(local) def install_app(self, filepath, replace=False, install_options=None): """ Perform `adb install` command Args: filepath: full path to file to be installed on the device replace: force to replace existing application, default is False e.g.["-t", # allow test packages "-l", # forward lock application, "-s", # install application on sdcard, "-d", # allow version code downgrade (debuggable packages only) "-g", # grant all runtime permissions ] Returns: command output """ if isinstance(filepath, str): filepath = decode_path(filepath) if not os.path.isfile(filepath): raise RuntimeError("file: %s does not exists" % (repr(filepath))) if not install_options or type(install_options) != list: install_options = [] if replace: install_options.append("-r") cmds = ["install", ] + install_options + [filepath, ] try: out = self.cmd(cmds) except AdbError as e: out = repr(e.stderr) + repr(e.stdout) # If the signatures are inconsistent, uninstall the old version first if "INSTALL_FAILED_UPDATE_INCOMPATIBLE" in out and replace: try: package_name = re.search(r"package (.*?) .*", out).group(1) except: # get package name package_name = APK(filepath).get_package() self.uninstall_app(package_name) out = self.cmd(cmds) else: raise if re.search(r"Failure \[.*?\]", out): raise AdbShellError("Installation Failure", repr(out)) return out def install_multiple_app(self, filepath, replace=False, install_options=None): """ Perform `adb install-multiple` command Args: filepath: full path to file to be installed on the device replace: force to replace existing application, default is False install_options: list of options e.g.["-t", # allow test packages "-l", # forward lock application, "-s", # install application on sdcard, "-d", # allow version code downgrade (debuggable packages only) "-g", # grant all runtime permissions "-p", # partial application install (install-multiple only) ] Returns: command output """ if isinstance(filepath, str): filepath = decode_path(filepath) if not os.path.isfile(filepath): raise RuntimeError("file: %s does not exists" % (repr(filepath))) if not install_options or type(install_options) != list: install_options = [] if replace: install_options.append("-r") cmds = ["install-multiple", ] + install_options + [filepath, ] try: out = self.cmd(cmds) except AdbError as err: if "Failed to finalize session".lower() in err.stderr.lower(): return "Success" else: return self.install_app(filepath, replace) if re.search(r"Failure \[.*?\]", out): raise AdbShellError("Installation Failure", repr(out)) return out def pm_install(self, filepath, replace=False, install_options=None): """ Perform `adb push` and `adb install` commands Note: This is more reliable and recommended way of installing `.apk` files Args: filepath: full path to file to be installed on the device replace: force to replace existing application, default is False install_options: list of options e.g.["-t", # allow test packages "-l", # forward lock application, "-s", # install application on sdcard, "-d", # allow version code downgrade (debuggable packages only) "-g", # grant all runtime permissions ] Returns: None """ if isinstance(filepath, str): filepath = decode_path(filepath) if not os.path.isfile(filepath): raise RuntimeError("file: %s does not exists" % (repr(filepath))) if not install_options or type(install_options) != list: install_options = [] if replace: install_options.append("-r") filename = os.path.basename(filepath) device_dir = "/data/local/tmp" try: # if the apk file path contains spaces, the path must be escaped device_path = self.push(filepath, device_dir) except AdbError as err: # Error: no space left on device raise err try: cmds = ["pm", "install", ] + install_options + [device_path] self.shell(cmds) except AdbError as e: out = repr(e.stderr) + repr(e.stdout) # If the signatures are inconsistent, uninstall the old version first if re.search(r"INSTALL_FAILED_UPDATE_INCOMPATIBLE", out): try: package_name = re.search(r"package (.*?) .*", out).group(1) except: # get package name package_name = APK(filepath).get_package() self.uninstall_app(package_name) out = self.shell(cmds) else: raise finally: # delete apk file self.cmd(["shell", "rm", device_path], timeout=30) def uninstall_app(self, package): """ Perform `adb uninstall` command Args: package: package name to be uninstalled from the device Returns: command output """ return self.cmd(['uninstall', package]) def pm_uninstall(self, package, keepdata=False): """ Perform `adb uninstall` command and delete all related application data Args: package: package name to be uninstalled from the device keepdata: True or False, keep application data after removing the app from the device Returns: command output """ cmd = ['pm', 'uninstall', package] if keepdata: cmd.append('-k') self.shell(cmd) def snapshot(self): """ Take the screenshot of the device display Returns: command output (stdout) """ if self.display_id: raw = self.cmd( 'shell screencap -d {0} -p'.format(self.display_id), ensure_unicode=False) else: raw = self.cmd('shell screencap -p', ensure_unicode=False) return raw.replace(self.line_breaker, b"\n") # PEP 3113 -- Removal of Tuple Parameter Unpacking # https://www.python.org/dev/peps/pep-3113/ def touch(self, tuple_xy): """ Perform user input (touchscreen) on given coordinates Args: tuple_xy: coordinates (x, y) Returns: None """ x, y = tuple_xy self.shell('input tap %d %d' % (x, y)) time.sleep(0.1) def swipe(self, tuple_x0y0, tuple_x1y1, duration=500): """ Perform user input (swipe screen) from start point (x,y) to end point (x,y) Args: tuple_x0y0: start point coordinates (x, y) tuple_x1y1: end point coordinates (x, y) duration: time interval for action, default 500 Raises: AirtestError: if SDK version is not supported Returns: None """ # prot python 3 x0, y0 = tuple_x0y0 x1, y1 = tuple_x1y1 version = self.sdk_version if version <= 15: raise AirtestError( 'swipe: API <= 15 not supported (version=%d)' % version) elif version <= 17: self.shell('input swipe %d %d %d %d' % (x0, y0, x1, y1)) else: self.shell('input touchscreen swipe %d %d %d %d %d' % (x0, y0, x1, y1, duration)) def logcat(self, grep_str="", extra_args="", read_timeout=10): """ Perform `adb shell logcat` command and search for given patterns Args: grep_str: pattern to filter from the logcat output extra_args: additional logcat arguments read_timeout: time interval to read the logcat, default is 10 Yields: logcat lines containing filtered patterns Returns: None """ cmds = "shell logcat" if extra_args: cmds += " " + extra_args if grep_str: cmds += " | grep " + grep_str logcat_proc = self.start_cmd(cmds) nbsp = NonBlockingStreamReader(logcat_proc.stdout, print_output=False) while True: line = nbsp.readline(read_timeout) if line is None: break else: yield line nbsp.kill() logcat_proc.kill() return def exists_file(self, filepath): """ Check if the file exits on the device Args: filepath: path to the file Returns: True or False if file found or not """ try: out = self.shell("ls \"%s\"" % filepath) except (AdbShellError, AdbError): return False else: return not ("No such file or directory" in out) def file_size(self, filepath): """ Get the file size Args: filepath: path to the file Returns: The file size Raises: AdbShellError if no such file """ out = self.shell(["ls", "-l", filepath]) try: file_size = int(out.split()[4]) except ValueError: # 安卓6.0.1系统得到的结果是[3]为文件大小 file_size = int(out.split()[3]) return file_size def _cleanup_forwards(self): """ Remove the local forward ports Returns: None """ # remove forward成功后,会改变self._forward_local_using的内容,因此需要copy一遍 # After remove_forward() is successful, self._forward_local_using will be changed, so it needs to be copied forward_local_list = copy(self._forward_local_using) for local in forward_local_list: try: self.remove_forward(local) except DeviceConnectionError: # if device is offline, ignore pass @property def line_breaker(self): """ Set carriage return and line break property for various platforms and SDK versions Returns: carriage return and line break string """ if not self._line_breaker: if self.sdk_version >= SDK_VERISON_ANDROID7: line_breaker = os.linesep else: line_breaker = '\r' + os.linesep self._line_breaker = line_breaker.encode("ascii") return self._line_breaker @property def display_info(self): """ Set device display properties (orientation, rotation and max values for x and y coordinates) Notes: if there is a lock screen detected, the function tries to unlock the device first Returns: device screen properties """ self._display_info_lock.acquire() if not self._display_info: self._display_info = self.get_display_info() self._display_info_lock.release() return self._display_info def get_display_info(self): """ Get information about device physical display (orientation, rotation and max values for x and y coordinates) Returns: device screen properties e.g { 'width': 1440, 'height': 2960, 'density': 4.0, 'orientation': 3, 'rotation': 270, 'max_x': 4095, 'max_y': 4095 } """ display_info = self.getPhysicalDisplayInfo() orientation = self.getDisplayOrientation() max_x, max_y = self.getMaxXY() display_info.update({ "orientation": orientation, "rotation": orientation * 90, "max_x": max_x, "max_y": max_y, }) return display_info def getMaxXY(self): """ Get device display maximum values for x and y coordinates Returns: max x and max y coordinates """ ret = self.shell('getevent -p').split('\n') max_x, max_y = None, None for i in ret: if i.find("0035") != -1: patten = re.compile(r'max [0-9]+') ret = patten.search(i) if ret: max_x = int(ret.group(0).split()[1]) if i.find("0036") != -1: patten = re.compile(r'max [0-9]+') ret = patten.search(i) if ret: max_y = int(ret.group(0).split()[1]) return max_x, max_y def getRestrictedScreen(self): """ Get value for mRestrictedScreen (without black border / virtual keyboard)` Returns: screen resolution mRestrictedScreen value as tuple (x, y) """ # get the effective screen resolution of the device result = None # get the corresponding mRestrictedScreen parameters according to the device serial number dumpsys_info = self.shell("dumpsys window") match = re.search(r'mRestrictedScreen=.+', dumpsys_info) if match: # like 'mRestrictedScreen=(0,0) 720x1184' infoline = match.group(0).strip() resolution = infoline.split(" ")[1].split("x") if isinstance(resolution, list) and len(resolution) == 2: result = int(str(resolution[0])), int(str(resolution[1])) return result def getPhysicalDisplayInfo(self): """ Get value for display dimension and density from `mPhysicalDisplayInfo` value obtained from `dumpsys` command. Returns: physical display info for dimension and density """ # use adb shell wm size displayInfo = {} try: wm_size = re.search( r'(?P<width>\d+)x(?P<height>\d+)\s*$', self.cmd('shell wm size', timeout=5)) except (AdbError, RuntimeError) as e: LOGGING.error(e) else: if wm_size: displayInfo = dict((k, int(v)) for k, v in wm_size.groupdict().items()) displayInfo['density'] = self._getDisplayDensity(strip=True) return displayInfo phyDispRE = re.compile( '.*PhysicalDisplayInfo{(?P<width>\d+) x (?P<height>\d+), .*, density (?P<density>[\d.]+).*') out = self.raw_shell('dumpsys display') m = phyDispRE.search(out) if m: for prop in ['width', 'height']: displayInfo[prop] = int(m.group(prop)) for prop in ['density']: # In mPhysicalDisplayInfo density is already a factor, no need to calculate displayInfo[prop] = float(m.group(prop)) return displayInfo # This could also be mSystem or mOverscanScreen phyDispRE = re.compile( '\s*mUnrestrictedScreen=\((?P<x>\d+),(?P<y>\d+)\) (?P<width>\d+)x(?P<height>\d+)') # This is known to work on older versions (i.e. API 10) where mrestrictedScreen is not available dispWHRE = re.compile( '\s*DisplayWidth=(?P<width>\d+) *DisplayHeight=(?P<height>\d+)') out = self.raw_shell('dumpsys window') m = phyDispRE.search(out, 0) if not m: m = dispWHRE.search(out, 0) if m: for prop in ['width', 'height']: displayInfo[prop] = int(m.group(prop)) for prop in ['density']: d = self._getDisplayDensity(strip=True) if d: displayInfo[prop] = d else: # No available density information displayInfo[prop] = -1.0 return displayInfo # gets C{mPhysicalDisplayInfo} values from dumpsys. This is a method to obtain display dimensions and density phyDispRE = re.compile( 'Physical size: (?P<width>\d+)x(?P<height>\d+).*Physical density: (?P<density>\d+)', re.S) m = phyDispRE.search(self.cmd('shell wm size; wm density', timeout=3)) if m: for prop in ['width', 'height']: displayInfo[prop] = int(m.group(prop)) for prop in ['density']: displayInfo[prop] = float(m.group(prop)) return displayInfo if not displayInfo: raise DeviceConnectionError( "Getting device screen information timed out") def _getDisplayDensity(self, strip=True): """ Get display density Args: strip: strip the output Returns: display density """ BASE_DPI = 160.0 d = self.getprop('ro.sf.lcd_density', strip) if d: return float(d) / BASE_DPI d = self.getprop('qemu.sf.lcd_density', strip) if d: return float(d) / BASE_DPI return -1.0 def getDisplayOrientation(self): """ Another way to get the display orientation, this works well for older devices (SDK version 15) Returns: display orientation information """ # another way to get orientation, for old sumsung device(sdk version 15) from xiaoma SurfaceFlingerRE = re.compile('orientation=(\d+)') output = self.shell('dumpsys SurfaceFlinger') m = SurfaceFlingerRE.search(output) if m: return int(m.group(1)) # Fallback method to obtain the orientation # See https://github.com/dtmilano/AndroidViewClient/issues/128 surfaceOrientationRE = re.compile('SurfaceOrientation:\s+(\d+)') output = self.shell('dumpsys input') m = surfaceOrientationRE.search(output) if m: return int(m.group(1)) displayFramesRE = re.compile(r"DisplayFrames.*r=(\d+)") output = self.shell('dumpsys window displays') m = displayFramesRE.search(output) if m: return int(m.group(1)) # We couldn't obtain the orientation warnings.warn("Could not obtain the orientation, return 0") return 0 def update_cur_display(self, display_info): """ Some phones support resolution modification, try to get the modified resolution from dumpsys adb shell dumpsys window displays | find "cur=" 本方法虽然可以更好地获取到部分修改过分辨率的手机信息 但是会因为cur=(\d+)x(\d+)的数值在不同设备上width和height的顺序可能不同,导致横竖屏识别出现问题 airtest不再使用本方法作为通用的屏幕尺寸获取方法,但依然可用于部分设备获取当前被修改过的分辨率 Examples: >>> # 部分三星和华为设备,若分辨率没有指定为最高,可能会导致点击偏移,可以用这个方式强制修改: >>> # For some Samsung and Huawei devices, if the resolution is not specified as the highest, >>> # it may cause click offset, which can be modified in this way: >>> dev = device() >>> info = dev.display_info >>> info2 = dev.adb.update_cur_display(info) >>> dev.display_info.update(info2) Args: display_info: the return of self.getPhysicalDisplayInfo() Returns: display_info """ # adb shell dumpsys window displays | find "init=" # 上面的命令行在dumpsys window里查找init=widthxheight,得到的结果是物理分辨率,且部分型号手机不止一个结果 # 如果改为读取 cur=widthxheight 的数据,得到的是修改过分辨率手机的结果(例如三星S8) actual = self.shell("dumpsys window displays") arr = re.findall(r'cur=(\d+)x(\d+)', actual) if len(arr) > 0: # 强制设定宽度width为更小的数字、height为更大的数字,避免因为各手机厂商返回结果的顺序不同导致问题 # Set the width to a smaller number and the height to a larger number width, height = min(list(map(int, arr[0]))), max( list(map(int, arr[0]))) display_info['physical_width'] = display_info['width'] display_info['physical_height'] = display_info['height'] display_info['width'], display_info['height'] = width, height return display_info def get_top_activity(self): """ Perform `adb shell dumpsys activity top` command search for the top activity Raises: AirtestError: if top activity cannot be obtained Returns: top activity as a tuple: (package_name, activity_name, pid) """ dat = self.shell('dumpsys activity top') activityRE = re.compile( r'\s*ACTIVITY ([A-Za-z0-9_.$]+)/([A-Za-z0-9_.$]+) \w+ pid=(\d+)') # in Android8.0 or higher, the result may be more than one m = activityRE.findall(dat) if m: return m[-1] else: raise AirtestError("Can not get top activity, output:%s" % dat) def is_keyboard_shown(self): """ Perform `adb shell dumpsys input_method` command and search for information if keyboard is shown Returns: True or False whether the keyboard is shown or not """ dim = self.shell('dumpsys input_method') if dim: return "mInputShown=true" in dim return False def is_screenon(self): """ Perform `adb shell dumpsys window policy` command and search for information if screen is turned on or off Raises: AirtestError: if screen state can't be detected Returns: True or False whether the screen is turned on or off """ screenOnRE = re.compile('mScreenOnFully=(true|false)') m = screenOnRE.search(self.shell('dumpsys window policy')) if m: return m.group(1) == 'true' else: # MIUI11 screenOnRE = re.compile( 'screenState=(SCREEN_STATE_ON|SCREEN_STATE_OFF)') m = screenOnRE.search(self.shell('dumpsys window policy')) if m: return m.group(1) == 'SCREEN_STATE_ON' raise AirtestError("Couldn't determine screen ON state") @retries(max_tries=3) def is_locked(self): """ Perform `adb shell dumpsys window policy` command and search for information if screen is locked or not Raises: AirtestError: if lock screen can't be detected Returns: True or False whether the screen is locked or not """ lockScreenRE = re.compile( '(?:mShowingLockscreen|isStatusBarKeyguard|showing)=(true|false)') m = lockScreenRE.search(self.shell('dumpsys window policy')) if not m: raise AirtestError("Couldn't determine screen lock state") return (m.group(1) == 'true') def unlock(self): """ Perform `adb shell input keyevent MENU` and `adb shell input keyevent BACK` commands to attempt to unlock the screen Returns: None Warnings: Might not work on all devices """ self.shell('input keyevent MENU') self.shell('input keyevent BACK') def get_package_version(self, package): """ Perform `adb shell dumpsys package` and search for information about given package version Args: package: package name Returns: None if no info has been found, otherwise package version """ package_info = self.shell(['dumpsys', 'package', package]) matcher = re.search(r'versionCode=(\d+)', package_info) if matcher: return int(matcher.group(1)) return None def list_app(self, third_only=False): """ Perform `adb shell pm list packages` to print all packages, optionally only those whose package name contains the text in FILTER. Options -f: see their associated file -d: filter to only show disabled packages -e: filter to only show enabled packages -s: filter to only show system packages -3: filter to only show third party packages -i: see the installer for the packages -u: also include uninstalled packages Args: third_only: print only third party packages Returns: list of packages """ cmd = ["pm", "list", "packages"] if third_only: cmd.append("-3") output = self.shell(cmd) packages = output.splitlines() # remove all empty string; "package:xxx" -> "xxx" packages = [p.split(":")[1] for p in packages if p] return packages def path_app(self, package): """ Perform `adb shell pm path` command to print the path to the package Args: package: package name Raises: AdbShellError: if any adb error occurs AirtestError: if package is not found on the device Returns: path to the package """ try: output = self.shell(['pm', 'path', package]) except AdbShellError: output = "" if 'package:' not in output: raise AirtestError('package not found, output:[%s]' % output) return output.split("package:")[1].strip() def check_app(self, package): """ Perform `adb shell dumpsys package` command and check if package exists on the device Args: package: package name Raises: AirtestError: if package is not found Returns: True if package has been found """ output = self.shell(['dumpsys', 'package', package]) pattern = r'Package\s+\[' + str(package) + '\]' match = re.search(pattern, output) if match is None: raise AirtestError('package "{}" not found'.format(package)) return True def start_app(self, package, activity=None): """ Perform `adb shell monkey` commands to start the application, if `activity` argument is `None`, then `adb shell am start` command is used. Args: package: package name activity: activity name Returns: None """ if not activity: try: ret = self.shell( ['monkey', '-p', package, '-c', 'android.intent.category.LAUNCHER', '1']) except AdbShellError as e: raise AirtestError( "Starting App: %s Failed! No activities found to run." % package) if "No activities found to run" in ret: raise AirtestError( "Starting App: %s Failed! No activities found to run." % package) else: self.shell(['am', 'start', '-n', '%s/%s.%s' % (package, package, activity)]) def start_app_timing(self, package, activity): """ Start the application and activity, and measure time Args: package: package name activity: activity name Returns: app launch time """ out = self.shell(['am', 'start', '-S', '-W', '%s/%s' % (package, activity), '-c', 'android.intent.category.LAUNCHER', '-a', 'android.intent.action.MAIN']) if not re.search(r"Status:\s*ok", out): raise AirtestError("Starting App: %s/%s Failed!" % (package, activity)) # matcher = re.search(r"TotalTime:\s*(\d+)", out) matcher = re.search(r"TotalTime:\s*(\d+)", out) if matcher: return int(matcher.group(1)) else: return 0 def stop_app(self, package): """ Perform `adb shell am force-stop` command to force stop the application Args: package: package name Returns: None """ self.shell(['am', 'force-stop', package]) def clear_app(self, package): """ Perform `adb shell pm clear` command to clear all application data Args: package: package name Returns: None """ self.shell(['pm', 'clear', package]) def text(self, content): """ Use adb shell input for text input Args: content: text to input Returns: None Examples: >>> dev = connect_device("Android:///") >>> dev.text("Hello World") >>> dev.text("test123") """ if content.isalpha(): self.shell(["input", "text", content]) else: # If it contains letters and numbers, input with `adb shell input text` may result in the wrong order for i in content: if i == " ": self.keyevent("KEYCODE_SPACE") else: self.shell(["input", "text", i]) def get_ip_address(self): """ Perform several set of commands to obtain the IP address. * `adb shell netcfg | grep wlan0` * `adb shell ifconfig` * `adb getprop dhcp.wlan0.ipaddress` Returns: None if no IP address has been found, otherwise return the IP address """ def get_ip_address_from_interface(interface): """Get device ip from target network interface.""" # android >= 6.0: ip -f inet addr show {interface} try: res = self.shell('ip -f inet addr show {}'.format(interface)) except AdbShellError: res = '' matcher = re.search(r"inet (\d+\.){3}\d+", res) if matcher: return matcher.group().split(" ")[-1] # android >= 6.0 backup method: ifconfig try: res = self.shell('ifconfig') except AdbShellError: res = '' matcher = re.search( interface + r'.*?inet addr:((\d+\.){3}\d+)', res, re.DOTALL) if matcher: return matcher.group(1) # android <= 6.0: netcfg try: res = self.shell('netcfg') except AdbShellError: res = '' matcher = re.search(interface + r'.* ((\d+\.){3}\d+)/\d+', res) if matcher: return matcher.group(1) # android <= 6.0 backup method: getprop dhcp.{}.ipaddress try: res = self.shell('getprop dhcp.{}.ipaddress'.format(interface)) except AdbShellError: res = '' matcher = IP_PATTERN.search(res) if matcher: return matcher.group(0) # sorry, no more methods... return None interfaces = ('eth0', 'eth1', 'wlan0') for i in interfaces: ip = get_ip_address_from_interface(i) if ip and not ip.startswith('127.') and not ip.startswith('169.'): return ip return None def get_gateway_address(self): """ Perform several set of commands to obtain the gateway address. * `adb getprop dhcp.wlan0.gateway` * `adb shell netcfg | grep wlan0` Returns: None if no gateway address has been found, otherwise return the gateway address """ def ip2int(ip): return reduce(lambda a, b: ( a << 8) + b, map(int, ip.split('.')), 0) def int2ip(n): return '.'.join( [str(n >> (i << 3) & 0xFF) for i in range(0, 4)[::-1]]) try: res = self.shell('getprop dhcp.wlan0.gateway') except AdbShellError: res = '' matcher = IP_PATTERN.search(res) if matcher: return matcher.group(0) ip = self.get_ip_address() if not ip: return None mask_len = self._get_subnet_mask_len() gateway = (ip2int(ip) & (((1 << mask_len) - 1) << (32 - mask_len))) + 1 return int2ip(gateway) def _get_subnet_mask_len(self): """ Perform `adb shell netcfg | grep wlan0` command to obtain mask length Returns: 17 if mask length could not be detected, otherwise the mask length """ try: res = self.shell('netcfg') except AdbShellError: pass else: matcher = re.search(r'wlan0.* (\d+\.){3}\d+/(\d+) ', res) if matcher: return int(matcher.group(2)) # 获取不到网段长度就默认取17 print('[iputils WARNING] fail to get subnet mask len. use 17 as default.') return 17 def get_memory(self): res = self.shell("dumpsys meminfo") pat = re.compile(r".*Total RAM:\s+(\S+)\s+", re.DOTALL) _str = pat.match(res).group(1) if ',' in _str: _list = _str.split(',') _num = int(_list[0]) _num = round(_num + (float(_list[1]) / 1000.0)) else: _num = round(float(_str) / 1000.0 / 1000.0) res = str(_num) + 'G' return res def get_storage(self): res = self.shell("df /data") pat = re.compile(r".*\/data\s+(\S+)", re.DOTALL) if pat.match(res): _str = pat.match(res).group(1) else: pat = re.compile( r".*\s+(\S+)\s+\S+\s+\S+\s+\S+\s+\/data", re.DOTALL) _str = pat.match(res).group(1) if 'G' in _str: _num = round(float(_str[:-1])) elif 'M' in _str: _num = round(float(_str[:-1]) / 1000.0) else: _num = round(float(_str) / 1000.0 / 1000.0) if _num > 64: res = '128G' elif _num > 32: res = '64G' elif _num > 16: res = '32G' elif _num > 8: res = '16G' else: res = '8G' return res def get_cpuinfo(self): res = self.shell("cat /proc/cpuinfo").strip() cpuNum = res.count("processor") pat = re.compile(r'Hardware\s+:\s+(\w+.*)') m = pat.search(res) if not m: pat = re.compile(r'Processor\s+:\s+(\w+.*)') m = pat.match(res) cpuName = m.group(1).replace('\r', '') return dict(cpuNum=cpuNum, cpuName=cpuName) def get_cpufreq(self): res = self.shell( "cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq") num = round(float(res) / 1000 / 1000, 1) res = str(num) + 'GHz' return res.strip() def get_cpuabi(self): res = self.shell("getprop ro.product.cpu.abi") return res.strip() def get_gpu(self): res = self.shell("dumpsys SurfaceFlinger") pat = re.compile(r'GLES:\s+(.*)') m = pat.search(res) if not m: return None _list = m.group(1).split(',') gpuModel = "" opengl = "" if len(_list) > 0: gpuModel = _list[1].strip() if len(_list) > 1: m2 = re.search(r'(\S+\s+\S+\s+\S+).*', _list[2]) if m2: opengl = m2.group(1) return dict(gpuModel=gpuModel, opengl=opengl) def get_model(self): return self.getprop("ro.product.model") def get_manufacturer(self): return self.getprop("ro.product.manufacturer") def get_device_info(self): """ Get android device information, including: memory/storage/display/cpu/gpu/model/manufacturer... Returns: Dict of info """ handlers = { "platform": "Android", "serialno": self.serialno, "memory": self.get_memory, "storage": self.get_storage, "display": self.getPhysicalDisplayInfo, "cpuinfo": self.get_cpuinfo, "cpufreq": self.get_cpufreq, "cpuabi": self.get_cpuabi, "sdkversion": self.sdk_version, "gpu": self.get_gpu, "model": self.get_model, "manufacturer": self.get_manufacturer, # "battery": getBatteryCapacity } ret = {} for k, v in handlers.items(): if callable(v): try: value = v() except Exception: value = None ret[k] = value else: ret[k] = v return ret def get_display_of_all_screen(self, info, package=None): """ Perform `adb shell dumpsys window windows` commands to get window display of application. Args: info: device screen properties package: package name, default to the package of top activity Returns: None if adb command failed to run, otherwise return device screen properties(portrait mode) eg. (offset_x, offset_y, screen_width, screen_height) """ output = self.shell("dumpsys window windows") windows = output.split("Window #") offsetx, offsety, width, height = 0, 0, info['width'], info['height'] package = self._search_for_current_package( output) if package is None else package if package: for w in windows: if "package=%s" % package in w: arr = re.findall( r'Frames: containing=\[(\d+\.?\d*),(\d+\.?\d*)]\[(\d+\.?\d*),(\d+\.?\d*)]', w) if len(arr) >= 1 and len(arr[0]) == 4: offsetx, offsety, width, height = float(arr[0][0]), float( arr[0][1]), float(arr[0][2]), float(arr[0][3]) if info["orientation"] in [1, 3]: offsetx, offsety, width, height = offsety, offsetx, height, width width, height = width - offsetx, height - offsety return { "offset_x": offsetx, "offset_y": offsety, "offset_width": width, "offset_height": height, } def _search_for_current_package(self, ret): """ Search for current app package name from the output of command "adb shell dumpsys window windows" Returns: package name if exists else "" """ try: packageRE = re.compile( '\s*mCurrentFocus=Window{.* ([A-Za-z0-9_.]+)/[A-Za-z0-9_.]+}') m = packageRE.findall(ret) if m: return m[-1] else: return self.get_top_activity()[0] except Exception as e: print("[Error] Cannot get current top activity") return ""
class ADB(object): '''adb client object class''' def __init__(self, serialno=None, adb_path=None, server_addr=None, display_id=None, input_event=None): pass @staticmethod def get_adb_path(): ''' Returns the path to the adb executable. Checks if adb process is running, returns the running process path. If adb process is not running, checks if ANDROID_HOME environment variable is set. Constructs the adb path using ANDROID_HOME and returns it if set. If adb process is not running and ANDROID_HOME is not set, uses built-in adb path. Returns: str: The path to the adb executable. ''' pass @staticmethod def builtin_adb_path(): ''' Return built-in adb executable path Returns: adb executable path ''' pass def _set_cmd_options(self, server_addr=None): ''' Set communication parameters (host and port) between adb server and adb client Args: server_addr: adb server address, default is ["127.0.0.1", 5037] Returns: None ''' pass def start_server(self): ''' Perform `adb start-server` command to start the adb server Returns: None ''' pass def kill_server(self): ''' Perform `adb kill-server` command to kill the adb server Returns: None ''' pass def version(self): ''' Perform `adb version` command and return the command output Returns: command output ''' pass def start_cmd(self, cmds, device=True): ''' Start a subprocess with adb command(s) Args: cmds: command(s) to be run device: if True, the device serial number must be specified by `-s serialno` argument Raises: RuntimeError: if `device` is True and serialno is not specified Returns: a subprocess ''' pass def cmd(self, cmds, device=True, ensure_unicode=True, timeout=None): ''' Run the adb command(s) in subprocess and return the standard output Args: cmds: command(s) to be run device: if True, the device serial number must be specified by -s serialno argument ensure_unicode: encode/decode unicode of standard outputs (stdout, stderr) timeout: timeout in seconds Raises: DeviceConnectionError: if any error occurs when connecting the device AdbError: if any other adb error occurs Returns: command(s) standard output (stdout) ''' pass def close_proc_pipe(self, proc): '''close stdin/stdout/stderr of subprocess.Popen.''' pass def close_pipe(pipe): pass def devices(self, state=None): ''' Perform `adb devices` command and return the list of adb devices Args: state: optional parameter to filter devices in specific state Returns: list od adb devices ''' pass def connect(self, force=False): ''' Perform `adb connect` command, remote devices are preferred to connect first Args: force: force connection, default is False Returns: None ''' pass def disconnect(self): ''' Perform `adb disconnect` command Returns: None ''' pass def get_status(self): ''' Perform `adb get-state` and return the device status Raises: AdbError: if status cannot be obtained from the device Returns: None if status is `not found`, otherwise return the standard output from `adb get-state` command ''' pass def wait_for_device(self, timeout=5): ''' Perform `adb wait-for-device` command Args: timeout: time interval in seconds to wait for device Raises: DeviceConnectionError: if device is not available after timeout Returns: None ''' pass def start_shell(self, cmds): ''' Handle `adb shell` command(s) Args: cmds: adb shell command(s) Returns: None ''' pass def raw_shell(self, cmds, ensure_unicode=True): ''' Handle `adb shell` command(s) with unicode support Args: cmds: adb shell command(s) ensure_unicode: decode/encode unicode True or False, default is True Returns: command(s) output ''' pass def shell(self, cmd): ''' Run the `adb shell` command on the device Args: cmd: a command to be run Raises: AdbShellError: if command return value is non-zero or if any other `AdbError` occurred Returns: command output ''' pass def keyevent(self, keyname): ''' Perform `adb shell input keyevent` command on the device Args: keyname: key event name Returns: None ''' pass def getprop(self, key, strip=True): ''' Perform `adb shell getprop` on the device Args: key: key value for property strip: True or False to strip the return carriage and line break from returned string Returns: propery value ''' pass @property @retries(max_tries=3) def sdk_version(self): ''' Get the SDK version from the device Returns: SDK version ''' pass def push(self, local, remote): ''' Push file or folder to the specified directory to the device Args: local: local file or folder to be copied to the device remote: destination on the device where the file will be copied Returns: The file path saved in the phone may be enclosed in quotation marks, eg. '"test\ file.txt"' Examples: >>> adb = device().adb >>> adb.push("test.txt", "/data/local/tmp") >>> new_name = adb.push("test space.txt", "/data/local/tmp") # test the space in file name >>> print(new_name) "/data/local/tmp/test\ space.txt" >>> adb.shell("rm " + new_name) >>> adb.push("test_dir", "/sdcard/Android/data/com.test.package/files") >>> adb.push("test_dir", "/sdcard/Android/data/com.test.package/files/test_dir") ''' pass def pull(self, remote, local=""): ''' Perform `adb pull` command Args: remote: remote file to be downloaded from the device local: local destination where the file will be downloaded from the device Note: If <=PY3, the path in Windows cannot be the root directory, and cannot contain symbols such as /g in the path 注意:如果低于PY3,windows中路径不能为根目录,并且不能包含/g等符号在路径里 Returns: None ''' pass def forward(self, local, remote, no_rebind=True): ''' Perform `adb forward` command Args: local: local tcp port to be forwarded remote: tcp port of the device where the local tcp port will be forwarded no_rebind: True or False Returns: None ''' pass def get_forwards(self): ''' Perform `adb forward --list`command Yields: serial number, local tcp port, remote tcp port Returns: None ''' pass @classmethod def get_available_forward_local(cls): ''' Generate a pseudo random number between 11111 and 20000 that will be used as local forward port Returns: integer between 11111 and 20000 Note: use `forward --no-rebind` to check if port is available ''' pass @retries(3) def setup_forward(self, device_port, no_rebind=True): ''' Generate pseudo random local port and check if the port is available. Args: device_port: it can be string or the value of the `function(localport)`, e.g. `"tcp:5001"` or `"localabstract:{}".format` no_rebind: adb forward --no-rebind option Returns: local port and device port ''' pass def remove_forward(self, local=None): ''' Perform `adb forward --remove` command Args: local: local tcp port Returns: None ''' pass def install_app(self, filepath, replace=False, install_options=None): ''' Perform `adb install` command Args: filepath: full path to file to be installed on the device replace: force to replace existing application, default is False e.g.["-t", # allow test packages "-l", # forward lock application, "-s", # install application on sdcard, "-d", # allow version code downgrade (debuggable packages only) "-g", # grant all runtime permissions ] Returns: command output ''' pass def install_multiple_app(self, filepath, replace=False, install_options=None): ''' Perform `adb install-multiple` command Args: filepath: full path to file to be installed on the device replace: force to replace existing application, default is False install_options: list of options e.g.["-t", # allow test packages "-l", # forward lock application, "-s", # install application on sdcard, "-d", # allow version code downgrade (debuggable packages only) "-g", # grant all runtime permissions "-p", # partial application install (install-multiple only) ] Returns: command output ''' pass def pm_install(self, filepath, replace=False, install_options=None): ''' Perform `adb push` and `adb install` commands Note: This is more reliable and recommended way of installing `.apk` files Args: filepath: full path to file to be installed on the device replace: force to replace existing application, default is False install_options: list of options e.g.["-t", # allow test packages "-l", # forward lock application, "-s", # install application on sdcard, "-d", # allow version code downgrade (debuggable packages only) "-g", # grant all runtime permissions ] Returns: None ''' pass def uninstall_app(self, package): ''' Perform `adb uninstall` command Args: package: package name to be uninstalled from the device Returns: command output ''' pass def pm_uninstall(self, package, keepdata=False): ''' Perform `adb uninstall` command and delete all related application data Args: package: package name to be uninstalled from the device keepdata: True or False, keep application data after removing the app from the device Returns: command output ''' pass def snapshot(self): ''' Take the screenshot of the device display Returns: command output (stdout) ''' pass def touch(self, tuple_xy): ''' Perform user input (touchscreen) on given coordinates Args: tuple_xy: coordinates (x, y) Returns: None ''' pass def swipe(self, tuple_x0y0, tuple_x1y1, duration=500): ''' Perform user input (swipe screen) from start point (x,y) to end point (x,y) Args: tuple_x0y0: start point coordinates (x, y) tuple_x1y1: end point coordinates (x, y) duration: time interval for action, default 500 Raises: AirtestError: if SDK version is not supported Returns: None ''' pass def logcat(self, grep_str="", extra_args="", read_timeout=10): ''' Perform `adb shell logcat` command and search for given patterns Args: grep_str: pattern to filter from the logcat output extra_args: additional logcat arguments read_timeout: time interval to read the logcat, default is 10 Yields: logcat lines containing filtered patterns Returns: None ''' pass def exists_file(self, filepath): ''' Check if the file exits on the device Args: filepath: path to the file Returns: True or False if file found or not ''' pass def file_size(self, filepath): ''' Get the file size Args: filepath: path to the file Returns: The file size Raises: AdbShellError if no such file ''' pass def _cleanup_forwards(self): ''' Remove the local forward ports Returns: None ''' pass @property def line_breaker(self): ''' Set carriage return and line break property for various platforms and SDK versions Returns: carriage return and line break string ''' pass @property def display_info(self): ''' Set device display properties (orientation, rotation and max values for x and y coordinates) Notes: if there is a lock screen detected, the function tries to unlock the device first Returns: device screen properties ''' pass def get_display_info(self): ''' Get information about device physical display (orientation, rotation and max values for x and y coordinates) Returns: device screen properties e.g { 'width': 1440, 'height': 2960, 'density': 4.0, 'orientation': 3, 'rotation': 270, 'max_x': 4095, 'max_y': 4095 } ''' pass def getMaxXY(self): ''' Get device display maximum values for x and y coordinates Returns: max x and max y coordinates ''' pass def getRestrictedScreen(self): ''' Get value for mRestrictedScreen (without black border / virtual keyboard)` Returns: screen resolution mRestrictedScreen value as tuple (x, y) ''' pass def getPhysicalDisplayInfo(self): ''' Get value for display dimension and density from `mPhysicalDisplayInfo` value obtained from `dumpsys` command. Returns: physical display info for dimension and density ''' pass def _getDisplayDensity(self, strip=True): ''' Get display density Args: strip: strip the output Returns: display density ''' pass def getDisplayOrientation(self): ''' Another way to get the display orientation, this works well for older devices (SDK version 15) Returns: display orientation information ''' pass def update_cur_display(self, display_info): ''' Some phones support resolution modification, try to get the modified resolution from dumpsys adb shell dumpsys window displays | find "cur=" 本方法虽然可以更好地获取到部分修改过分辨率的手机信息 但是会因为cur=(\d+)x(\d+)的数值在不同设备上width和height的顺序可能不同,导致横竖屏识别出现问题 airtest不再使用本方法作为通用的屏幕尺寸获取方法,但依然可用于部分设备获取当前被修改过的分辨率 Examples: >>> # 部分三星和华为设备,若分辨率没有指定为最高,可能会导致点击偏移,可以用这个方式强制修改: >>> # For some Samsung and Huawei devices, if the resolution is not specified as the highest, >>> # it may cause click offset, which can be modified in this way: >>> dev = device() >>> info = dev.display_info >>> info2 = dev.adb.update_cur_display(info) >>> dev.display_info.update(info2) Args: display_info: the return of self.getPhysicalDisplayInfo() Returns: display_info ''' pass def get_top_activity(self): ''' Perform `adb shell dumpsys activity top` command search for the top activity Raises: AirtestError: if top activity cannot be obtained Returns: top activity as a tuple: (package_name, activity_name, pid) ''' pass def is_keyboard_shown(self): ''' Perform `adb shell dumpsys input_method` command and search for information if keyboard is shown Returns: True or False whether the keyboard is shown or not ''' pass def is_screenon(self): ''' Perform `adb shell dumpsys window policy` command and search for information if screen is turned on or off Raises: AirtestError: if screen state can't be detected Returns: True or False whether the screen is turned on or off ''' pass @retries(max_tries=3) def is_locked(self): ''' Perform `adb shell dumpsys window policy` command and search for information if screen is locked or not Raises: AirtestError: if lock screen can't be detected Returns: True or False whether the screen is locked or not ''' pass def unlock(self): ''' Perform `adb shell input keyevent MENU` and `adb shell input keyevent BACK` commands to attempt to unlock the screen Returns: None Warnings: Might not work on all devices ''' pass def get_package_version(self, package): ''' Perform `adb shell dumpsys package` and search for information about given package version Args: package: package name Returns: None if no info has been found, otherwise package version ''' pass def list_app(self, third_only=False): ''' Perform `adb shell pm list packages` to print all packages, optionally only those whose package name contains the text in FILTER. Options -f: see their associated file -d: filter to only show disabled packages -e: filter to only show enabled packages -s: filter to only show system packages -3: filter to only show third party packages -i: see the installer for the packages -u: also include uninstalled packages Args: third_only: print only third party packages Returns: list of packages ''' pass def path_app(self, package): ''' Perform `adb shell pm path` command to print the path to the package Args: package: package name Raises: AdbShellError: if any adb error occurs AirtestError: if package is not found on the device Returns: path to the package ''' pass def check_app(self, package): ''' Perform `adb shell dumpsys package` command and check if package exists on the device Args: package: package name Raises: AirtestError: if package is not found Returns: True if package has been found ''' pass def start_app(self, package, activity=None): ''' Perform `adb shell monkey` commands to start the application, if `activity` argument is `None`, then `adb shell am start` command is used. Args: package: package name activity: activity name Returns: None ''' pass def start_app_timing(self, package, activity): ''' Start the application and activity, and measure time Args: package: package name activity: activity name Returns: app launch time ''' pass def stop_app(self, package): ''' Perform `adb shell am force-stop` command to force stop the application Args: package: package name Returns: None ''' pass def clear_app(self, package): ''' Perform `adb shell pm clear` command to clear all application data Args: package: package name Returns: None ''' pass def text(self, content): ''' Use adb shell input for text input Args: content: text to input Returns: None Examples: >>> dev = connect_device("Android:///") >>> dev.text("Hello World") >>> dev.text("test123") ''' pass def get_ip_address(self): ''' Perform several set of commands to obtain the IP address. * `adb shell netcfg | grep wlan0` * `adb shell ifconfig` * `adb getprop dhcp.wlan0.ipaddress` Returns: None if no IP address has been found, otherwise return the IP address ''' pass def get_ip_address_from_interface(interface): '''Get device ip from target network interface.''' pass def get_gateway_address(self): ''' Perform several set of commands to obtain the gateway address. * `adb getprop dhcp.wlan0.gateway` * `adb shell netcfg | grep wlan0` Returns: None if no gateway address has been found, otherwise return the gateway address ''' pass def ip2int(ip): pass def int2ip(n): pass def _get_subnet_mask_len(self): ''' Perform `adb shell netcfg | grep wlan0` command to obtain mask length Returns: 17 if mask length could not be detected, otherwise the mask length ''' pass def get_memory(self): pass def get_storage(self): pass def get_cpuinfo(self): pass def get_cpufreq(self): pass def get_cpuabi(self): pass def get_gpu(self): pass def get_model(self): pass def get_manufacturer(self): pass def get_device_info(self): ''' Get android device information, including: memory/storage/display/cpu/gpu/model/manufacturer... Returns: Dict of info ''' pass def get_display_of_all_screen(self, info, package=None): ''' Perform `adb shell dumpsys window windows` commands to get window display of application. Args: info: device screen properties package: package name, default to the package of top activity Returns: None if adb command failed to run, otherwise return device screen properties(portrait mode) eg. (offset_x, offset_y, screen_width, screen_height) ''' pass def _search_for_current_package(self, ret): ''' Search for current app package name from the output of command "adb shell dumpsys window windows" Returns: package name if exists else "" ''' pass
91
70
22
3
11
8
3
0.72
1
19
5
0
74
12
77
77
1,801
321
864
283
774
619
783
265
702
15
1
5
265
3,447
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_yosemite.py
tests.test_yosemite.TestIme
class TestIme(unittest.TestCase): @classmethod def setUpClass(cls): cls.adb = ADB() devices = cls.adb.devices() if not devices: raise RuntimeError("At lease one adb device required") cls.adb.serialno = devices[0][0] cls.ime = YosemiteIme(cls.adb) cls.ime.start() def test_text(self): self.ime.text("nimei") self.ime.text("你妹") def test_escape_text(self): self.ime.text("$call org/org->create_org($id,'test123')") self.ime.text("#@$%^&&*)_+!") def test_code(self): self.ime.text("test code") self.ime.code("2") def test_0_install(self): self.ime.yosemite.install_or_upgrade() self.ime.text("安装") def test_end(cls): cls.ime.end()
class TestIme(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_text(self): pass def test_escape_text(self): pass def test_code(self): pass def test_0_install(self): pass def test_end(cls): pass
8
0
4
0
4
0
1
0.04
1
3
2
0
5
0
6
78
30
6
24
9
16
1
23
8
16
2
2
1
7
3,448
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_maxtouch.py
tests.test_maxtouch.TestMaxTouch
class TestMaxTouch(TestMaxTouchBase): def test_touch(self): self.maxtouch.touch((100, 100)) def test_swipe(self): self.maxtouch.swipe((100, 100), (200, 200)) def test_swipe_along(self): self.maxtouch.swipe_along([(100, 100), (200, 200), (300, 300)]) def test_two_finger_swipe(self): self.maxtouch.two_finger_swipe((100, 100), (200, 200)) def test_pinch(self): self.maxtouch.pinch() self.maxtouch.pinch(in_or_out='out')
class TestMaxTouch(TestMaxTouchBase): def test_touch(self): pass def test_swipe(self): pass def test_swipe_along(self): pass def test_two_finger_swipe(self): pass def test_pinch(self): pass
6
0
2
0
2
0
1
0
1
0
0
1
5
0
5
80
17
5
12
6
6
0
12
6
6
1
3
0
5
3,449
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/error.py
airtest.aircv.error.TemplateInputError
class TemplateInputError(BaseError): """Resolution input is not right."""
class TemplateInputError(BaseError): '''Resolution input is not right.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
3,450
AirtestProject/Airtest
AirtestProject_Airtest/airtest/aircv/keypoint_matching.py
airtest.aircv.keypoint_matching.AKAZEMatching
class AKAZEMatching(KeypointMatching): """AKAZE Matching.""" METHOD_NAME = "AKAZE" # 日志中的方法名 def init_detector(self): """Init keypoint detector object.""" self.detector = cv2.AKAZE_create() # create BFMatcher object: self.matcher = cv2.BFMatcher(cv2.NORM_L1)
class AKAZEMatching(KeypointMatching): '''AKAZE Matching.''' def init_detector(self): '''Init keypoint detector object.''' pass
2
2
5
0
3
3
1
1
1
0
0
0
1
2
1
17
10
2
5
5
3
5
5
5
3
1
2
0
1
3,451
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/android/touch_methods/base_touch.py
airtest.core.android.touch_methods.base_touch.BaseTouch
class BaseTouch(object): """ A super class for Minitouch or Maxtouch """ def __init__(self, adb, backend=False, size_info=None, input_event=None, *args, **kwargs): self.adb = adb self.backend = backend self.server_proc = None self.client = None self.size_info = None self.input_event = input_event self.handle = None self.size_info = size_info or self.adb.get_display_info() self.default_pressure = 50 self.path_in_android = "" reg_cleanup(self.teardown) @ready_method def install_and_setup(self): """ Install and setup airtest touch Returns: None """ self.install() self.setup_server() if self.backend: self.setup_client_backend() else: self.setup_client() def uninstall(self): """ Uninstall airtest touch Returns: None """ raise NotImplemented def install(self): """ Install airtest touch Returns: None """ raise NotImplemented def setup_server(self): """ Setip touch server and adb forward Returns: server process """ raise NotImplemented @retry_when_connection_error def safe_send(self, data): """ Send data to client Args: data: data to send Raises: Exception: when data cannot be sent Returns: None """ if isinstance(data, six.text_type): data = data.encode('utf-8') # 如果连接异常,会抛出ConnectionAbortedError,并自动重试一次 self.client.send(data) def _backend_worker(self): """ Backend worker queue thread Returns: None """ while not self.backend_stop_event.isSet(): cmd = self.backend_queue.get() if cmd is None: break self.safe_send(cmd) def setup_client_backend(self): """ Setup backend client thread as daemon Returns: None """ self.backend_queue = queue.Queue() self.backend_stop_event = threading.Event() self.setup_client() t = threading.Thread(target=self._backend_worker, name="airtouch") # t.daemon = True t.start() self.backend_thread = t self.handle = self.backend_queue.put def setup_client(self): """ Setup client Returns: None """ raise NotImplemented def teardown(self): """ Stop the server and client Returns: None """ if hasattr(self, "backend_stop_event"): self.backend_stop_event.set() self.backend_queue.put(None) if self.client: self.client.close() if self.server_proc: kill_proc(self.server_proc) def transform_xy(self, x, y): """ Transform coordinates (x, y) according to the device display Args: x: coordinate x y: coordinate y Returns: transformed coordinates (x, y) """ return x, y @on_method_ready('install_and_setup') def perform(self, motion_events, interval=0.01): """ Perform a sequence of motion events including: UpEvent, DownEvent, MoveEvent, SleepEvent Args: motion_events: a list of MotionEvent instances interval: minimum interval between events Returns: None """ for event in motion_events: if isinstance(event, SleepEvent): time.sleep(event.seconds) else: cmd = event.getcmd(transform=self.transform_xy) self.handle(cmd) time.sleep(interval) @on_method_ready('install_and_setup') def touch(self, tuple_xy, duration=0.01): """ Perform touch event minitouch protocol example:: d 0 10 10 50 c <wait in your own code> u 0 c Args: tuple_xy: coordinates (x, y) duration: time interval for touch event, default is 0.01 Returns: None """ touch_events = [DownEvent( tuple_xy, pressure=self.default_pressure), SleepEvent(duration), UpEvent()] self.perform(touch_events) def __swipe_move(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5): """ Return a sequence of swipe motion events (only MoveEvent) minitouch protocol example:: d 0 0 0 50 c m 0 20 0 50 c m 0 40 0 50 c m 0 60 0 50 c m 0 80 0 50 c m 0 100 0 50 c u 0 c Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: [MoveEvent(from_x, from_y), ..., MoveEvent(to_x, to_y)] """ from_x, from_y = tuple_from_xy to_x, to_y = tuple_to_xy ret = [] interval = float(duration) / (steps + 1) for i in range(1, steps): ret.append(MoveEvent((from_x + (to_x - from_x) * i / steps, from_y + (to_y - from_y) * i / steps))) ret.append(SleepEvent(interval)) ret += [MoveEvent((to_x, to_y), pressure=self.default_pressure), SleepEvent(interval)] return ret @on_method_ready('install_and_setup') def swipe_along(self, coordinates_list, duration=0.8, steps=5): """ Perform swipe event across multiple points in sequence. Args: coordinates_list: list of coordinates: [(x1, y1), (x2, y2), (x3, y3)] duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: None """ tuple_from_xy = coordinates_list[0] swipe_events = [ DownEvent(tuple_from_xy, pressure=self.default_pressure), SleepEvent(0.1)] for tuple_to_xy in coordinates_list[1:]: swipe_events += self.__swipe_move(tuple_from_xy, tuple_to_xy, duration=duration, steps=steps) tuple_from_xy = tuple_to_xy swipe_events.append(UpEvent()) self.perform(swipe_events) @on_method_ready('install_and_setup') def swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5): """ Perform swipe event. Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: None """ swipe_events = [ DownEvent(tuple_from_xy, pressure=self.default_pressure), SleepEvent(0.1)] swipe_events += self.__swipe_move(tuple_from_xy, tuple_to_xy, duration=duration, steps=steps) swipe_events.append(UpEvent()) self.perform(swipe_events) @on_method_ready('install_and_setup') def two_finger_swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5, offset=(0, 50)): """ Perform two finger swipe action minitouch protocol example:: d 0 0 0 50 d 1 1 0 50 c m 0 20 0 50 m 1 21 0 50 c m 0 40 0 50 m 1 41 0 50 c m 0 60 0 50 m 1 61 0 50 c m 0 80 0 50 m 1 81 0 50 c m 0 100 0 50 m 1 101 0 50 c u 0 u 1 c Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 offset: coordinate offset of the second finger, default is (0, 50) Returns: None """ from_x, from_y = tuple_from_xy to_x, to_y = tuple_to_xy # 根据偏移量计算第二个手指的坐标 from_x2, from_y2 = (min(max(0, from_x + offset[0]), self.size_info['width']), min(max(0, from_y + offset[1]), self.size_info['height'])) to_x2, to_y2 = (min(max(0, to_x + offset[0]), self.size_info['width']), min(max(0, to_y + offset[1]), self.size_info['height'])) swipe_events = [DownEvent(tuple_from_xy, contact=0, pressure=self.default_pressure), DownEvent((from_x2, from_y2), contact=1, pressure=self.default_pressure), ] interval = float(duration) / (steps + 1) for i in range(1, steps + 1): move_events = [ SleepEvent(interval), MoveEvent((from_x + ((to_x - from_x) * i / steps), from_y + (to_y - from_y) * i / steps), contact=0, pressure=self.default_pressure), MoveEvent((from_x2 + (to_x2 - from_x2) * i / steps, from_y2 + (to_y2 - from_y2) * i / steps), contact=1, pressure=self.default_pressure), ] swipe_events.extend(move_events) swipe_events.extend([UpEvent(contact=0), UpEvent(contact=1)]) self.perform(swipe_events) @on_method_ready('install_and_setup') def pinch(self, center=None, percent=0.5, duration=0.5, steps=5, in_or_out='in'): """ Perform pinch action minitouch protocol example:: d 0 0 100 50 d 1 100 0 50 c m 0 10 90 50 m 1 90 10 50 c m 0 20 80 50 m 1 80 20 50 c m 0 20 80 50 m 1 80 20 50 c m 0 30 70 50 m 1 70 30 50 c m 0 40 60 50 m 1 60 40 50 c m 0 50 50 50 m 1 50 50 50 c u 0 u 1 c Args: center: the center point of the pinch operation percent: pinch distance to half of screen, default is 0.5 duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 in_or_out: pinch in or pinch out, default is 'in' Returns: None Raises: TypeError: An error occurred when center is not a list/tuple or None """ w, h = self.size_info['width'], self.size_info['height'] if isinstance(center, (list, tuple)): x0, y0 = center elif center is None: x0, y0 = w / 2, h / 2 else: raise TypeError( "center should be None or list/tuple, not %s" % repr(center)) x1, y1 = x0 - w * percent / 2, y0 - h * percent / 2 x2, y2 = x0 + w * percent / 2, y0 + h * percent / 2 pinch_events = [] interval = float(duration) / (steps + 1) # 根据in还是out,设定双指滑动的起始和结束坐标 if in_or_out == 'in': start_pos1_x, start_pos1_y = x1, y1 start_pos2_x, start_pos2_y = x2, y2 end_pos1_x, end_pos1_y = x0, y0 end_pos2_x, end_pos2_y = x0, y0 else: start_pos1_x, start_pos1_y = x0, y0 start_pos2_x, start_pos2_y = x0, y0 end_pos1_x, end_pos1_y = x1, y1 end_pos2_x, end_pos2_y = x2, y2 # 开始定义pinch的操作 pinch_events.extend([ DownEvent((start_pos1_x, start_pos1_y), contact=0, pressure=self.default_pressure), DownEvent((start_pos2_x, start_pos2_y), contact=1, pressure=self.default_pressure) ]) for i in range(1, steps): pinch_events.extend([ SleepEvent(interval), MoveEvent((start_pos1_x + (end_pos1_x - start_pos1_x) * i / steps, start_pos1_y + (end_pos1_y - start_pos1_y) * i / steps), contact=0, pressure=self.default_pressure), MoveEvent((start_pos2_x + (end_pos2_x - start_pos2_x) * i / steps, start_pos2_y + (end_pos2_y - start_pos2_y) * i / steps), contact=1, pressure=self.default_pressure) ]) pinch_events.extend([ SleepEvent(interval), MoveEvent((end_pos1_x, end_pos1_y), contact=0, pressure=self.default_pressure), MoveEvent((end_pos2_x, end_pos2_y), contact=1, pressure=self.default_pressure) ]) pinch_events.extend([UpEvent(contact=0), UpEvent(contact=1)]) self.perform(pinch_events) @on_method_ready('install_and_setup') def operate(self, args): """ Perform down, up and move actions Args: args: action arguments, dictionary containing type and x, y coordinates, e.g.:: { "type" : "down", "x" : 10, "y" : 10 } Raises: RuntimeError: is invalid arguments are provided Returns: None """ if args["type"] == "down": x, y = self.transform_xy(args["x"], args["y"]) cmd = "d 0 {x} {y} {pressure}\nc\n".format( x=x, y=y, pressure=self.default_pressure) elif args["type"] == "move": x, y = self.transform_xy(args["x"], args["y"]) cmd = "m 0 {x} {y} {pressure}\nc\n".format( x=x, y=y, pressure=self.default_pressure) elif args["type"] == "up": cmd = "u 0\nc\n" else: raise RuntimeError("invalid operate args: {}".format(args)) self.handle(cmd)
class BaseTouch(object): ''' A super class for Minitouch or Maxtouch ''' def __init__(self, adb, backend=False, size_info=None, input_event=None, *args, **kwargs): pass @ready_method def install_and_setup(self): ''' Install and setup airtest touch Returns: None ''' pass def uninstall(self): ''' Uninstall airtest touch Returns: None ''' pass def install_and_setup(self): ''' Install airtest touch Returns: None ''' pass def setup_server(self): ''' Setip touch server and adb forward Returns: server process ''' pass @retry_when_connection_error def safe_send(self, data): ''' Send data to client Args: data: data to send Raises: Exception: when data cannot be sent Returns: None ''' pass def _backend_worker(self): ''' Backend worker queue thread Returns: None ''' pass def setup_client_backend(self): ''' Setup backend client thread as daemon Returns: None ''' pass def setup_client_backend(self): ''' Setup client Returns: None ''' pass def teardown(self): ''' Stop the server and client Returns: None ''' pass def transform_xy(self, x, y): ''' Transform coordinates (x, y) according to the device display Args: x: coordinate x y: coordinate y Returns: transformed coordinates (x, y) ''' pass @on_method_ready('install_and_setup') def perform(self, motion_events, interval=0.01): ''' Perform a sequence of motion events including: UpEvent, DownEvent, MoveEvent, SleepEvent Args: motion_events: a list of MotionEvent instances interval: minimum interval between events Returns: None ''' pass @on_method_ready('install_and_setup') def touch(self, tuple_xy, duration=0.01): ''' Perform touch event minitouch protocol example:: d 0 10 10 50 c <wait in your own code> u 0 c Args: tuple_xy: coordinates (x, y) duration: time interval for touch event, default is 0.01 Returns: None ''' pass def __swipe_move(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5): ''' Return a sequence of swipe motion events (only MoveEvent) minitouch protocol example:: d 0 0 0 50 c m 0 20 0 50 c m 0 40 0 50 c m 0 60 0 50 c m 0 80 0 50 c m 0 100 0 50 c u 0 c Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: [MoveEvent(from_x, from_y), ..., MoveEvent(to_x, to_y)] ''' pass @on_method_ready('install_and_setup') def swipe_along(self, coordinates_list, duration=0.8, steps=5): ''' Perform swipe event across multiple points in sequence. Args: coordinates_list: list of coordinates: [(x1, y1), (x2, y2), (x3, y3)] duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: None ''' pass @on_method_ready('install_and_setup') def swipe_along(self, coordinates_list, duration=0.8, steps=5): ''' Perform swipe event. Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 Returns: None ''' pass @on_method_ready('install_and_setup') def two_finger_swipe(self, tuple_from_xy, tuple_to_xy, duration=0.8, steps=5, offset=(0, 50)): ''' Perform two finger swipe action minitouch protocol example:: d 0 0 0 50 d 1 1 0 50 c m 0 20 0 50 m 1 21 0 50 c m 0 40 0 50 m 1 41 0 50 c m 0 60 0 50 m 1 61 0 50 c m 0 80 0 50 m 1 81 0 50 c m 0 100 0 50 m 1 101 0 50 c u 0 u 1 c Args: tuple_from_xy: start point tuple_to_xy: end point duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 offset: coordinate offset of the second finger, default is (0, 50) Returns: None ''' pass @on_method_ready('install_and_setup') def pinch(self, center=None, percent=0.5, duration=0.5, steps=5, in_or_out='in'): ''' Perform pinch action minitouch protocol example:: d 0 0 100 50 d 1 100 0 50 c m 0 10 90 50 m 1 90 10 50 c m 0 20 80 50 m 1 80 20 50 c m 0 20 80 50 m 1 80 20 50 c m 0 30 70 50 m 1 70 30 50 c m 0 40 60 50 m 1 60 40 50 c m 0 50 50 50 m 1 50 50 50 c u 0 u 1 c Args: center: the center point of the pinch operation percent: pinch distance to half of screen, default is 0.5 duration: time interval for swipe duration, default is 0.8 steps: size of swipe step, default is 5 in_or_out: pinch in or pinch out, default is 'in' Returns: None Raises: TypeError: An error occurred when center is not a list/tuple or None ''' pass @on_method_ready('install_and_setup') def operate(self, args): ''' Perform down, up and move actions Args: args: action arguments, dictionary containing type and x, y coordinates, e.g.:: { "type" : "down", "x" : 10, "y" : 10 } Raises: RuntimeError: is invalid arguments are provided Returns: None ''' pass
29
19
23
3
9
11
2
1.22
1
12
4
2
19
12
19
19
473
80
177
76
148
216
134
67
114
5
1
2
38
3,452
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/android/yosemite.py
airtest.core.android.yosemite.Yosemite
class Yosemite(object): """Wrapper class of Yosemite.apk, used by javacap/recorder/yosemite_ime.""" def __init__(self, adb): self.adb = adb def install_or_upgrade(self): """ Install or update the Yosemite.apk file on the device Returns: None """ self._install_apk_upgrade(YOSEMITE_APK, YOSEMITE_PACKAGE) def _install_apk_upgrade(self, apk_path, package): """ Install or update the `.apk` file on the device Args: apk_path: full path `.apk` file package: package name Returns: None """ apk_version = int(APK(apk_path).androidversion_code) installed_version = self.adb.get_package_version(package) if installed_version is None or apk_version > int(installed_version): LOGGING.info( "local version code is {}, installed version code is {}".format(apk_version, installed_version)) try: self.adb.pm_install(apk_path, replace=True, install_options=["-t"]) except: if installed_version is None: raise # If the installation fails, but the phone has an old version, do not force the installation print(traceback.format_exc()) warnings.warn( "Yosemite.apk update failed, please try to reinstall manually(airtest/core/android/static/apks/Yosemite.apk).") @on_method_ready('install_or_upgrade') def get_ready(self): pass def uninstall(self): """ Uninstall `Yosemite.apk` application from the device Returns: None """ self.adb.uninstall_app(YOSEMITE_PACKAGE)
class Yosemite(object): '''Wrapper class of Yosemite.apk, used by javacap/recorder/yosemite_ime.''' def __init__(self, adb): pass def install_or_upgrade(self): ''' Install or update the Yosemite.apk file on the device Returns: None ''' pass def _install_apk_upgrade(self, apk_path, package): ''' Install or update the `.apk` file on the device Args: apk_path: full path `.apk` file package: package name Returns: None ''' pass @on_method_ready('install_or_upgrade') def get_ready(self): pass def uninstall(self): ''' Uninstall `Yosemite.apk` application from the device Returns: None ''' pass
7
4
9
1
4
4
2
0.87
1
1
0
3
5
1
5
5
55
12
23
10
16
20
21
9
15
4
1
3
8
3,453
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_minitouch.py
tests.test_minitouch.TestMiniTouch
class TestMiniTouch(TestMiniTouchBase): def test_touch(self): self.minitouch.touch((100, 100)) def test_swipe(self): self.minitouch.swipe((100, 100), (200, 200)) def test_swipe_along(self): self.minitouch.swipe_along([(100, 100), (200, 200), (300, 300)]) def test_two_finger_swipe(self): self.minitouch.two_finger_swipe((100, 100), (200, 200)) def test_pinch(self): self.minitouch.pinch() self.minitouch.pinch(in_or_out='out')
class TestMiniTouch(TestMiniTouchBase): def test_touch(self): pass def test_swipe(self): pass def test_swipe_along(self): pass def test_two_finger_swipe(self): pass def test_pinch(self): pass
6
0
2
0
2
0
1
0
1
0
0
1
5
0
5
80
17
5
12
6
6
0
12
6
6
1
3
0
5
3,454
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_minicap.py
tests.test_minicap.TestMinicapSetup
class TestMinicapSetup(TestMinicapBase): def test_0_install(self): self.minicap.uninstall() self.minicap.install() def test_teardown(self): self.minicap.get_frame_from_stream() self.minicap.teardown_stream() self.assertEqual(self._count_server_proc(), 0)
class TestMinicapSetup(TestMinicapBase): def test_0_install(self): pass def test_teardown(self): pass
3
0
4
0
4
0
1
0
1
0
0
0
2
0
2
77
10
2
8
3
5
0
8
3
5
1
3
0
2
3,455
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_minicap.py
tests.test_minicap.TestMinicapBase
class TestMinicapBase(unittest.TestCase): @classmethod def setUpClass(cls): cls.dev = Android() cls.dev.rotation_watcher.get_ready() cls.minicap = Minicap(cls.dev.adb, rotation_watcher=cls.dev.rotation_watcher) def _count_server_proc(self): output = self.dev.adb.raw_shell("ps").strip() cnt = 0 for line in output.splitlines(): if "minicap" in line and "do_exit" not in line and "R" in line: cnt += 1 return cnt @classmethod def tearDownClass(cls): cls.dev.rotation_watcher.teardown() cls.minicap.teardown_stream()
class TestMinicapBase(unittest.TestCase): @classmethod def setUpClass(cls): pass def _count_server_proc(self): pass @classmethod def tearDownClass(cls): pass
6
0
5
0
5
0
2
0
1
2
2
2
1
0
3
75
20
3
17
9
11
0
15
7
11
3
2
2
5
3,456
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/helper.py
airtest.core.helper.G
class G(object, metaclass=DeviceMetaProperty): """Represent the globals variables""" BASEDIR = [] LOGGER = AirtestLogger(None) LOGGING = get_logger("airtest.core.api") SCREEN = None _DEVICE = None DEVICE_LIST = [] RECENT_CAPTURE = None RECENT_CAPTURE_PATH = None CUSTOM_DEVICES = {} @classmethod def add_device(cls, dev): """ Add device instance in G and set as current device. Examples: G.add_device(Android()) Args: dev: device to init Returns: None """ for index, instance in enumerate(cls.DEVICE_LIST): if dev.uuid == instance.uuid: cls.LOGGING.warn("Device:%s updated %s -> %s" % (dev.uuid, instance, dev)) cls.DEVICE_LIST[index] = dev cls.DEVICE = dev break else: cls.DEVICE = dev cls.DEVICE_LIST.append(dev) @classmethod def register_custom_device(cls, device_cls): cls.CUSTOM_DEVICES[device_cls.__name__.lower()] = device_cls
class G(object, metaclass=DeviceMetaProperty): '''Represent the globals variables''' @classmethod def add_device(cls, dev): ''' Add device instance in G and set as current device. Examples: G.add_device(Android()) Args: dev: device to init Returns: None ''' pass @classmethod def register_custom_device(cls, device_cls): pass
5
2
13
2
6
5
2
0.42
2
1
0
0
0
0
2
17
40
6
24
15
19
10
22
13
19
3
3
2
4
3,457
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_minicap.py
tests.test_minicap.TestMinicap
class TestMinicap(TestMinicapBase): def test_get_frame(self): frame = self.minicap.get_frame() frame = string_2_img(frame) self.assertIsInstance(frame, ndarray) def test_get_frames(self): frame = self.minicap.get_frame_from_stream() frame = string_2_img(frame) self.assertIsInstance(frame, ndarray) def test_rotation(self): self.dev.keyevent("HOME") time.sleep(1) frame_vertical = self.minicap.get_frame_from_stream() frame_vertical = string_2_img(frame_vertical) self.dev.start_app(PKG) time.sleep(3) frame_horizontal = self.minicap.get_frame_from_stream() frame_horizontal = string_2_img(frame_horizontal) self.assertEqual(frame_vertical.shape[0], frame_horizontal.shape[1]) self.assertEqual(frame_vertical.shape[1], frame_horizontal.shape[0]) def test_projection(self): """ 先按home键回到桌面,确保当前是竖屏 然后设置高度为800,大部分手机竖屏高度都大于这个数值,计算出对应的projection参数 最后验证截出来的图是否高度等于800 Returns: """ self.dev.keyevent("HOME") default_height = 800 height = self.dev.display_info.get("height") width = self.dev.display_info.get("width") scale_factor = min(default_height, height) / height projection = (scale_factor * width, scale_factor * height) screen = string_2_img(self.minicap.get_frame(projection=projection)) self.assertEqual(screen.shape[0], default_height) self.minicap.projection = projection screen_stream = self.minicap.get_frame_from_stream() screen2 = string_2_img(screen_stream) self.assertEqual(screen2.shape[0], default_height)
class TestMinicap(TestMinicapBase): def test_get_frame(self): pass def test_get_frames(self): pass def test_rotation(self): pass def test_projection(self): ''' 先按home键回到桌面,确保当前是竖屏 然后设置高度为800,大部分手机竖屏高度都大于这个数值,计算出对应的projection参数 最后验证截出来的图是否高度等于800 Returns: ''' pass
5
1
10
1
8
2
1
0.18
1
0
0
0
4
0
4
79
46
7
33
17
28
6
33
17
28
1
3
0
4
3,458
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_maxtouch.py
tests.test_maxtouch.TestMaxTouchSetup
class TestMaxTouchSetup(TestMaxTouchBase): def test_0_install(self): self.maxtouch.uninstall() self.maxtouch.install() def test_teardown(self): self.maxtouch.touch((0, 0)) cnt = self._count_server_proc() self.maxtouch.teardown() self.assertEqual(self._count_server_proc(), cnt - 1)
class TestMaxTouchSetup(TestMaxTouchBase): def test_0_install(self): pass def test_teardown(self): pass
3
0
4
0
4
0
1
0
1
0
0
0
2
0
2
77
11
2
9
4
6
0
9
4
6
1
3
0
2
3,459
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_maxtouch.py
tests.test_maxtouch.TestMaxTouchBase
class TestMaxTouchBase(unittest.TestCase): @classmethod def setUpClass(cls): cls.adb = ADB() devices = cls.adb.devices() if not devices: raise RuntimeError("At lease one adb device required") cls.adb.serialno = devices[0][0] cls.maxtouch = Maxtouch(cls.adb) @classmethod def tearDownClass(cls): cls.maxtouch.teardown() def _count_server_proc(self): output = self.adb.raw_shell("ps").strip() cnt = 0 for line in output.splitlines(): if "app_process" in line and line.split(" ")[-2] not in ["Z", "T", "X"]: # 进程状态是睡眠或运行 cnt += 1 return cnt
class TestMaxTouchBase(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def _count_server_proc(self): pass
6
0
6
0
5
0
2
0.05
1
3
2
2
1
0
3
75
23
3
19
10
13
1
17
8
13
3
2
2
6
3,460
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_adb.py
tests.test_adb.TestADBWithDevice
class TestADBWithDevice(unittest.TestCase): @classmethod def setUpClass(cls): devices = ADB().devices(state="device") if not devices: raise RuntimeError("At lease one adb device required") cls.adb = ADB(devices[0][0]) def test_devices(self): online_devices = self.adb.devices(state=self.adb.status_device) self.assertEqual(online_devices[0][0], self.adb.serialno) self.assertEqual(online_devices[0][1], self.adb.status_device) def test_get_status(self): self.assertEqual(self.adb.get_status(), self.adb.status_device) def test_cmd(self): output = self.adb.cmd("shell whoami") self.assertIsInstance(output, text_type) with self.assertRaises(RuntimeError): self.adb.cmd("shell top", timeout=2) def test_wait_for_device(self): self.adb.wait_for_device() with self.assertRaises(DeviceConnectionError): ADB("some_impossible_serialno").wait_for_device(timeout=2) def test_start_shell(self): proc = self.adb.start_shell("time") self.assertIsInstance(proc, subprocess.Popen) out, err = proc.communicate() self.assertIsInstance(out, str) self.assertIsInstance(err, str) def test_raw_shell(self): output = self.adb.raw_shell("pwd") self.assertEqual(output.strip(), "/") self.assertIsInstance(output, text_type) self.assertIsInstance(self.adb.raw_shell("pwd", ensure_unicode=False), str) def test_shell(self): output = self.adb.shell("time") self.assertIsInstance(output, text_type) with self.assertRaises(AdbShellError): self.adb.shell("ls some_imposible_path") def test_getprop(self): output = self.adb.getprop("wifi.interface") self.assertIsInstance(output, text_type) def test_sdk_version(self): output = self.adb.sdk_version self.assertIsInstance(output, int) def test_exists_file(self): self.assertTrue(self.adb.exists_file("/")) def test_file_size(self): self.assertIsInstance(self.adb.file_size("/data/local/tmp/minicap"), int) def test_push(self): def test_push_file(file_path, des_path): des_file = self.adb.push(file_path, des_path) print(des_file) self.assertIsNotNone(des_file) self.assertTrue(self.adb.exists_file(des_file)) self.adb.shell("rm -r \"" + des_file + "\"") tmpdir = "/data/local/tmp" test_push_file(IMG, tmpdir) imgname = os.path.basename(IMG) tmpimgpath = tmpdir + "/" + imgname test_push_file(IMG, tmpimgpath) test_push_file(IMG, tmpdir) # 测试空格+特殊字符+中文 test_space_img = os.path.join(os.path.dirname(IMG), "space " + imgname) shutil.copy(IMG, test_space_img) test_push_file(test_space_img, tmpdir) test_push_file(test_space_img, tmpdir + "/" + os.path.basename(test_space_img)) try_remove(test_space_img) test_img = os.path.join(os.path.dirname(IMG), imgname + "中文 (1)") shutil.copy(IMG, test_img) test_push_file(test_img, tmpdir) test_push_file(test_img, tmpdir + "/" + os.path.basename(test_img)) try_remove(test_img) # 测试非临时目录(部分高版本手机有权限问题,不允许直接push) dst_path = "/sdcard/Android/data/com.netease.nie.yosemite/files" test_push_file(IMG, dst_path) test_img = os.path.join(os.path.dirname(IMG), imgname + "中文 (1)") shutil.copy(IMG, test_img) test_push_file(test_img, dst_path) # 推送文件夹 /test push 到 目标路径 os.makedirs("test push", exist_ok=True) shutil.copy(IMG, "test push/" + imgname) test_push_file("test push", dst_path) test_push_file("test push", tmpdir) shutil.rmtree("test push") # 推送文件夹 /test push 到 目标路径/test push os.makedirs("test push", exist_ok=True) shutil.copy(IMG, "test push/" + imgname) test_push_file("test push", dst_path + "/test") shutil.rmtree("test push") def test_pull(self): tmpdir = "/data/local/tmp" imgname = os.path.basename(IMG) tmpimgpath = tmpdir + "/" + imgname dest_file = self.adb.push(IMG, tmpdir) try_remove(imgname) self.adb.pull(tmpimgpath, ".") self.assertTrue(os.path.exists(imgname)) try_remove(imgname) # 测试空格+特殊字符+中文 test_file_path = "test pull/g18/test中文 (1).png" os.makedirs(os.path.dirname(test_file_path)) self.adb.pull(tmpimgpath, test_file_path) self.assertTrue(os.path.exists(test_file_path)) try_remove("test pull") self.adb.shell("rm " + dest_file) def test_get_forwards(self): self.adb.remove_forward() self.adb.forward(local='tcp:6100', remote="tcp:7100") forwards = self.adb.get_forwards() self.assertIsInstance(forwards, GeneratorType) forwards = list(forwards) self.assertEqual(len(forwards), 1) sn, local, remote = forwards[0] self.assertEqual(sn, self.adb.serialno) self.assertEqual(local, 'tcp:6100') self.assertEqual(remote, 'tcp:7100') def test_remove_forward(self): self.adb.remove_forward() self.assertEqual(len(list(self.adb.get_forwards())), 0) # set a remote and remove it self.adb.forward(local='tcp:6100', remote="tcp:7100") self.adb.remove_forward(local='tcp:6100') self.assertEqual(len(list(self.adb.get_forwards())), 0) def test_cleanup_forwards(self): """ Test that all forward ports have been removed 测试所有forward的端口号都被remove了 """ for port in ['tcp:10010', 'tcp:10020', 'tcp:10030']: self.adb.forward(port, port) self.adb._cleanup_forwards() self.assertEqual(len(list(self.adb.get_forwards())), 0) def test_logcat(self): line_cnt = 0 for line in self.adb.logcat(): self.assertIsInstance(line, str) line_cnt += 1 if line_cnt > 3: break self.assertGreater(line_cnt, 0) def test_pm_install(self): if PKG in self.adb.list_app(): self.adb.pm_uninstall(PKG) self.adb.pm_install(APK, install_options=["-r", "-g"]) self.assertIn(PKG, self.adb.list_app()) # 安装完毕后,验证apk文件是否已删除 tmpdir = "/data/local/tmp" tmp_files = self.adb.shell("ls " + tmpdir) self.assertNotIn(os.path.basename(APK), tmp_files, "The apk file in /data/local/tmp is not deleted!") self.adb.pm_uninstall(PKG) self.assertNotIn(PKG, self.adb.list_app()) # 测试中文名+特殊字符的apk安装 test_apk_name = "中文 (1).apk" shutil.copy(APK, test_apk_name) self.adb.pm_install(test_apk_name, install_options=["-r", "-g"]) self.assertIn(PKG, self.adb.list_app()) # 安装完毕后,验证apk文件是否已删除 tmpdir = "/data/local/tmp" tmp_files = self.adb.shell("ls " + tmpdir) self.assertNotIn(os.path.basename(APK), tmp_files, "The apk file in /data/local/tmp is not deleted!") self.adb.pm_uninstall(PKG) self.assertNotIn(PKG, self.adb.list_app()) try_remove(test_apk_name) def test_ip(self): ip = self.adb.get_ip_address() if ip: self.assertEqual(len(ip.split('.')), 4) def test_gateway(self): gateway = self.adb.get_gateway_address() if gateway: self.assertEqual(len(gateway.split('.')), 4) def test_text(self): self.adb.text("Hello World") self.adb.text("test123")
class TestADBWithDevice(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_devices(self): pass def test_get_status(self): pass def test_cmd(self): pass def test_wait_for_device(self): pass def test_start_shell(self): pass def test_raw_shell(self): pass def test_shell(self): pass def test_getprop(self): pass def test_sdk_version(self): pass def test_exists_file(self): pass def test_file_size(self): pass def test_push(self): pass def test_push_file(file_path, des_path): pass def test_pull(self): pass def test_get_forwards(self): pass def test_remove_forward(self): pass def test_cleanup_forwards(self): ''' Test that all forward ports have been removed 测试所有forward的端口号都被remove了 ''' pass def test_logcat(self): pass def test_pm_install(self): pass def test_ip(self): pass def test_gateway(self): pass def test_text(self): pass
25
1
9
1
7
1
1
0.08
1
8
3
0
21
0
22
94
220
46
161
56
136
13
160
55
136
3
2
2
30
3,461
AirtestProject/Airtest
AirtestProject_Airtest/tests/test_maxtouch.py
tests.test_maxtouch.TestMaxTouchBackend
class TestMaxTouchBackend(TestMaxTouch): @classmethod def setUpClass(cls): cls.adb = ADB() devices = cls.adb.devices() if not devices: raise RuntimeError("At lease one adb device required") cls.adb.serialno = devices[0][0] cls.maxtouch = Maxtouch(cls.adb, backend=True)
class TestMaxTouchBackend(TestMaxTouch): @classmethod def setUpClass(cls): pass
3
0
7
0
7
0
2
0
1
3
2
0
0
0
1
81
10
1
9
4
6
0
8
3
6
2
4
1
2
3,462
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/tests/test_screen_proxy.py
tests.test_screen_proxy.TestScreenProxy.test_custom_cap_method.TestCap
class TestCap(BaseCap): def get_frame_from_stream(self): return b"frame"
class TestCap(BaseCap): def get_frame_from_stream(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
3,463
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/tests/test_ios.py
tests.test_ios.TestIos
class TestIos(unittest.TestCase): @classmethod def setUpClass(cls): cls.ios = IOS(addr=DEFAULT_ADDR, cap_method=CAP_METHOD.WDACAP) cls.TEST_FSYNC_APP = "" # 测试文件推送、同步的app的bundleID # 获取一个可以用于文件操作的app cls.TEST_FSYNC_APP = "com.apple.Keynote" # cls.TEST_FSYNC_APP = "rn.notes.best" @classmethod def tearDownClass(cls): try_remove('screen.png') try_remove('test_10s.mp4') try_remove('test_cv_10s.mp4') def test_wda(self): print("test_wda") self.assertIsInstance(self.ios.driver, wda.Client) print(self.ios.driver.session()) def test_display_info(self): print("test_display_info") device_infos = self.ios.display_info self.assertIsInstance(device_infos["width"], int) self.assertIsInstance(device_infos["height"], int) self.assertIsInstance(device_infos["orientation"], str) print(device_infos) def test_window_size(self): print("test window size") window_size = self.ios.window_size() print(window_size) self.assertIsInstance(window_size.height, int) self.assertIsInstance(window_size.width, int) # 以下用例可能会因为wda更新而失败,到时候需要去掉 ios._display_info里的ipad横屏下的额外处理 # 当ipad 在横屏+桌面的情况下,获取到的window_size的值为 height*height,没有width的值 if self.ios.is_pad and self.client.orientation != 'PORTRAIT' and self.ios.home_interface(): self.assertEqual(window_size.width, window_size.height) def test_using_ios_tagent(self): status = self.ios.driver.status() print(self.ios.using_ios_tagent) self.assertEqual('Version' in status, self.ios.using_ios_tagent) def test_snapshot(self): print("test_snapshot") filename = "./screen.png" if os.path.exists(filename): os.remove(filename) screen = self.ios.snapshot(filename=filename) self.assertIsInstance(screen, numpy.ndarray) self.assertTrue(os.path.exists(filename)) def test_get_frames(self): frame = self.ios.get_frame_from_stream() frame = aircv.utils.string_2_img(frame) self.assertIsInstance(frame, numpy.ndarray) def test_keyevent_home(self): print("test_keyevent_home") self.ios.keyevent("home") with self.assertRaises(ValueError): self.ios.keyevent("home1") def test_keyevent_volume_up(self): print("test_keyevent_volume_up") self.ios.keyevent("voluMeup") def test_keyevent_volume_down(self): print("test_keyevent_volume_down") self.ios.keyevent("voluMeDown") def test_press(self): with self.assertRaises(ValueError): self.ios.press("home1") self.ios.press("home") self.ios.press("volumeUp") self.ios.press("volumeDown") def test_home(self): print("test_home") self.ios.home() self.assertTrue(self.ios.home_interface()) def test_text(self): self.ios.start_app("com.apple.mobilenotes") self.ios.touch((0.5, 0.5)) self.ios.text('test text') self.ios.text('中文') self.ios.stop_app("com.apple.mobilenotes") def test_touch(self): # 位置参数可为:相对于设备的百分比坐标或者实际的逻辑位置坐标 print("test_touch") self.ios.touch((480, 350), duration=0.1) time.sleep(2) self.ios.home() time.sleep(2) self.ios.touch((0.3, 0.3)) def test_swipe(self): print("test_swipe") # 右往左滑 self.ios.swipe((1050, 1900), (150, 1900)) time.sleep(2) # 左往右滑 self.ios.swipe((0.2, 0.5), (0.8, 0.5)) # 上往下滑,按住0.5秒后往下滑动 self.ios.swipe((0.5, 0.1), (0.5, 0.5), duration=0.5) def test_lock(self): print("test_lock") self.ios.lock() def test_is_locked(self): print("test_is_locked") self.ios.unlock() self.assertTrue(not self.ios.is_locked()) def test_unlock(self): print("test_unlock") self.ios.unlock() def test_get_render_resolution(self): print("test_get_render_resolution") self.ios.get_render_resolution() def test_double_click(self): print("test_double_click") self.ios.double_click((0.5, 0.5)) time.sleep(1) self.ios.double_click((100, 100)) def test_startapp(self): print("test_startapp") self.ios.start_app(PKG_SAFARI) def test_general_api(self): print("test_general_api") start_app(PKG_SAFARI) stop_app(PKG_SAFARI) start_app("com.apple.mobilenotes") set_clipboard("Legends never die.") cliboard_text = get_clipboard() self.assertEqual(cliboard_text, "Legends never die.") def test_stopapp(self): print("test_stopapp") self.ios.stop_app(PKG_SAFARI) stop_app(PKG_SAFARI) def test_app_state(self): print("test_app_state") self.ios.start_app(PKG_SAFARI) print(self.ios.app_state(PKG_SAFARI)) self.assertEqual(self.ios.app_state(PKG_SAFARI)["value"], 4) time.sleep(1) self.ios.home() time.sleep(1) print(self.ios.app_state(PKG_SAFARI)) self.assertEqual(self.ios.app_state(PKG_SAFARI)["value"], 3) self.ios.stop_app(PKG_SAFARI) time.sleep(1) print(self.ios.app_state(PKG_SAFARI)) self.assertEqual(self.ios.app_state(PKG_SAFARI)["value"], 1) def test_app_current(self): print("test_app_current") self.ios.start_app(PKG_SAFARI) time.sleep(2) self.assertEqual(self.ios.app_current()["bundleId"], PKG_SAFARI) self.ios.stop_app(PKG_SAFARI) def test_get_ip_address(self): print("test_get_ip_address") print(self.ios.get_ip_address()) def test_device_status(self): print("test_get_device_status") status = self.ios.device_status() print(status) self.assertIsInstance(status, dict) @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_exists") def test_alert_exists(self): # alert测试方法:手机开飞行模式断网,打开天气app,会弹出提示需要关闭飞行模式 # 重复测试时,需要先关闭app-关闭飞行模式-开启app-关闭app,然后重新开飞行模式 # 未安装手机sim卡时,在取消飞行模式的时候也会弹出一个“未安装SIM卡”的提示 print("test_get_alert_exists") print(self.ios.alert_exists()) @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_accept") def test_alert_accept(self): print("test_get_alert_accept") self.assertTrue(self.ios.alert_exists()) print(self.ios.alert_accept()) @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_dismiss") def test_alert_dismiss(self): print("test_get_alert_dismiss") self.ios.alert_dismiss() @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_buttons") def test_alert_buttons(self): print("test_get_alert_buttons") print(self.ios.alert_buttons()) print(self.ios.driver.alert.text) @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_click") def test_alert_click(self): print("test_get_alert_click") self.ios.alert_click(['设置', '允许', '好']) @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_click") def test_alert_watch_and_click(self): with self.ios.alert_watch_and_click(['Cancel']): time.sleep(5) # default watch buttons are # ["使用App时允许", "好", "稍后", "稍后提醒", "确定", "允许", "以后"] # default check every 2.0s with self.ios.alert_watch_and_click(interval=2.0): time.sleep(5) def test_device_info(self): print("test_device_info") print(self.ios.device_info) def test_home_interface(self): print("test_home_interface") self.ios.home() time.sleep(2) self.assertTrue(self.ios.home_interface()) def test_touch_factor(self): """ 在部分特殊型号的设备上,可能默认的touch_factor不能正确点击对应的位置,因此需要修正 Returns: """ print("test touch factor") print("ios.driver.scale:", self.ios.driver.scale) print("display_info:", self.ios.display_info) print("default touch_factor:", self.ios.touch_factor) self.ios.touch((500, 500)) self.ios.touch_factor = 1 / 3.3 self.ios.touch((500, 500)) def test_disconnect(self): print("test_disconnect") self.ios.cap_method = CAP_METHOD.MJPEG self.ios.get_frame_from_stream() self.ios.disconnect() self.assertEqual( len(self.ios.instruct_helper._port_using_func.keys()), 0) def test_record(self): self.ios.start_recording(output="test_10s.mp4") time.sleep(10 + 4) self.ios.stop_recording() time.sleep(2) self.assertEqual(os.path.exists("test_10s.mp4"), True) duration = 0 cap = cv2.VideoCapture("test_10s.mp4") if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num / rate self.assertEqual(duration >= 10, True) def test_list_app(self): print("test_list_app") app_list = self.ios.list_app(type="all") self.assertIsInstance(app_list, list) print(app_list) def test_install_app(self): print("test_install_app") self.ios.install_app(TEST_IPA_FILE_OR_URL) def test_uninstall_app(self): print("test_uninstall_app") self.ios.uninstall_app(TEST_IPA_BUNDLE_ID) def test_get_clipboard(self): print("test_get_clipboard") print(self.ios.get_clipboard()) def test_set_clipboard(self): for i in range(10): text = "test_set_clipboard" + str(i) self.ios.set_clipboard(text) self.assertEqual(self.ios.get_clipboard(), text) self.ios.paste() text = "test clipboard with中文 $pecial char #@!#%$#^&*()'" self.ios.set_clipboard(text) self.assertEqual(self.ios.get_clipboard(), text) self.ios.paste() def test_ls(self): print("test ls") # ls /DCIM/ dcim = self.ios.ls("/DCIM/") print(dcim) self.assertTrue(isinstance(dcim, list) and len(dcim) > 0) self.assertTrue(isinstance(dcim[0], dict)) # ls app /Documents/ with open("test_ls_file.txt", 'w') as f: f.write('Test data') self.ios.push("test_ls_file.txt", "/Documents/", self.TEST_FSYNC_APP) file_list = self.ios.ls("/Documents/", self.TEST_FSYNC_APP) self.assertTrue(isinstance(file_list, list)) self.assertTrue(len(file_list) > 0) self.assertTrue(isinstance(file_list[0], dict)) self._try_remove_ios( "/Documents/test_ls_file.txt", self.TEST_FSYNC_APP) try_remove("test_ls_file.txt") def _try_remove_ios(self, file_name, bundle_id=None): try: self.ios.rm(file_name, bundle_id) file_list = self.ios.ls(os.path.dirname(file_name), bundle_id) for file in file_list: if file['name'] == file_name: raise Exception(f"remove file {file_name} failed") print(f"file {file_name} not exist now.") except: print(f"not find {file_name}") pass def test_push(self): def _test_file(file_name, dst="/Documents/", bundle_id=self.TEST_FSYNC_APP, target=None): try_remove(file_name) with open(file_name, 'w') as f: f.write('Test data') # 用来ls和rm的路径,没有将文件改名则默认为file_name if not target: tmp_dst = os.path.normpath(dst) if os.path.basename(tmp_dst) != file_name: tmp_dst = os.path.join(tmp_dst, file_name) target = tmp_dst.replace('\\', '/') # 清理手机里的文件 self._try_remove_ios(target, bundle_id) self.ios.push(file_name, dst, bundle_id, timeout=60) time.sleep(1) file_list = self.ios.ls(target, bundle_id) # 验证结果 self.assertEqual(len(file_list), 1) self.assertEqual(file_list[0]['name'], os.path.basename(target)) self.assertEqual(file_list[0]['type'], 'File') self._try_remove_ios(target, bundle_id) time.sleep(1) # 清理 try_remove(file_name) def _test_dir(dir_name, dst="/Documents/"): print(f"test push directory {dir_name}") # 用来ls和rm的路径 tmp_dst = os.path.normpath(dst) if os.path.basename(tmp_dst) != dir_name: tmp_dst = os.path.join(tmp_dst, dir_name) target = tmp_dst.replace('\\', '/') # 创建文件夹和文件 try_remove(dir_name) self._try_remove_ios(target, self.TEST_FSYNC_APP) os.mkdir(dir_name) with open(f'{dir_name}/test_data', 'w') as f: f.write('Test data') self.ios.push(dir_name, dst, self.TEST_FSYNC_APP, timeout=60) time.sleep(1) dir_list = self.ios.ls( os.path.dirname(target), self.TEST_FSYNC_APP) print(dir_list) self.assertTrue( f"{dir_name}/" in [item['name'] for item in dir_list]) file_list = self.ios.ls(f"{target}/test_data", self.TEST_FSYNC_APP) self.assertTrue("test_data" in [item['name'] for item in file_list]) self._try_remove_ios(target, self.TEST_FSYNC_APP) time.sleep(1) try_remove(dir_name) # 执行得太快会报错,可能和wda的处理速度有关 # 如果报错尝试单独执行那些用例 _test_file("test_data_1.txt", "/Documents/") _test_file("test_data_2.txt", "/Documents/test_data_2.txt") _test_file("test_data_3.txt", "/Documents/test_data_3.txt/") # 重命名文件 _test_file("test_data_4.txt", "/Documents/test_data.txt/", target="/Documents/test_data.txt") _test_file("test_data.txt", "/Documents") _test_file("test_1.png", "/DCIM", None) _test_file("test_2.png", "/DCIM/", None) _test_file("test_3.png", "/DCIM/test_3.png", None) _test_file("test_4.png", "/DCIM/test_4.png/", None) _test_file("test_5.png", "/DCIM/test.png/", None, target="/DCIM/test.png") _test_file("test.png", "/DCIM/", None) _test_file("t e s t d a t a.txt", "/Documents") _test_file("测试文件.txt", "/Documents") _test_file("测 试 文 件.txt", "/Documents") _test_file("(){}[]~'-_@!#$%&+,;=^.txt", "/Documents") _test_file("data", "/Documents") _test_dir('test_dir', "/Documents/") _test_dir('test_dir_1', "/Documents") _test_dir('t e s t d i r', "/Documents") _test_dir("(){}[]~'-_@!#$%&+,;=^", "/Documents") _test_dir('测试文件夹', "/Documents/") _test_dir('测试文件夹_1', "/Documents") _test_dir('测 试 文 件 夹', "/Documents") def test_pull(self): def _get_file_md5(file_path): hasher = hashlib.md5() with open(file_path, 'rb') as f: while chunk := f.read(8192): hasher.update(chunk) return hasher.hexdigest() def _get_folder_md5(folder_path): md5_list = [] for root, _, files in os.walk(folder_path): for file in sorted(files): # Sort to maintain order file_path = os.path.join(root, file) file_md5 = _get_file_md5(file_path) md5_list.append(file_md5) combined_md5 = hashlib.md5("".join(md5_list).encode()).hexdigest() return combined_md5 def _test_file(file_name, bundle_id=self.TEST_FSYNC_APP, folder="/Documents"): target = f"{folder}/{file_name}" # 删除手机和本地存在的文件, try_remove(file_name) self._try_remove_ios(target, bundle_id=bundle_id) # 创建文件,推送文件 with open(file_name, 'w') as f: f.write('Test data') md5 = _get_file_md5(file_name) self.ios.push(file_name, f"{folder}/", bundle_id=bundle_id, timeout=60) try_remove(file_name) # 下载文件 print(f"test pull file {file_name}") self.ios.pull(target, ".", bundle_id=bundle_id, timeout=60) self.assertTrue(os.path.exists(file_name)) self.assertEqual(md5, _get_file_md5(file_name)) # 下载、重命名文件 self.ios.pull(target, "rename_file.txt", bundle_id=bundle_id, timeout=60) self.assertTrue(os.path.exists("rename_file.txt")) self.assertEqual(md5, _get_file_md5("rename_file.txt")) # 带文件夹路径 os.mkdir("test_dir") self.ios.pull(target, "test_dir", bundle_id=bundle_id, timeout=60) self.assertTrue(os.path.exists(f"test_dir/{file_name}")) self.assertEqual(md5, _get_file_md5(f"test_dir/{file_name}")) # 清理 self._try_remove_ios(target, bundle_id) try_remove(file_name) try_remove("rename_file.txt") try_remove("test_dir") def _test_dir(dir_name, bundle_id=self.TEST_FSYNC_APP, folder="/Documents"): target = f"{folder}/{dir_name}" # 删除手机和本地存在的文件夹,创建文件夹和文件 try_remove(dir_name) self._try_remove_ios(target, bundle_id=bundle_id) os.mkdir(dir_name) with open(f'{dir_name}/test_data', 'w') as f: f.write('Test data') md5 = _get_folder_md5(dir_name) self.ios.push(dir_name, f"{folder}/", bundle_id=bundle_id, timeout=60) time.sleep(1) try_remove(dir_name) # 推送文件夹 print(f"test pull directory {dir_name}") os.mkdir(dir_name) self.ios.pull(target, dir_name, bundle_id=bundle_id, timeout=60) self.assertTrue(os.path.exists(f"{dir_name}/{dir_name}")) self.assertEqual(md5, _get_folder_md5(f"{dir_name}/{dir_name}")) # 清理 self._try_remove_ios(target, bundle_id=bundle_id) time.sleep(1) try_remove(dir_name) # 执行得太快会报错,可能和wda的处理速度有关 # 如果报错尝试单独执行那些用例 _test_file("test_data.txt") _test_file("t e s t _ d a t a.txt") _test_file("测试文件.txt") _test_file("测 试 文 件.txt") _test_file("(){}[]~'-_@!#$%&+,;=^.txt") _test_file("data") _test_file("data.png", bundle_id=None, folder="/DCIM") _test_dir('test_dir') _test_dir('t e s t _ d i r') _test_dir('测试文件夹') _test_dir('测试文件夹.txt') _test_dir('测 试 文 件 夹') _test_dir("(){}[]~'-_@!#$%&+,;=^") _test_dir('test_dir_no_bundle', bundle_id=None, folder="/DCIM") def test_rm(self): def _test_file(file_name, bundle_id=self.TEST_FSYNC_APP, folder="/Documents"): target = f"{folder}/{file_name}" # 删除手机和本地存在的文件,创建文件 self._try_remove_ios(target, bundle_id) with open(file_name, 'w') as f: f.write('Test data') # 推送文件 self.ios.push(file_name, f"{folder}/", bundle_id, timeout=60) time.sleep(1) try_remove(file_name) file_list = self.ios.ls(target, bundle_id) self.assertEqual(len(file_list), 1) # 删除文件 print(f"test rm file {file_name}") self.ios.rm(target, bundle_id) file_list = self.ios.ls(folder, bundle_id) for item in file_list: if item['name'] == file_name: raise Exception(f"remove {file_name} failed") def _test_dir(dir_name, bundle_id=self.TEST_FSYNC_APP, folder="/Documents"): target = f"{folder}/{dir_name}" # 删除手机和本地存在的文件夹,创建文件夹和文件 self._try_remove_ios(target, bundle_id) os.mkdir(dir_name) with open(f'{dir_name}/test_data', 'w') as f: f.write('Test data') # 推送文件夹 self.ios.push(dir_name, f"{folder}/", bundle_id, timeout=60) time.sleep(1) try_remove(dir_name) print(f"test rm directory {dir_name}") file_list = self.ios.ls(folder, bundle_id) for item in file_list: if item['name'] == f"{dir_name}/": break else: raise Exception(f"directory {dir_name} not exist") # 删除文件夹 self.ios.rm(target, bundle_id) file_list = self.ios.ls(folder, bundle_id) self.assertTrue( f"{dir_name}/" not in [item['name'] for item in file_list]) # 执行得太快会报错,可能和wda的处理速度有关 # 如果报错尝试单独执行那些用例 _test_file("test_data.txt") _test_file("t e s t _ d a t a.txt") _test_file("测试文件.txt") _test_file("测 试 文 件.txt") _test_file("(){}[]~'-_@!#$%&+,;=^.txt") _test_file("data") _test_file("data.png", bundle_id=None, folder="/DCIM") _test_dir('test_dir') _test_dir('t e s t _ d i r') _test_dir('测试文件夹') _test_dir('测试文件夹.txt') _test_dir('测 试 文 件 夹') _test_dir("(){}[]~'-_@!#$%&+,;=^") _test_dir('test_dir_no_bundle', bundle_id=None, folder="/DCIM") def test_mkdir(self): def _test(dir_name, bundle_id=self.TEST_FSYNC_APP, folder="/Documents"): target = f"{folder}/{dir_name}" # 删除目标目录 self._try_remove_ios(target, bundle_id) print("test mkdir") # 创建目录 self.ios.mkdir(target, bundle_id) # 获取目标文件夹下的目录列表 dirs = self.ios.ls(folder, bundle_id) # 检查新建的目录是否存在 self.assertTrue(any(d['name'] == f"{dir_name}/" for d in dirs)) # 删除目标目录 self._try_remove_ios(target, bundle_id) # 执行得太快会报错,可能和wda的处理速度有关 # 如果报错尝试单独执行那些用例 _test('test_dir') _test('t e s t _ d i r') _test('测试文件夹') _test('测试文件夹.txt') _test('测 试 文 件 夹') _test("(){}[]~'-_@!#$%&+,;=^") _test('test_dir_no_bundle', bundle_id=None, folder="/DCIM") def test_is_dir(self): print("test is_dir") def create_and_push_file(local_name, remote_name, bundle_id): with open(local_name, 'w') as f: f.write('Test data') self.ios.push(local_name, remote_name, bundle_id) try_remove(local_name) def create_and_push_dir(local_name, remote_name, bundle_id): os.makedirs(local_name) self.ios.push(local_name, remote_name, bundle_id) try_remove(local_name) # 测试文件 file_path = "/Documents/test_data.txt" self._try_remove_ios(file_path, self.TEST_FSYNC_APP) create_and_push_file( "test_data.txt", "/Documents/", self.TEST_FSYNC_APP) self.assertFalse(self.ios.is_dir(file_path, self.TEST_FSYNC_APP)) self._try_remove_ios(file_path, self.TEST_FSYNC_APP) # 测试文件夹 dir_path = "/Documents/test_dir" create_and_push_dir("test_dir", "/Documents/", self.TEST_FSYNC_APP) self.assertTrue(self.ios.is_dir(dir_path, self.TEST_FSYNC_APP)) self._try_remove_ios(dir_path, self.TEST_FSYNC_APP) # 测试另外一个文件夹 file_path_dcim = "/DCIM/test.png" self._try_remove_ios(file_path_dcim, None) create_and_push_file("test_data.txt", "/DCIM/test.png", None) self.assertTrue(self.ios.is_dir("/DCIM", None)) self.assertFalse(self.ios.is_dir(file_path_dcim, None)) self._try_remove_ios(file_path_dcim, None)
class TestIos(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_wda(self): pass def test_display_info(self): pass def test_window_size(self): pass def test_using_ios_tagent(self): pass def test_snapshot(self): pass def test_get_frames(self): pass def test_keyevent_home(self): pass def test_keyevent_volume_up(self): pass def test_keyevent_volume_down(self): pass def test_press(self): pass def test_home(self): pass def test_text(self): pass def test_touch(self): pass def test_swipe(self): pass def test_lock(self): pass def test_is_locked(self): pass def test_unlock(self): pass def test_get_render_resolution(self): pass def test_double_click(self): pass def test_startapp(self): pass def test_general_api(self): pass def test_stopapp(self): pass def test_app_state(self): pass def test_app_current(self): pass def test_get_ip_address(self): pass def test_device_status(self): pass @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_exists") def test_alert_exists(self): pass @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_accept") def test_alert_accept(self): pass @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_dismiss") def test_alert_dismiss(self): pass @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_buttons") def test_alert_buttons(self): pass @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_click") def test_alert_click(self): pass @unittest.skipIf(skip_alert_flag, "demonstrating skipping get_alert_click") def test_alert_watch_and_click(self): pass def test_device_info(self): pass def test_home_interface(self): pass def test_touch_factor(self): ''' 在部分特殊型号的设备上,可能默认的touch_factor不能正确点击对应的位置,因此需要修正 Returns: ''' pass def test_disconnect(self): pass def test_record(self): pass def test_list_app(self): pass def test_install_app(self): pass def test_uninstall_app(self): pass def test_get_clipboard(self): pass def test_set_clipboard(self): pass def test_ls(self): pass def _try_remove_ios(self, file_name, bundle_id=None): pass def test_push(self): pass def _test_file(file_name, dst="/Documents/", bundle_id=self.TEST_FSYNC_APP, target=None): pass def _test_dir(dir_name, dst="/Documents/"): pass def test_pull(self): pass def _get_file_md5(file_path): pass def _get_folder_md5(folder_path): pass def _test_file(file_name, dst="/Documents/", bundle_id=self.TEST_FSYNC_APP, target=None): pass def _test_dir(dir_name, dst="/Documents/"): pass def test_rm(self): pass def _test_file(file_name, dst="/Documents/", bundle_id=self.TEST_FSYNC_APP, target=None): pass def _test_dir(dir_name, dst="/Documents/"): pass def test_mkdir(self): pass def _test_file(file_name, dst="/Documents/", bundle_id=self.TEST_FSYNC_APP, target=None): pass def test_is_dir(self): pass def create_and_push_file(local_name, remote_name, bundle_id): pass def create_and_push_dir(local_name, remote_name, bundle_id): pass
71
1
13
1
10
2
1
0.14
1
9
2
0
49
0
51
123
648
102
489
127
418
68
481
109
418
4
2
3
79
3,464
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/tests/test_android.py
tests.test_android.TestAndroid.test_snapshot_thread.ScreenshotThread
class ScreenshotThread(Thread): def __init__(self, dev, assert_true): self.dev = dev self._running = True self.assert_true = assert_true super(ScreenshotThread, self).__init__() self.dev.snapshot("screen_thread.jpg") assert_exists_and_remove("screen_thread.jpg") def terminate(self): self._running = False def run(self): while self._running: filename = "screen_thread.jpg" self.dev.snapshot(filename) assert_exists_and_remove(filename) time.sleep(2)
class ScreenshotThread(Thread): def __init__(self, dev, assert_true): pass def terminate(self): pass def run(self): pass
4
0
5
0
5
0
1
0
1
2
1
0
3
3
3
28
18
2
16
8
12
0
16
8
12
2
1
1
4
3,465
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/ios/rotation.py
airtest.core.ios.rotation.RotationWatcher
class RotationWatcher(object): """ RotationWatcher class """ def __init__(self, iosHandle): self.iosHandle = iosHandle self.ow_callback = [] self.roundProcess = None self._stopEvent = threading.Event() self.last_result = None reg_cleanup(self.teardown) @on_method_ready('start') def get_ready(self): pass def _install_and_setup(self): """ Install and setup the RotationWatcher package Raises: RuntimeError: if any error occurs while installing the package Returns: None """ # fetch orientation result self.last_result = None # reg_cleanup(self.ow_proc.kill) def teardown(self): # if has roataion watcher stop it if self.roundProcess: self._stopEvent.set() self.ow_callback = [] def start(self): """ Start the RotationWatcher daemon thread Returns: None """ self._install_and_setup() def _refresh_by_ow(): try: return self.get_rotation() except Exception: # 重试5次,如果还是失败就返回None,终止线程 for i in range(5): try: self.iosHandle._fetch_new_session() return self.get_rotation() except: time.sleep(2) continue LOGGING.info("orientationWatcher has ended") return None def _run(): while not self._stopEvent.isSet(): time.sleep(1) ori = _refresh_by_ow() if ori is None: break elif self.last_result == ori: continue LOGGING.info('update orientation %s->%s' % (self.last_result, ori)) self.last_result = ori # exec cb functions for cb in self.ow_callback: try: cb(ori) except: LOGGING.error("cb: %s error" % cb) traceback.print_exc() self.roundProcess = threading.Thread( target=_run, name="rotationwatcher") # self._t.daemon = True self.roundProcess.start() def reg_callback(self, ow_callback): """ Args: ow_callback: Returns: """ """方向变化的时候的回调函数,参数一定是ori,如果断掉了,ori传None""" self.ow_callback.append(ow_callback) def get_rotation(self): return self.iosHandle.get_orientation()
class RotationWatcher(object): ''' RotationWatcher class ''' def __init__(self, iosHandle): pass @on_method_ready('start') def get_ready(self): pass def _install_and_setup(self): ''' Install and setup the RotationWatcher package Raises: RuntimeError: if any error occurs while installing the package Returns: None ''' pass def teardown(self): pass def start(self): ''' Start the RotationWatcher daemon thread Returns: None ''' pass def _refresh_by_ow(): pass def _run(): pass def reg_callback(self, ow_callback): ''' Args: ow_callback: Returns: ''' pass def get_rotation(self): pass
11
4
14
1
9
3
2
0.48
1
4
0
0
7
5
7
7
102
19
56
19
45
27
52
18
42
6
1
3
18
3,466
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/ios/mjpeg_cap.py
airtest.core.ios.mjpeg_cap.MJpegcap
class MJpegcap(object): def __init__(self, instruct_helper=None, ip='localhost', port=None, ori_function=None): self.instruct_helper = instruct_helper self.port = int(port or DEFAULT_MJPEG_PORT) self.ip = ip # 如果指定了port,说明已经将wda的9100端口映射到了新端口,无需本地重复映射 self.port_forwarding = True if self.port == DEFAULT_MJPEG_PORT and ip in ( 'localhost', '127.0.0.1') else False self.ori_function = ori_function self.sock = None self.buf = None self._is_running = False @ready_method def setup_stream_server(self): if self.port_forwarding: self.port, _ = self.instruct_helper.setup_proxy(9100) self.init_sock() reg_cleanup(self.teardown_stream) def init_sock(self): try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.ip, self.port)) self.buf = SocketBuffer(self.sock) self.buf.write(b"GET / HTTP/1.0\r\nHost: localhost\r\n\r\n") self.buf.read_until(b'\r\n\r\n') self._is_running = True LOGGING.info("mjpegsock is ready") except ConnectionResetError: # 断开tidevice或是拔线,会导致这个异常,直接退出即可 LOGGING.error("mjpegsock connection error") raise @on_method_ready('setup_stream_server') def get_frame_from_stream(self): if self._is_running is False: self.init_sock() try: while True: line = self.buf.read_until(b'\r\n') if line.startswith(b"Content-Length"): length = int(line.decode('utf-8').split(": ")[1]) break while True: if self.buf.read_until(b'\r\n') == b'': break imdata = self.buf.read_bytes(length) return imdata except IOError: # 如果暂停获取mjpegsock的数据一段时间,可能会导致它断开,这里将self.buf关闭并临时返回黑屏图像 # 等待下一次需要获取屏幕时,再进行重连 LOGGING.debug("mjpegsock is closed") self._is_running = False self.buf.close() return self.get_blank_screen() def get_frame(self): # 获得单张屏幕截图 return self.get_frame_from_stream() def snapshot(self, ensure_orientation=True, *args, **kwargs): """ Take a screenshot and convert it into a cv2 image object 获取一张屏幕截图,并转化成cv2的图像对象 !!! 注意,该方法拿到的截图可能不是队列中最新的,除非一直在消费队列中的图像,否则可能会是过往图像内容,请谨慎使用 Args: ensure_orientation: True or False whether to keep the orientation same as display Returns: numpy.ndarray """ screen = self.get_frame_from_stream() try: screen = aircv.utils.string_2_img(screen) except Exception: # may be black/locked screen or other reason, print exc for debugging traceback.print_exc() return None if ensure_orientation: if self.ori_function: display_info = self.ori_function() orientation = next(key for key, value in ROTATION_MODE.items( ) if value == display_info["orientation"]) screen = aircv.rotate(screen, -orientation, clockwise=False) return screen def get_blank_screen(self): """ 生成一个黑屏图像,在连接失效时代替屏幕画面返回 Returns: """ if self.ori_function: display_info = self.ori_function() width, height = display_info['width'], display_info['height'] if display_info["orientation"] in [90, 270]: width, height = height, width else: width, height = 1080, 1920 img = numpy.zeros((width, height, 3)).astype('uint8') img_string = aircv.utils.img_2_string(img) return img_string def teardown_stream(self): if self.buf: self.buf.close() if self.port_forwarding: self.instruct_helper.remove_proxy(self.port) self.port = None
class MJpegcap(object): def __init__(self, instruct_helper=None, ip='localhost', port=None, ori_function=None): pass @ready_method def setup_stream_server(self): pass def init_sock(self): pass @on_method_ready('setup_stream_server') def get_frame_from_stream(self): pass def get_frame_from_stream(self): pass def snapshot(self, ensure_orientation=True, *args, **kwargs): ''' Take a screenshot and convert it into a cv2 image object 获取一张屏幕截图,并转化成cv2的图像对象 !!! 注意,该方法拿到的截图可能不是队列中最新的,除非一直在消费队列中的图像,否则可能会是过往图像内容,请谨慎使用 Args: ensure_orientation: True or False whether to keep the orientation same as display Returns: numpy.ndarray ''' pass def get_blank_screen(self): ''' 生成一个黑屏图像,在连接失效时代替屏幕画面返回 Returns: ''' pass def teardown_stream(self): pass
11
2
13
1
10
2
3
0.23
1
5
1
0
8
8
8
8
113
15
80
30
69
18
77
28
68
7
1
3
24
3,467
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/ios/instruct_cmd.py
airtest.core.ios.instruct_cmd.InstructHelper
class InstructHelper(object): """ ForwardHelper class or help run other Instruction """ def __init__(self, uuid=None): self.subprocessHandle = [] # uuid不是ios手机序列号,而是wda.info['uuid']字段 self.uuid = uuid # 下面_udid这个是真正的手机序列号,检测到是USB设备,才会记录这个字段 self._udid = None self._device = None # 记录曾经使用过的端口号和关闭端口用的方法,方便后续释放端口, _port_using_func[port] = kill_func self._port_using_func = {} reg_cleanup(self.tear_down) @staticmethod def builtin_iproxy_path(): # Port forwarding for iOS: # 1. Windows/Mac: iproxy.exe/iproxy -u uid port1 port2 # 2. Ubuntu linux: apt-get install libusbmuxd-tools; iproxy port1 port2 # 3. Use python (low efficiency): python relay.py -t 5100:5100 if shutil.which("iproxy"): return shutil.which("iproxy") system = platform.system() iproxy_path = DEFAULT_IPROXY_PATH.get(system) if iproxy_path: if system == "Darwin": make_file_executable(iproxy_path) return iproxy_path warnings.warn( "Please install iproxy for a better experience(Ubuntu Linux): apt-get install libusbmuxd-tools") return None @property def usb_device(self): """ Whether the current iOS uses the local USB interface, if so, return the wda.usbmux.Device object 当前iOS是否使用了本地USB接口,如果是,返回wda.usbmux.Device对象 Returns: wda.usbmux.Device or None """ if not self._device: # wda无法直接获取iOS的udid,因此先检查usb连接的手机udid列表 try: device_list = wda.usbmux.Usbmux().device_list() except ConnectionRefusedError: # windows上必须要先启动iTunes才能获取到iOS设备列表 LOGGING.warning( "If you are using iOS device in windows, please check if iTunes is launched") return None except Exception as e: # 其他异常,例如 socket unix:/var/run/usbmuxd unable to connect print(e) return None for dev in device_list: udid = dev.get('SerialNumber') usb_dev = wda.Client( url=wda.requests_usbmux.DEFAULT_SCHEME + udid) # 对比wda.info获取到的uuid是否一致 try: if usb_dev.info['uuid'] == self.uuid: self._device = wda.usbmux.Device(udid) self._udid = udid except: return None return self._device def tear_down(self): # 退出时的清理操作,目前暂时只有清理端口 using_ports = copy(list(self._port_using_func.keys())) for port in using_ports: try: kill_func = self._port_using_func.pop(port) kill_func() except: continue # this function auto gen local port @retries(3) def setup_proxy(self, device_port): """ Map a port number on an iOS device to a random port number on the machine 映射iOS设备上某个端口号到本机的随机端口号 Args: device_port: The port number to be mapped on the ios device Returns: """ if not self.usb_device: raise LocalDeviceError( "Currently only supports port forwarding for locally connected iOS devices") local_port = random.randint(11111, 20000) self.do_proxy(local_port, device_port) return local_port, device_port def remove_proxy(self, local_port): if local_port in self._port_using_func: kill_func = self._port_using_func.pop(local_port) kill_func() def do_proxy(self, port, device_port): """ Start do proxy of ios device and self device 目前只支持本地USB连接的手机进行端口转发,远程手机暂时不支持 Returns: None """ if not self.usb_device: raise LocalDeviceError( "Currently only supports port forwarding for locally connected iOS devices") proxy_process = self.builtin_iproxy_path() or shutil.which("tidevice") if proxy_process: cmds = [proxy_process, "-u", self._udid, str(port), str(device_port)] else: # Port forwarding using python self.do_proxy_usbmux(port, device_port) return # Port forwarding using iproxy # e.g. cmds=['/usr/local/bin/iproxy', '-u', '00008020-001270842E88002E', '11565', '5001'] proc = subprocess.Popen( cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=SUBPROCESS_FLAG ) # something like port binding fail time.sleep(0.5) if proc.poll() is not None: stdout, stderr = proc.communicate() stdout = stdout.decode(get_std_encoding(sys.stdout)) stderr = stderr.decode(get_std_encoding(sys.stderr)) raise AirtestError((stdout, stderr)) self._port_using_func[port] = partial(kill_proc, proc) def do_proxy_usbmux(self, lport, rport): """ Mapping ports of local USB devices using python multithreading 使用python多线程对本地USB设备的端口进行映射(当前仅使用USB连接一台iOS时才可用) Args: lport: local port rport: remote port Returns: """ server = ThreadedTCPServer(("localhost", lport), TCPRelay) server.rport = rport server.device = self.usb_device server.bufsize = 128 self.server = server self.server_thread = threading.Thread(target=self.server.serve_forever) self.server_thread.daemon = True self.server_thread.start() self._port_using_func[lport] = self.server.shutdown
class InstructHelper(object): ''' ForwardHelper class or help run other Instruction ''' def __init__(self, uuid=None): pass @staticmethod def builtin_iproxy_path(): pass @property def usb_device(self): ''' Whether the current iOS uses the local USB interface, if so, return the wda.usbmux.Device object 当前iOS是否使用了本地USB接口,如果是,返回wda.usbmux.Device对象 Returns: wda.usbmux.Device or None ''' pass def tear_down(self): pass @retries(3) def setup_proxy(self, device_port): ''' Map a port number on an iOS device to a random port number on the machine 映射iOS设备上某个端口号到本机的随机端口号 Args: device_port: The port number to be mapped on the ios device Returns: ''' pass def remove_proxy(self, local_port): pass def do_proxy(self, port, device_port): ''' Start do proxy of ios device and self device 目前只支持本地USB连接的手机进行端口转发,远程手机暂时不支持 Returns: None ''' pass def do_proxy_usbmux(self, lport, rport): ''' Mapping ports of local USB devices using python multithreading 使用python多线程对本地USB设备的端口进行映射(当前仅使用USB连接一台iOS时才可用) Args: lport: local port rport: remote port Returns: ''' pass
12
5
18
1
11
5
3
0.51
1
11
4
0
7
7
8
8
159
19
93
36
81
47
83
32
74
7
1
4
24
3,468
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/airtest/core/android/yosemite_ext.py
airtest.core.android.yosemite_ext.YosemiteExt
class YosemiteExt(Yosemite): def __init__(self, adb): super(YosemiteExt, self).__init__(adb) self._path = "" @property def path(self): if not self._path: self._path = self.adb.path_app(YOSEMITE_PACKAGE) return self._path @on_method_ready('install_or_upgrade') def device_op(self, op_name, op_args=""): """ Perform device operations Args: op_name: operation name op_args: operation args Returns: None """ return self.adb.shell(f"app_process -Djava.class.path={self.path} / com.netease.nie.yosemite.control.Control --DEVICE_OP {op_name} {op_args}") def get_clipboard(self): """ Get clipboard content Returns: clipboard content """ text = self.device_op("clipboard_get") if text: return text.strip() return "" def set_clipboard(self, text): """ Set clipboard content Args: text: text to be set Returns: None """ text = escape_special_char(text) try: ret = self.device_op("clipboard", f'--TEXT {text}') except Exception as e: raise AirtestError("set clipboard failed, %s" % repr(e)) else: if ret and "Exception" in ret: raise AirtestError("set clipboard failed: %s" % ret) def change_lang(self, lang): """ Change language Args: lang: language to be set Returns: None """ lang_list = ['zh', 'en', 'fr', 'de', 'it', 'ja', 'ko', ] self.device_op("changeLanguge", f"--LANGUAGE_OP {lang}")
class YosemiteExt(Yosemite): def __init__(self, adb): pass @property def path(self): pass @on_method_ready('install_or_upgrade') def device_op(self, op_name, op_args=""): ''' Perform device operations Args: op_name: operation name op_args: operation args Returns: None ''' pass def get_clipboard(self): ''' Get clipboard content Returns: clipboard content ''' pass def set_clipboard(self, text): ''' Set clipboard content Args: text: text to be set Returns: None ''' pass def change_lang(self, lang): ''' Change language Args: lang: language to be set Returns: None ''' pass
9
4
11
2
4
5
2
0.93
1
3
1
0
6
1
6
11
74
18
29
14
20
27
27
11
20
3
2
2
10
3,469
AirtestProject/Airtest
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Airtest/playground/ui.py
ui.AutomatorWrapper.__iter__.Iter
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
class Iter(object): def __init__(self): pass def next(self): pass
3
0
4
0
4
0
2
0
1
2
1
0
2
1
2
2
11
1
10
5
7
0
9
5
6
2
1
1
3
3,470
AirtestProject/Airtest
AirtestProject_Airtest/airtest/core/error.py
airtest.core.error.ScriptParamError
class ScriptParamError(AirtestError): """ This is ScriptParamError BaseError When something goes wrong """ pass
class ScriptParamError(AirtestError): ''' This is ScriptParamError BaseError When something goes wrong ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
12
6
0
2
1
1
4
2
1
1
0
5
0
0
3,471
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/pocofw.py
poco.pocofw.Poco.freeze.FrozenPoco
class FrozenPoco(Poco): def __init__(self, **kwargs): hierarchy_dict = this.agent.hierarchy.dump() hierarchy = create_immutable_hierarchy(hierarchy_dict) agent_ = PocoAgent( hierarchy, this.agent.input, this.agent.screen) kwargs['action_interval'] = 0.01 kwargs['pre_action_wait_for_appearance'] = 0 super(FrozenPoco, self).__init__(agent_, **kwargs) self.this = this def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): pass def __getattr__(self, item): return getattr(self.this, item)
class FrozenPoco(Poco): def __init__(self, **kwargs): pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass def __getattr__(self, item): pass
5
0
4
0
4
0
1
0
1
2
1
0
4
1
4
34
18
3
15
9
10
0
15
9
10
1
3
0
4
3,472
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/freezeui/utils.py
poco.freezeui.utils.create_immutable_dumper.ImmutableFrozenUIDumper
class ImmutableFrozenUIDumper(FrozenUIDumper): def dumpHierarchy(self, onlyVisibleNode=True): return hierarchy_dict
class ImmutableFrozenUIDumper(FrozenUIDumper): def dumpHierarchy(self, onlyVisibleNode=True): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
8
3
0
3
2
1
0
3
2
1
1
4
0
1
3,473
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/airtest/input.py
poco.utils.airtest.input.serializable_adapter.wrapped.PocoUIProxySerializable
class PocoUIProxySerializable(ISerializable): def __init__(self, obj): self.obj = obj def to_json(self): return repr(self.obj)
class PocoUIProxySerializable(ISerializable): def __init__(self, obj): pass def to_json(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
1
2
3
6
1
5
4
2
0
5
4
2
1
2
0
2
3,474
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/hrpc/hierarchy.py
poco.utils.hrpc.hierarchy.RemotePocoHierarchy
class RemotePocoHierarchy(HierarchyInterface): def __init__(self, dumper, selector, attributor): super(RemotePocoHierarchy, self).__init__() self.dumper = dumper self.selector = selector self.attributor = attributor # node/hierarchy interface @retries_when(TransportDisconnected, delay=3.0) @transform_node_has_been_removed_exception def getAttr(self, nodes, name): return self.attributor.getAttr(nodes, name) @retries_when(TransportDisconnected, delay=3.0) @transform_node_has_been_removed_exception def setAttr(self, nodes, name, value): return self.attributor.setAttr(nodes, name, value) @retries_when(TransportDisconnected, delay=3.0) def select(self, query, multiple=False): return self.selector.select(query, multiple) @retries_when(TransportDisconnected, delay=3.0) def dump(self): return self.dumper.dumpHierarchy()
class RemotePocoHierarchy(HierarchyInterface): def __init__(self, dumper, selector, attributor): pass @retries_when(TransportDisconnected, delay=3.0) @transform_node_has_been_removed_exception def getAttr(self, nodes, name): pass @retries_when(TransportDisconnected, delay=3.0) @transform_node_has_been_removed_exception def setAttr(self, nodes, name, value): pass @retries_when(TransportDisconnected, delay=3.0) def select(self, query, multiple=False): pass @retries_when(TransportDisconnected, delay=3.0) def dump(self): pass
12
0
3
0
3
0
1
0.05
1
1
0
0
5
3
5
9
25
4
20
13
8
1
14
9
8
1
2
0
5
3,475
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/six.py
poco.utils.simplerpc.jsonrpc.six.X
class X(object): def __len__(self): return 1 << 31
class X(object): def __len__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
3,476
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_backend_django/tests.py
poco.utils.simplerpc.jsonrpc.tests.test_backend_django.tests.TestDjangoBackend
class TestDjangoBackend(TestCase): @classmethod def setUpClass(cls): os.environ['DJANGO_SETTINGS_MODULE'] = \ 'jsonrpc.tests.test_backend_django.settings' def test_urls(self): self.assertTrue(isinstance(api.urls, list)) for api_url in api.urls: self.assertTrue(isinstance(api_url, RegexURLPattern)) def test_client(self): @api.dispatcher.add_method def dummy(request): return "" json_data = { "id": "0", "jsonrpc": "2.0", "method": "dummy", } response = self.client.post( '', json.dumps(json_data), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode('utf8')) self.assertEqual(data['result'], '') def test_method_not_allowed(self): response = self.client.get( '', content_type='application/json', ) self.assertEqual(response.status_code, 405, "Should allow only POST") def test_invalid_request(self): response = self.client.post( '', '{', content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode('utf8')) self.assertEqual(data['error']['code'], -32700) self.assertEqual(data['error']['message'], 'Parse error') def test_resource_map(self): response = self.client.get('/map') self.assertEqual(response.status_code, 200) data = response.content.decode('utf8') self.assertIn("JSON-RPC map", data) def test_method_not_allowed_prefix(self): response = self.client.get( '/prefix', content_type='application/json', ) self.assertEqual(response.status_code, 405) def test_resource_map_prefix(self): response = self.client.get('/prefix/map') self.assertEqual(response.status_code, 200) def test_empty_initial_dispatcher(self): class SubDispatcher(type(api.dispatcher)): pass custom_dispatcher = SubDispatcher() custom_api = JSONRPCAPI(custom_dispatcher) self.assertEqual(type(custom_api.dispatcher), SubDispatcher) self.assertEqual(id(custom_api.dispatcher), id(custom_dispatcher))
class TestDjangoBackend(TestCase): @classmethod def setUpClass(cls): pass def test_urls(self): pass def test_client(self): pass @api.dispatcher.add_method def dummy(request): pass def test_method_not_allowed(self): pass def test_invalid_request(self): pass def test_resource_map(self): pass def test_method_not_allowed_prefix(self): pass def test_resource_map_prefix(self): pass def test_empty_initial_dispatcher(self): pass class SubDispatcher(type(api.dispatcher)):
14
0
7
0
6
0
1
0
1
4
2
0
8
0
9
9
73
10
63
27
49
0
42
25
30
2
1
1
11
3,477
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_backend_flask/tests.py
poco.utils.simplerpc.jsonrpc.tests.test_backend_flask.tests.TestFlaskBackend
class TestFlaskBackend(unittest.TestCase): REQUEST = json.dumps({ "id": "0", "jsonrpc": "2.0", "method": "dummy", }) def setUp(self): self.client = self._get_test_client(JSONRPCAPI()) def _get_test_client(self, api): @api.dispatcher.add_method def dummy(): return "" app = Flask(__name__) app.config["TESTING"] = True app.register_blueprint(api.as_blueprint()) return app.test_client() def test_client(self): response = self.client.post( '/', data=self.REQUEST, content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['result'], '') def test_method_not_allowed(self): response = self.client.get( '/', content_type='application/json', ) self.assertEqual(response.status_code, 405, "Should allow only POST") def test_parse_error(self): response = self.client.post( '/', data='{', content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32700) self.assertEqual(data['error']['message'], 'Parse error') def test_wrong_content_type(self): response = self.client.post( '/', data=self.REQUEST, content_type='application/x-www-form-urlencoded', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32700) self.assertEqual(data['error']['message'], 'Parse error') def test_invalid_request(self): response = self.client.post( '/', data='{"method": "dummy", "id": 1}', content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32600) self.assertEqual(data['error']['message'], 'Invalid Request') def test_method_not_found(self): data = { "jsonrpc": "2.0", "method": "dummy2", "id": 1 } response = self.client.post( '/', data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32601) self.assertEqual(data['error']['message'], 'Method not found') def test_invalid_parameters(self): data = { "jsonrpc": "2.0", "method": "dummy", "params": [42], "id": 1 } response = self.client.post( '/', data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32602) self.assertEqual(data['error']['message'], 'Invalid params') def test_resource_map(self): response = self.client.get('/map') self.assertEqual(response.status_code, 200) self.assertTrue("JSON-RPC map" in response.data.decode('utf8')) def test_method_not_allowed_prefix(self): response = self.client.get( '/', content_type='application/json', ) self.assertEqual(response.status_code, 405) def test_resource_map_prefix(self): response = self.client.get('/map') self.assertEqual(response.status_code, 200) def test_as_view(self): api = JSONRPCAPI() with patch.object(api, 'jsonrpc') as mock_jsonrpc: self.assertIs(api.as_view(), mock_jsonrpc) def test_not_check_content_type(self): client = self._get_test_client(JSONRPCAPI(check_content_type=False)) response = client.post( '/', data=self.REQUEST, ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['result'], '') def test_check_content_type(self): client = self._get_test_client(JSONRPCAPI(check_content_type=False)) response = client.post( '/', data=self.REQUEST, content_type="application/x-www-form-urlencoded" ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['result'], '') def test_empty_initial_dispatcher(self): class SubDispatcher(type(api.dispatcher)): pass custom_dispatcher = SubDispatcher() custom_api = JSONRPCAPI(custom_dispatcher) self.assertEqual(type(custom_api.dispatcher), SubDispatcher) self.assertEqual(id(custom_api.dispatcher), id(custom_dispatcher))
class TestFlaskBackend(unittest.TestCase): def setUp(self): pass def _get_test_client(self, api): pass @api.dispatcher.add_method def dummy(): pass def test_client(self): pass def test_method_not_allowed(self): pass def test_parse_error(self): pass def test_wrong_content_type(self): pass def test_invalid_request(self): pass def test_method_not_found(self): pass def test_invalid_parameters(self): pass def test_resource_map(self): pass def test_method_not_allowed_prefix(self): pass def test_resource_map_prefix(self): pass def test_as_view(self): pass def test_not_check_content_type(self): pass def test_check_content_type(self): pass def test_empty_initial_dispatcher(self): pass class SubDispatcher(type(api.dispatcher)):
20
0
8
0
8
0
1
0
1
3
2
0
16
1
16
88
153
18
135
49
115
0
84
47
65
1
2
1
17
3,478
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_backend_flask/tests.py
poco.utils.simplerpc.jsonrpc.tests.test_backend_flask.tests.TestFlaskBackend.test_empty_initial_dispatcher.SubDispatcher
class SubDispatcher(type(api.dispatcher)): pass
class SubDispatcher(type(api.dispatcher)): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
2
0
0
3,479
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_dispatcher.py
poco.utils.simplerpc.jsonrpc.tests.test_dispatcher.TestDispatcher.test_init_from_object_instance.Dummy
class Dummy(): def one(self): pass def two(self): pass
class Dummy(): def one(self): pass def two(self): pass
3
0
2
0
2
0
1
0
0
0
0
0
2
0
2
2
7
2
5
3
2
0
5
3
2
1
0
0
2
3,480
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_utils.py
poco.utils.simplerpc.jsonrpc.tests.test_utils.TestJSONSerializable.setUp.A
class A(JSONSerializable): @property def json(self): pass
class A(JSONSerializable): @property def json(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
4
0
4
3
1
0
3
2
1
1
2
0
1
3,481
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/six.py
poco.utils.six.Iterator
class Iterator(object): def next(self): return type(self).__next__(self)
class Iterator(object): def next(self): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
1
4
1
3
2
1
0
3
2
1
1
1
0
1
3,482
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/six.py
poco.utils.six.X
class X(object): def __len__(self): return 1 << 31
class X(object): def __len__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
4
1
3
2
1
0
3
2
1
1
1
0
1
3,483
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/six.py
poco.utils.six.with_metaclass.metaclass
class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases)
class metaclass(type): def __new__(cls, name, this_bases, d): pass @classmethod def __prepare__(cls, name, this_bases): pass
4
0
2
0
2
0
1
0
1
0
0
0
1
0
2
15
8
2
6
4
2
0
5
3
2
1
2
0
2
3,484
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/transport/tcp/protocol.py
poco.utils.simplerpc.transport.tcp.protocol.SimpleProtocolFilter
class SimpleProtocolFilter(object): """ 简单协议过滤器 协议按照 [有效数据字节数][有效数据] 这种协议包的格式进行打包和解包 [有效数据字节数]长度HEADER_SIZE字节 [有效数据]长度有效数据字节数字节 本类按照这种方式,顺序从数据流中取出数据进行拼接,一旦接收完一个完整的协议包,就会将协议包返回 [有效数据]字段接收到后会按照utf-8进行解码,因为在传输过程中是用utf-8进行编码的 所有编解码的操作在该类中完成 """ def __init__(self): super(SimpleProtocolFilter, self).__init__() self.buf = b'' def input(self, data): """ 小数据片段拼接成完整数据包 如果内容足够则yield数据包 """ self.buf += data while len(self.buf) > HEADER_SIZE: data_len = struct.unpack('i', self.buf[0:HEADER_SIZE])[0] if len(self.buf) >= data_len + HEADER_SIZE: content = self.buf[HEADER_SIZE:data_len + HEADER_SIZE] self.buf = self.buf[data_len + HEADER_SIZE:] yield content else: break @staticmethod def pack(content): """ content should be str """ if isinstance(content, six.text_type): content = content.encode("utf-8") return struct.pack('i', len(content)) + content @staticmethod def unpack(data): """ return length, content """ length = struct.unpack('i', data[0:HEADER_SIZE]) return length[0], data[HEADER_SIZE:]
class SimpleProtocolFilter(object): ''' 简单协议过滤器 协议按照 [有效数据字节数][有效数据] 这种协议包的格式进行打包和解包 [有效数据字节数]长度HEADER_SIZE字节 [有效数据]长度有效数据字节数字节 本类按照这种方式,顺序从数据流中取出数据进行拼接,一旦接收完一个完整的协议包,就会将协议包返回 [有效数据]字段接收到后会按照utf-8进行解码,因为在传输过程中是用utf-8进行编码的 所有编解码的操作在该类中完成 ''' def __init__(self): pass def input(self, data): ''' 小数据片段拼接成完整数据包 如果内容足够则yield数据包 ''' pass @staticmethod def pack(content): ''' content should be str ''' pass @staticmethod def unpack(data): ''' return length, content ''' pass
7
4
7
0
5
2
2
0.65
1
1
0
0
2
1
4
4
42
4
23
11
16
15
20
9
15
3
1
2
7
3,485
AirtestProject/Poco
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AirtestProject_Poco/poco/utils/net/transport/ws.py
poco.utils.net.transport.ws.WsSocket.bind.MyWsApp
class MyWsApp(WebSocket): def handleConnected(self2): self.connections[self2] = six.text_type(uuid.uuid4()) self.connections_endpoints[self2.address] = self2 print('server on accept. {}'.format(self2)) def handleMessage(self2): print('received_message from {}: {}'.format( self2.address, self2.data)) cid = self.connections.get(self2) if cid: self.rq.put((cid, self2.data)) def handleClose(self2): self.connections.pop(self2, None) self.connections_endpoints.pop(self2.address, None) print('client gone. {}'.format(self2.address))
class MyWsApp(WebSocket): def handleConnected(self2): pass def handleMessage(self2): pass def handleClose(self2): pass
4
0
4
0
4
0
1
0
1
1
1
0
3
0
3
17
16
2
14
5
10
0
14
5
10
2
2
1
4
3,486
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/transport/tcp/main.py
poco.utils.simplerpc.transport.tcp.main.TcpClient
class TcpClient(IClient): """docstring for TcpClient""" def __init__(self, addr=DEFAULT_ADDR): super(TcpClient, self).__init__() self.addr = addr self.prot = SimpleProtocolFilter() self.c = None def __str__(self): return 'tcp://{}:{}'.format(*self.addr) __repr__ = __str__ def connect(self): if not self.c: self.c = Client(self.addr, on_connect=self.on_connect, on_close=self.on_close) self.c.connect() def send(self, msg): msg_bytes = self.prot.pack(msg) self.c.send(msg_bytes) def recv(self): try: msg_bytes = self.c.recv() except socket.timeout: # print("socket recv timeout") msg_bytes = b"" return self.prot.input(msg_bytes) def close(self): self.c.close() self.c = None
class TcpClient(IClient): '''docstring for TcpClient''' def __init__(self, addr=DEFAULT_ADDR): pass def __str__(self): pass def connect(self): pass def send(self, msg): pass def recv(self): pass def close(self): pass
7
1
4
0
4
0
1
0.07
1
3
2
0
6
4
6
13
34
5
27
14
20
2
25
13
18
2
3
1
8
3,487
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/ios/__init__.py
poco.drivers.ios.iosPocoAgent
class iosPocoAgent(PocoAgent): def __init__(self, client): self.client = client hierarchy = FrozenUIHierarchy(iosDumper(self.client)) screen = AirtestScreen() input = AirtestInput() super(iosPocoAgent, self).__init__(hierarchy, input, screen, None)
class iosPocoAgent(PocoAgent): def __init__(self, client): pass
2
0
7
1
6
0
1
0
1
5
4
0
1
1
1
7
8
1
7
5
5
0
7
5
5
1
2
0
1
3,488
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/exceptions.py
poco.sdk.exceptions.NoSuchTargetException
class NoSuchTargetException(Exception): """ Raised when the index is out of range for selecting the UI element by given index. .. TODO:: Maybe this is a little bit redundant to :py:class:`poco.exceptions.PocoNoSuchNodeException`. Should be optimized. """ pass
class NoSuchTargetException(Exception): ''' Raised when the index is out of range for selecting the UI element by given index. .. TODO:: Maybe this is a little bit redundant to :py:class:`poco.exceptions.PocoNoSuchNodeException`. Should be optimized. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
10
9
2
2
1
1
5
2
1
1
0
3
0
0
3,489
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/exceptions.py
poco.sdk.exceptions.NodeHasBeenRemovedException
class NodeHasBeenRemovedException(Exception): """ Raised when the node (UI element) is refreshed (updated, recycled or destroyed) while retrieving the attributes during traversing the hierarchy. In some engines implementations, the UI hierarchy is refreshed in a stand-alone thread while poco is performing the traverse process, so the engine error might be triggered when poco is trying to retrieve the attribute of the UI element but the attribute is being updated at the same time. In this situation, poco sdk catches the engine error and raises this exception. """ def __init__(self, attrName, node): msg = 'Node was no longer alive when query attribute "{}". Please re-select.'.format(attrName) super(NodeHasBeenRemovedException, self).__init__(msg)
class NodeHasBeenRemovedException(Exception): ''' Raised when the node (UI element) is refreshed (updated, recycled or destroyed) while retrieving the attributes during traversing the hierarchy. In some engines implementations, the UI hierarchy is refreshed in a stand-alone thread while poco is performing the traverse process, so the engine error might be triggered when poco is trying to retrieve the attribute of the UI element but the attribute is being updated at the same time. In this situation, poco sdk catches the engine error and raises this exception. ''' def __init__(self, attrName, node): pass
2
1
3
0
3
0
1
2
1
1
0
0
1
0
1
11
14
2
4
3
2
8
4
3
2
1
3
0
1
3,490
AirtestProject/Poco
AirtestProject_Poco/poco/utils/net/transport/tcp.py
poco.utils.net.transport.tcp.TcpSocket
class TcpSocket(Transport): def __init__(self, RX_SIZE=65536): super(TcpSocket, self).__init__() # active socket object self.s = None self.connections = {} # sock -> Connection self.connections_endpoints = {} # endpoint -> Connection self.rq = Queue() self.RX_SIZE = RX_SIZE def connect(self, endpoint): if endpoint in self.connections_endpoints: raise RuntimeError("Already connected to {}".format(endpoint)) c = socket.socket() c.connect(endpoint) cid = six.text_type(uuid.uuid4()) conn = Connection(cid, c, endpoint, self.RX_SIZE) self.connections[c] = conn self.connections_endpoints[endpoint] = conn def disconnect(self, endpoint=None): if endpoint is not None: conn = self.connections_endpoints.pop(endpoint, None) if conn: self.connections.pop(conn.get_socket_object(), None) conn.close() else: for _, conn in self.connections_endpoints.items(): conn.close() self.connections_endpoints = {} self.connections = {} def bind(self, endpoint): if self.s is not None: raise RuntimeError("Already bound at {}".format(self.s.getsockname())) ip, port = endpoint if ip in ('', '*', '0'): ip = '0.0.0.0' self.s = socket.socket() self.s.bind((ip, port)) self.s.listen(10) print('server listens on ("{}", {}) transport socket'.format(ip, port)) def update(self, timeout=0.002): rlist = [] if self.s is not None: rlist.append(self.s) rlist.extend(self.connections.keys()) r, _, _ = select.select(rlist, [], [], timeout) for c in r: if c is self.s: client_sock, endpoint = self.s.accept() print('accept from: {}'.format(endpoint)) cid = six.text_type(uuid.uuid4()) conn = Connection(cid, client_sock, endpoint, self.RX_SIZE) self.connections[client_sock] = conn self.connections_endpoints[endpoint] = conn else: conn = self.connections.get(c) if not conn: continue try: for packet in conn.recv(): self.rq.put((conn.cid, packet)) except ConnectionReset: self.connections.pop(c) return self.recv() def recv(self): try: return self.rq.get(False) except Empty: return None, None def send(self, cid, packet): if cid is None: # broadcast for _, conn in self.connections.items(): conn.send(packet) else: conn = self.get_connection(cid) if conn: conn.send(packet) def get_connection(self, cid): for sock, conn in self.connections.items(): if conn.cid == cid: return conn return None def __str__(self): return 'Tcp connection(s) at {}'.format(self.connections_endpoints.keys()) __repr__ = __str__
class TcpSocket(Transport): def __init__(self, RX_SIZE=65536): pass def connect(self, endpoint): pass def disconnect(self, endpoint=None): pass def bind(self, endpoint): pass def update(self, timeout=0.002): pass def recv(self): pass def send(self, cid, packet): pass def get_connection(self, cid): pass def __str__(self): pass
10
0
10
1
9
0
3
0.05
1
6
2
0
9
5
9
15
99
14
83
31
73
4
80
31
70
7
2
4
27
3,491
AirtestProject/Poco
AirtestProject_Poco/poco/utils/net/transport/tcp.py
poco.utils.net.transport.tcp.ConnectionReset
class ConnectionReset(Exception): pass
class ConnectionReset(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
3,492
AirtestProject/Poco
AirtestProject_Poco/poco/utils/net/transport/tcp.py
poco.utils.net.transport.tcp.Connection
class Connection(object): def __init__(self, cid, sock, endpoint, RX_SIZE=65536): super(Connection, self).__init__() self.cid = cid self.sock = sock self.endpoint = endpoint self.p = SimpleProtocolFilter() self.RX_SIZE = RX_SIZE def send(self, packet): data = self.p.pack(packet) self.sock.sendall(data) def recv(self): rxdata = '' try: rxdata = self.sock.recv(self.RX_SIZE) except socket.error as e: if e.errno in (errno.ECONNRESET, ): raise ConnectionReset if not rxdata: self.close() raise ConnectionReset else: for packet in self.p.input(rxdata): yield packet def close(self): try: self.sock.close() except socket.error: pass def get_socket_object(self): return self.sock
class Connection(object): def __init__(self, cid, sock, endpoint, RX_SIZE=65536): pass def send(self, packet): pass def recv(self): pass def close(self): pass def get_socket_object(self): pass
6
0
6
0
6
0
2
0
1
3
2
0
5
5
5
5
36
5
31
15
25
0
30
14
24
5
1
2
10
3,493
AirtestProject/Poco
AirtestProject_Poco/poco/utils/net/transport/simple_wss.py
poco.utils.net.transport.simple_wss.WebSocket
class WebSocket(object): def __init__(self, server, sock, address): self.server = server self.client = sock self.address = address self.handshaked = False self.headerbuffer = bytearray() self.headertoread = 2048 self.fin = 0 self.data = bytearray() self.opcode = 0 self.hasmask = 0 self.maskarray = None self.length = 0 self.lengtharray = None self.index = 0 self.request = None self.usingssl = False self.frag_start = False self.frag_type = BINARY self.frag_buffer = None self.frag_decoder = codecs.getincrementaldecoder('utf-8')(errors='strict') self.closed = False self.sendq = deque() self.state = HEADERB1 # restrict the size of header and payload for security reasons self.maxheader = MAXHEADER self.maxpayload = MAXPAYLOAD def handleMessage(self): """ Called when websocket frame is received. To access the frame data call self.data. If the frame is Text then self.data is a unicode object. If the frame is Binary then self.data is a bytearray object. """ pass def handleConnected(self): """ Called when a websocket client connects to the server. """ pass def handleClose(self): """ Called when a websocket server gets a Close frame from a client. """ pass def _handlePacket(self): if self.opcode == CLOSE: pass elif self.opcode == STREAM: pass elif self.opcode == TEXT: pass elif self.opcode == BINARY: pass elif self.opcode == PONG or self.opcode == PING: if len(self.data) > 125: raise Exception('control frame length can not be > 125') else: # unknown or reserved opcode so just close raise Exception('unknown opcode') if self.opcode == CLOSE: status = 1000 reason = u'' length = len(self.data) if length == 0: pass elif length >= 2: status = struct.unpack_from('!H', self.data[:2])[0] reason = self.data[2:] if status not in _VALID_STATUS_CODES: status = 1002 if len(reason) > 0: try: reason = reason.decode('utf8', errors='strict') except: status = 1002 else: status = 1002 self.close(status, reason) return elif self.fin == 0: if self.opcode != STREAM: if self.opcode == PING or self.opcode == PONG: raise Exception('control messages can not be fragmented') self.frag_type = self.opcode self.frag_start = True self.frag_decoder.reset() if self.frag_type == TEXT: self.frag_buffer = [] utf_str = self.frag_decoder.decode(self.data, final = False) if utf_str: self.frag_buffer.append(utf_str) else: self.frag_buffer = bytearray() self.frag_buffer.extend(self.data) else: if self.frag_start is False: raise Exception('fragmentation protocol error') if self.frag_type == TEXT: utf_str = self.frag_decoder.decode(self.data, final = False) if utf_str: self.frag_buffer.append(utf_str) else: self.frag_buffer.extend(self.data) else: if self.opcode == STREAM: if self.frag_start is False: raise Exception('fragmentation protocol error') if self.frag_type == TEXT: utf_str = self.frag_decoder.decode(self.data, final = True) self.frag_buffer.append(utf_str) self.data = u''.join(self.frag_buffer) else: self.frag_buffer.extend(self.data) self.data = self.frag_buffer self.handleMessage() self.frag_decoder.reset() self.frag_type = BINARY self.frag_start = False self.frag_buffer = None elif self.opcode == PING: self._sendMessage(False, PONG, self.data) elif self.opcode == PONG: pass else: if self.frag_start is True: raise Exception('fragmentation protocol error') if self.opcode == TEXT: try: self.data = self.data.decode('utf8', errors='strict') except Exception as exp: raise Exception('invalid utf-8 payload') self.handleMessage() def _handleData(self): # do the HTTP header and handshake if self.handshaked is False: data = self.client.recv(self.headertoread) if not data: raise Exception('remote socket closed') else: # accumulate self.headerbuffer.extend(data) if len(self.headerbuffer) >= self.maxheader: raise Exception('header exceeded allowable size') # indicates end of HTTP header if b'\r\n\r\n' in self.headerbuffer: self.request = HTTPRequest(self.headerbuffer) # handshake rfc 6455 try: key = self.request.headers['Sec-WebSocket-Key'] k = key.encode('ascii') + GUID_STR.encode('ascii') k_s = base64.b64encode(hashlib.sha1(k).digest()).decode('ascii') hStr = HANDSHAKE_STR % {'acceptstr': k_s} self.sendq.append((BINARY, hStr.encode('ascii'))) self.handshaked = True self.handleConnected() except Exception as e: raise Exception('handshake failed: %s', str(e)) # else do normal data else: data = self.client.recv(16384) if not data: raise Exception("remote socket closed") if VER >= 3: for d in data: self._parseMessage(d) else: for d in data: self._parseMessage(ord(d)) def close(self, status = 1000, reason = u''): """ Send Close frame to the client. The underlying socket is only closed when the client acknowledges the Close frame. status is the closing identifier. reason is the reason for the close. """ try: if self.closed is False: close_msg = bytearray() close_msg.extend(struct.pack("!H", status)) if _check_unicode(reason): close_msg.extend(reason.encode('utf-8')) else: close_msg.extend(reason) self._sendMessage(False, CLOSE, close_msg) finally: self.closed = True def _sendBuffer(self, buff, send_all = False): size = len(buff) tosend = size already_sent = 0 while tosend > 0: try: # i should be able to send a bytearray sent = self.client.send(buff[already_sent:]) if sent == 0: raise RuntimeError('socket connection broken') already_sent += sent tosend -= sent except socket.error as e: # if we have full buffers then wait for them to drain and try again if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]: if send_all: continue return buff[already_sent:] else: raise e return None def sendFragmentStart(self, data): """ Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ opcode = BINARY if _check_unicode(data): opcode = TEXT self._sendMessage(True, opcode, data) def sendFragment(self, data): """ see sendFragmentStart() If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ self._sendMessage(True, STREAM, data) def sendFragmentEnd(self, data): """ see sendFragmentEnd() If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ self._sendMessage(False, STREAM, data) def sendMessage(self, data): """ Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ opcode = BINARY if _check_unicode(data): opcode = TEXT self._sendMessage(False, opcode, data) def _sendMessage(self, fin, opcode, data): payload = bytearray() b1 = 0 b2 = 0 if fin is False: b1 |= 0x80 b1 |= opcode if _check_unicode(data): data = data.encode('utf-8') length = len(data) payload.append(b1) if length <= 125: b2 |= length payload.append(b2) elif length >= 126 and length <= 65535: b2 |= 126 payload.append(b2) payload.extend(struct.pack("!H", length)) else: b2 |= 127 payload.append(b2) payload.extend(struct.pack("!Q", length)) if length > 0: payload.extend(data) self.sendq.append((opcode, payload)) def _parseMessage(self, byte): # read in the header if self.state == HEADERB1: self.fin = byte & 0x80 self.opcode = byte & 0x0F self.state = HEADERB2 self.index = 0 self.length = 0 self.lengtharray = bytearray() self.data = bytearray() rsv = byte & 0x70 if rsv != 0: raise Exception('RSV bit must be 0') elif self.state == HEADERB2: mask = byte & 0x80 length = byte & 0x7F if self.opcode == PING and length > 125: raise Exception('ping packet is too large') if mask == 128: self.hasmask = True else: self.hasmask = False if length <= 125: self.length = length # if we have a mask we must read it if self.hasmask is True: self.maskarray = bytearray() self.state = MASK else: # if there is no mask and no payload we are done if self.length <= 0: try: self._handlePacket() finally: self.state = HEADERB1 self.data = bytearray() # we have no mask and some payload else: #self.index = 0 self.data = bytearray() self.state = PAYLOAD elif length == 126: self.lengtharray = bytearray() self.state = LENGTHSHORT elif length == 127: self.lengtharray = bytearray() self.state = LENGTHLONG elif self.state == LENGTHSHORT: self.lengtharray.append(byte) if len(self.lengtharray) > 2: raise Exception('short length exceeded allowable size') if len(self.lengtharray) == 2: self.length = struct.unpack_from('!H', self.lengtharray)[0] if self.hasmask is True: self.maskarray = bytearray() self.state = MASK else: # if there is no mask and no payload we are done if self.length <= 0: try: self._handlePacket() finally: self.state = HEADERB1 self.data = bytearray() # we have no mask and some payload else: #self.index = 0 self.data = bytearray() self.state = PAYLOAD elif self.state == LENGTHLONG: self.lengtharray.append(byte) if len(self.lengtharray) > 8: raise Exception('long length exceeded allowable size') if len(self.lengtharray) == 8: self.length = struct.unpack_from('!Q', self.lengtharray)[0] if self.hasmask is True: self.maskarray = bytearray() self.state = MASK else: # if there is no mask and no payload we are done if self.length <= 0: try: self._handlePacket() finally: self.state = HEADERB1 self.data = bytearray() # we have no mask and some payload else: #self.index = 0 self.data = bytearray() self.state = PAYLOAD # MASK STATE elif self.state == MASK: self.maskarray.append(byte) if len(self.maskarray) > 4: raise Exception('mask exceeded allowable size') if len(self.maskarray) == 4: # if there is no mask and no payload we are done if self.length <= 0: try: self._handlePacket() finally: self.state = HEADERB1 self.data = bytearray() # we have no mask and some payload else: #self.index = 0 self.data = bytearray() self.state = PAYLOAD # PAYLOAD STATE elif self.state == PAYLOAD: if self.hasmask is True: self.data.append( byte ^ self.maskarray[self.index % 4] ) else: self.data.append( byte ) # if length exceeds allowable size then we except and remove the connection if len(self.data) >= self.maxpayload: raise Exception('payload exceeded allowable size') # check if we have processed length bytes; if so we are done if (self.index+1) == self.length: try: self._handlePacket() finally: #self.index = 0 self.state = HEADERB1 self.data = bytearray() else: self.index += 1
class WebSocket(object): def __init__(self, server, sock, address): pass def handleMessage(self): ''' Called when websocket frame is received. To access the frame data call self.data. If the frame is Text then self.data is a unicode object. If the frame is Binary then self.data is a bytearray object. ''' pass def handleConnected(self): ''' Called when a websocket client connects to the server. ''' pass def handleClose(self): ''' Called when a websocket server gets a Close frame from a client. ''' pass def _handlePacket(self): pass def _handleData(self): pass def close(self, status = 1000, reason = u''): ''' Send Close frame to the client. The underlying socket is only closed when the client acknowledges the Close frame. status is the closing identifier. reason is the reason for the close. ''' pass def _sendBuffer(self, buff, send_all = False): pass def sendFragmentStart(self, data): ''' Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. ''' pass def sendFragmentStart(self, data): ''' see sendFragmentStart() If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. ''' pass def sendFragmentEnd(self, data): ''' see sendFragmentEnd() If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. ''' pass def sendMessage(self, data): ''' Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. ''' pass def _sendMessage(self, fin, opcode, data): pass def _parseMessage(self, byte): pass
15
8
34
6
24
5
7
0.21
1
5
1
1
14
25
14
14
493
95
330
67
315
68
284
64
269
29
1
5
93
3,494
AirtestProject/Poco
AirtestProject_Poco/poco/utils/net/transport/simple_wss.py
poco.utils.net.transport.simple_wss.SimpleWebSocketServer
class SimpleWebSocketServer(object): def __init__(self, host, port, websocketclass, selectInterval = 0.1): self.websocketclass = websocketclass self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serversocket.bind((host, port)) self.serversocket.listen(5) self.selectInterval = selectInterval self.connections = {} self.listeners = [self.serversocket] def _decorateSocket(self, sock): return sock def _constructWebSocket(self, sock, address): return self.websocketclass(self, sock, address) def close(self): self.serversocket.close() for desc, conn in self.connections.items(): conn.close() self._handleClose(conn) def _handleClose(self, client): client.client.close() # only call handleClose when we have a successful websocket connection if client.handshaked: try: client.handleClose() except: pass def serveonce(self): writers = [] for fileno in self.listeners: if fileno == self.serversocket: continue client = self.connections[fileno] if client.sendq: writers.append(fileno) if self.selectInterval: rList, wList, xList = select(self.listeners, writers, self.listeners, self.selectInterval) else: rList, wList, xList = select(self.listeners, writers, self.listeners) for ready in wList: client = self.connections[ready] try: while client.sendq: opcode, payload = client.sendq.popleft() remaining = client._sendBuffer(payload) if remaining is not None: client.sendq.appendleft((opcode, remaining)) break else: if opcode == CLOSE: raise Exception('received client close') except Exception as n: self._handleClose(client) del self.connections[ready] self.listeners.remove(ready) for ready in rList: if ready == self.serversocket: sock = None try: sock, address = self.serversocket.accept() newsock = self._decorateSocket(sock) newsock.setblocking(0) fileno = newsock.fileno() self.connections[fileno] = self._constructWebSocket(newsock, address) self.listeners.append(fileno) except Exception as n: if sock is not None: sock.close() else: if ready not in self.connections: continue client = self.connections[ready] try: client._handleData() except Exception as n: self._handleClose(client) del self.connections[ready] self.listeners.remove(ready) for failed in xList: if failed == self.serversocket: self.close() raise Exception('server socket failed') else: if failed not in self.connections: continue client = self.connections[failed] self._handleClose(client) del self.connections[failed] self.listeners.remove(failed) def serveforever(self): while True: self.serveonce()
class SimpleWebSocketServer(object): def __init__(self, host, port, websocketclass, selectInterval = 0.1): pass def _decorateSocket(self, sock): pass def _constructWebSocket(self, sock, address): pass def close(self): pass def _handleClose(self, client): pass def serveonce(self): pass def serveforever(self): pass
8
0
14
1
13
0
4
0.01
1
2
0
1
7
5
7
7
104
12
91
26
83
1
87
25
79
19
1
5
29
3,495
AirtestProject/Poco
AirtestProject_Poco/poco/utils/net/transport/simple_wss.py
poco.utils.net.transport.simple_wss.SimpleSSLWebSocketServer
class SimpleSSLWebSocketServer(SimpleWebSocketServer): def __init__(self, host, port, websocketclass, certfile, keyfile, version = ssl.PROTOCOL_TLSv1, selectInterval = 0.1): SimpleWebSocketServer.__init__(self, host, port, websocketclass, selectInterval) self.context = ssl.SSLContext(version) self.context.load_cert_chain(certfile, keyfile) def close(self): super(SimpleSSLWebSocketServer, self).close() def _decorateSocket(self, sock): sslsock = self.context.wrap_socket(sock, server_side=True) return sslsock def _constructWebSocket(self, sock, address): ws = self.websocketclass(self, sock, address) ws.usingssl = True return ws def serveforever(self): super(SimpleSSLWebSocketServer, self).serveforever()
class SimpleSSLWebSocketServer(SimpleWebSocketServer): def __init__(self, host, port, websocketclass, certfile, keyfile, version = ssl.PROTOCOL_TLSv1, selectInterval = 0.1): pass def close(self): pass def _decorateSocket(self, sock): pass def _constructWebSocket(self, sock, address): pass def serveforever(self): pass
6
0
4
0
3
0
1
0
1
2
0
0
5
1
5
12
25
7
18
10
11
0
16
9
10
1
2
0
5
3,496
AirtestProject/Poco
AirtestProject_Poco/poco/utils/net/stdbroker.py
poco.utils.net.stdbroker.StdBroker
class StdBroker(object): def __init__(self, ep1, ep2): super(StdBroker, self).__init__() # always ep2 --request---> ep1 # ep2 <--response-- ep1 self.ep1 = self._make_transport(ep1) self.ep2 = self._make_transport(ep2) self.requests_map = {} # reqid -> requester cid self.t = threading.Thread(target=self.loop) self.t.daemon = True self.t.start() def _make_transport(self, ep): ep = urlparse(ep) if ep.scheme.startswith('ws'): transport = WsSocket() else: transport = TcpSocket() transport.bind((ep.hostname, ep.port)) return transport def deserialize(self, data): if six.PY3 and not isinstance(data, six.text_type): data = data.decode('utf-8') return json.loads(data) def serialize(self, packet): return json.dumps(packet) def handle_request(self): cid, data = self.ep2.update() if data: packet = self.deserialize(data) reqid = packet['id'] self.requests_map[reqid] = cid self.ep1.send(None, data) def handle_response(self): _, data = self.ep1.update() if data: packet = self.deserialize(data) reqid = packet['id'] cid = self.requests_map.pop(reqid, None) if cid: self.ep2.send(cid, data) def loop(self): print('StdBroker on.') while True: self.handle_request() self.handle_response()
class StdBroker(object): def __init__(self, ep1, ep2): pass def _make_transport(self, ep): pass def deserialize(self, data): pass def serialize(self, packet): pass def handle_request(self): pass def handle_response(self): pass def loop(self): pass
8
0
7
0
6
0
2
0.07
1
4
2
0
7
4
7
7
53
8
43
20
35
3
42
20
34
3
1
2
13
3,497
AirtestProject/Poco
AirtestProject_Poco/poco/utils/hunter/command.py
poco.utils.hunter.command.HunterCommand
class HunterCommand(CommandInterface): def __init__(self, hunter): self.hunter = hunter def command(self, cmd, type=None): """ 通过hunter调用gm指令,可调用hunter指令库中定义的所有指令,也可以调用text类型的gm指令 gm指令相关功能请参考safaia GM指令扩展模块 :param cmd: 指令 :param type: 语言,默认text :return: None """ type = type or 'text' self.hunter.script(cmd, lang=type)
class HunterCommand(CommandInterface): def __init__(self, hunter): pass def command(self, cmd, type=None): ''' 通过hunter调用gm指令,可调用hunter指令库中定义的所有指令,也可以调用text类型的gm指令 gm指令相关功能请参考safaia GM指令扩展模块 :param cmd: 指令 :param type: 语言,默认text :return: None ''' pass
3
1
7
1
3
4
1
1.17
1
0
0
0
2
1
2
3
16
3
6
4
3
7
6
4
3
1
2
0
2
3,498
AirtestProject/Poco
AirtestProject_Poco/poco/utils/device.py
poco.utils.device.VirtualDevice
class VirtualDevice(Device): def __init__(self, ip): super(VirtualDevice, self).__init__() self.ip = ip @property def uuid(self): return 'virtual-device' def get_current_resolution(self): return [1920, 1080] def get_ip_address(self): return self.ip
class VirtualDevice(Device): def __init__(self, ip): pass @property def uuid(self): pass def get_current_resolution(self): pass def get_ip_address(self): pass
6
0
2
0
2
0
1
0
1
1
0
0
4
1
4
4
14
3
11
7
5
0
10
6
5
1
1
0
4
3,499
AirtestProject/Poco
AirtestProject_Poco/poco/utils/airtest/screen.py
poco.utils.airtest.screen.AirtestScreen
class AirtestScreen(ScreenInterface): def __init__(self): super(AirtestScreen, self).__init__() def getPortSize(self): disp = current_device().display_info if disp['orientation'] in (1, 3): return [disp['height'], disp['width']] else: return [disp['width'], disp['height']] def getScreen(self, width): savepath = snapshot() return base64.b64encode(open(savepath, 'rb').read()), 'png'
class AirtestScreen(ScreenInterface): def __init__(self): pass def getPortSize(self): pass def getScreen(self, width): pass
4
0
4
0
4
0
1
0
1
1
0
0
3
0
3
5
14
2
12
6
8
0
11
6
7
2
2
1
4