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,500
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/std/rpc/reactor.py
poco.sdk.std.rpc.reactor.StdRpcReactor
class StdRpcReactor(object): def __init__(self): super(StdRpcReactor, self).__init__() self.slots = {} # method name -> method self.pending_response = {} # rid -> result def register(self, name, method): if not callable(method): raise ValueError('Argument `method` should be a callable object. Got {}'.format(repr(method))) if name in self.slots: raise ValueError('"{}" already registered. {}'.format(name, repr(self.slots[name]))) self.slots[name] = method def dispatch(self, name, *args, **kwargs): method = self.slots.get(name) if not method: raise NoSuchMethod(name, self.slots.keys()) return method(*args, **kwargs) def handle_request(self, req): ret = { 'id': req['id'], 'jsonrpc': req['jsonrpc'], } method = req['method'] params = req['params'] try: result = self.dispatch(method, *params) ret['result'] = result except Exception as e: ret['error'] = { 'message': '{}\n\n|--- REMOTE TRACEBACK ---|\n{}|--- REMOTE TRACEBACK END ---|' .format(six.text_type(e), traceback.format_exc()) } return ret def handle_response(self, res): id = res['id'] self.pending_response[id] = res def build_request(self, method, *args, **kwargs): rid = six.text_type(uuid.uuid4()) ret = { 'id': rid, 'jsonrpc': '2.0', 'method': method, 'params': args or kwargs or [], } self.pending_response[rid] = None return ret def get_result(self, rid): return self.pending_response.get(rid)
class StdRpcReactor(object): def __init__(self): pass def register(self, name, method): pass def dispatch(self, name, *args, **kwargs): pass def handle_request(self, req): pass def handle_response(self, res): pass def build_request(self, method, *args, **kwargs): pass def get_result(self, rid): pass
8
0
7
1
7
0
2
0.04
1
4
1
0
7
2
7
7
57
10
47
18
39
2
36
17
28
3
1
1
11
3,501
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/exceptions.py
poco.sdk.exceptions.NoSuchComparatorException
class NoSuchComparatorException(Exception): """ Raised when the matcher does not support the given comparison method. """ def __init__(self, matchingMethod, matcherName): super(NoSuchComparatorException, self).__init__() self.message = 'No such matching method "{}" of this Matcher ("{}")'.format(matchingMethod, matcherName)
class NoSuchComparatorException(Exception): ''' Raised when the matcher does not support the given comparison method. ''' def __init__(self, matchingMethod, matcherName): pass
2
1
3
0
3
0
1
0.75
1
1
0
0
1
1
1
11
8
1
4
3
2
3
4
3
2
1
3
0
1
3,502
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/std/rpc/reactor.py
poco.sdk.std.rpc.reactor.NoSuchMethod
class NoSuchMethod(Exception): def __init__(self, name, available_methods): msg = 'No such method "{}". Available methods {}'.format(name, available_methods) super(NoSuchMethod, self).__init__(msg)
class NoSuchMethod(Exception): def __init__(self, name, available_methods): pass
2
0
3
0
3
0
1
0
1
1
0
0
1
0
1
11
4
0
4
3
2
0
4
3
2
1
3
0
1
3,503
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/std/rpc/controller.py
poco.sdk.std.rpc.controller.RpcRemoteException
class RpcRemoteException(Exception): pass
class RpcRemoteException(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,504
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/interfaces/command.py
poco.sdk.interfaces.command.CommandInterface
class CommandInterface(object): """ This is one of the main communication interfaces. This interface defines command-level behaviours providing abilities to control remote runtime by sending self-defined command. The provided command can be various type - from string type to specific structure of a dict. """ def command(self, cmd, type): """ Emit a command to remote runtime (target device). Args: cmd: any json serializable data. type (:obj:`str`): a string value indicated the command type (command tag). Returns: None (recommended). """ pass
class CommandInterface(object): ''' This is one of the main communication interfaces. This interface defines command-level behaviours providing abilities to control remote runtime by sending self-defined command. The provided command can be various type - from string type to specific structure of a dict. ''' def command(self, cmd, type): ''' Emit a command to remote runtime (target device). Args: cmd: any json serializable data. type (:obj:`str`): a string value indicated the command type (command tag). Returns: None (recommended). ''' pass
2
2
13
3
2
8
1
4.33
1
0
0
1
1
0
1
1
20
4
3
2
1
13
3
2
1
1
1
0
1
3,505
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/exceptions.py
poco.sdk.exceptions.UnableToSetAttributeException
class UnableToSetAttributeException(Exception): """ Raised when settings the attribute of the given UI element failed. In most cases, the reason why it failed is that the UI element does not support mutation. From the point of view of SDK implementation, this exception can be raised proactively to indicate that the modification of the attribute is not allowed. """ def __init__(self, attrName, node): msg = 'Unable to set attribute "{}" of node "{}".'.format(attrName, node) super(UnableToSetAttributeException, self).__init__(msg)
class UnableToSetAttributeException(Exception): ''' Raised when settings the attribute of the given UI element failed. In most cases, the reason why it failed is that the UI element does not support mutation. From the point of view of SDK implementation, this exception can be raised proactively to indicate that the modification of the attribute is not allowed. ''' def __init__(self, attrName, node): pass
2
1
3
0
3
0
1
1.25
1
1
0
0
1
0
1
11
10
1
4
3
2
5
4
3
2
1
3
0
1
3,506
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/exceptions.py
poco.sdk.exceptions.NonuniqueSurfaceException
class NonuniqueSurfaceException(Exception): """ Raised when the device selector matches multiple devices surface """ def __init__(self, selector): msg = 'The arguments ("{}") match multiple device surface. More precise conditions required.'.format(selector) super(NonuniqueSurfaceException, self).__init__(msg)
class NonuniqueSurfaceException(Exception): ''' Raised when the device selector matches multiple devices surface ''' def __init__(self, selector): pass
2
1
3
0
3
0
1
0.75
1
1
0
0
1
0
1
11
8
1
4
3
2
3
4
3
2
1
3
0
1
3,507
AirtestProject/Poco
AirtestProject_Poco/poco/exceptions.py
poco.exceptions.PocoNoSuchNodeException
class PocoNoSuchNodeException(PocoException): """ Raised when the UI element specified by query expression cannot be found. """ def __init__(self, objproxy): super(PocoNoSuchNodeException, self).__init__() self.message = 'Cannot find any visible node by query {}'.format(to_text(repr(objproxy)))
class PocoNoSuchNodeException(PocoException): ''' Raised when the UI element specified by query expression cannot be found. ''' def __init__(self, objproxy): pass
2
1
3
0
3
0
1
0.75
1
1
0
0
1
1
1
13
8
1
4
3
2
3
4
3
2
1
4
0
1
3,508
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/ios/__init__.py
poco.drivers.ios.iosPoco
class iosPoco(Poco): def __init__(self, device=None, **kwargs): device = device or current_device() if not device or device.__class__.__name__ != 'IOS': raise RuntimeError('Please call `connect_device` to connect an iOS device first') agent = iosPocoAgent(device) super(iosPoco, self).__init__(agent, **kwargs)
class iosPoco(Poco): def __init__(self, device=None, **kwargs): pass
2
0
7
1
6
0
2
0
1
3
1
0
1
0
1
31
8
1
7
3
5
0
7
3
5
2
3
1
2
3,509
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/windows/sdk/WindowsUIDumper.py
poco.drivers.windows.sdk.WindowsUIDumper.WindowsUIDumper
class WindowsUIDumper(AbstractDumper): def __init__(self, root): self.RootControl = root self.RootHeight = self.RootControl.BoundingRectangle[3] - self.RootControl.BoundingRectangle[1] self.RootWidth = self.RootControl.BoundingRectangle[2] - self.RootControl.BoundingRectangle[0] self.RootLeft = self.RootControl.BoundingRectangle[0] self.RootTop = self.RootControl.BoundingRectangle[1] if self.RootWidth == 0 or self.RootHeight == 0: raise InvalidSurfaceException(self, "You may have minimized or closed your window or the window is too small!") def getRoot(self): return WindowsUINode(self.RootControl, self)
class WindowsUIDumper(AbstractDumper): def __init__(self, root): pass def getRoot(self): pass
3
0
5
0
5
0
2
0
1
2
2
0
2
5
2
6
13
2
11
8
8
0
11
8
8
2
3
1
3
3,510
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/windows/sdk/WindowsUI.py
poco.drivers.windows.sdk.WindowsUI.PocoSDKWindows
class PocoSDKWindows(object): def __init__(self, addr=DEFAULT_ADDR): self.reactor = None self.addr = addr self.running = False UIAuto.OPERATION_WAIT_TIME = 0.05 # make operation faster self.root = None def Dump(self, _): res = WindowsUIDumper(self.root).dumpHierarchy() return res def SetText(self, id, val2): control = UIAuto.ControlFromHandle(id) if not control or not isinstance(val2, string_types): raise UnableToSetAttributeException("text", control) else: control.SetValue(val2) def GetSDKVersion(self): return '0.0.1' def GetDebugProfilingData(self): return {} def GetScreenSize(self): Width = self.root.BoundingRectangle[2] - self.root.BoundingRectangle[0] Height = self.root.BoundingRectangle[3] - self.root.BoundingRectangle[1] return [Width, Height] def GetWindowRect(self): return self.root.BoundingRectangle def JudgeSize(self): self.SetForeground() # 先打开窗口再获取大小,否则最小化的窗口获取到的大小会为0 size = self.GetScreenSize() if size[0] == 0 or size[1] == 0: raise InvalidSurfaceException(self, "You may have minimized or closed your window or the window is too small!") def Screenshot(self, width): self.JudgeSize() self.root.ToBitmap().ToFile('Screenshot.bmp') f = open(r'Screenshot.bmp', 'rb') deflated = zlib.compress(f.read()) # 压缩图片 ls_f = base64.b64encode(deflated) f.close() return [ls_f, "bmp.deflate"] # self.root.ToBitmap().ToFile('Screenshot.bmp') # f = open(r'Screenshot.bmp', 'rb') # ls_f = base64.b64encode(f.read()) # f.close() # return [ls_f, "bmp"] def Click(self, x, y): self.JudgeSize() self.root.Click(x, y) return True def RClick(self, x, y): self.JudgeSize() self.root.RightClick(x, y) return True def DoubleClick(self, x, y): self.JudgeSize() self.root.DoubleClick(x, y) return True def Swipe(self, x1, y1, x2, y2, duration, **kwargs): self.JudgeSize() Left = self.root.BoundingRectangle[0] Top = self.root.BoundingRectangle[1] Width = self.root.BoundingRectangle[2] - self.root.BoundingRectangle[0] Height = self.root.BoundingRectangle[3] - self.root.BoundingRectangle[1] x1 = int(Left + Width * x1) # 比例换算 y1 = int(Top + Height * y1) x2 = int(Left + Width * x2) y2 = int(Top + Height * y2) UIAuto.MAX_MOVE_SECOND = duration * 10 # 同步到跟UIAutomation库的时间设定一样 UIAuto.DragDrop(int(x1), int(y1), int(x2), int(y2)) return True def LongClick(self, x, y, duration, **kwargs): self.JudgeSize() Left = self.root.BoundingRectangle[0] Top = self.root.BoundingRectangle[1] Width = self.root.BoundingRectangle[2] - self.root.BoundingRectangle[0] Height = self.root.BoundingRectangle[3] - self.root.BoundingRectangle[1] x = Left + Width * x y = Top + Height * y UIAuto.MAX_MOVE_SECOND = duration * 10 UIAuto.DragDrop(int(x), int(y), int(x), int(y)) return True def Scroll(self, direction, percent, duration): if direction not in ('vertical', 'horizontal'): return False if direction == 'horizontal': return False self.JudgeSize() x = 0.5 # 先把鼠标移到窗口中间,这样才能保证滚动的是这个窗口。 y = 0.5 steps = percent Left = self.root.BoundingRectangle[0] Top = self.root.BoundingRectangle[1] Width = self.root.BoundingRectangle[2] - self.root.BoundingRectangle[0] Height = self.root.BoundingRectangle[3] - self.root.BoundingRectangle[1] x = Left + Width * x y = Top + Height * y x = int(x) y = int(y) UIAuto.MoveTo(x, y) interval = float(duration - 0.3 * steps) / (abs(steps) + 1) # 实现滚动时间 if interval <= 0: interval = 0.1 if steps < 0: for i in range(0, abs(steps)): time.sleep(interval) UIAuto.WheelUp(1) else: for i in range(0, abs(steps)): time.sleep(interval) UIAuto.WheelDown(1) return True def KeyEvent(self, keycode): self.JudgeSize() UIAuto.SendKeys(keycode) return True def SetForeground(self): win32gui.ShowWindow(self.root.Handle, win32con.SW_SHOWNORMAL) # 先把窗口取消最小化 UIAuto.Win32API.SetForegroundWindow(self.root.Handle) # 再把窗口设为前台,方便点击和截图 return True def EnumWindows(self): hWndList = [] # 枚举所有窗口,并把有效窗口handle保存在hwndlist里 def foo(hwnd, mouse): if win32gui.IsWindow(hwnd): hWndList.append(hwnd) win32gui.EnumWindows(foo, 0) return hWndList def ConnectWindowsByTitle(self, title): hn = set() # 匹配窗口的集合,把所有标题匹配上的窗口handle都保存在这个集合里 hWndList = self.EnumWindows() for handle in hWndList: title_temp = win32gui.GetWindowText(handle) if PY2: title_temp = title_temp.decode("gbk") # py2要解码成GBK,WindowsAPI中文返回的一般都是GBK if title == title_temp: hn.add(handle) if len(hn) == 0: return -1 return hn def ConnectWindowsByTitleRe(self, title_re): hn = set() # 匹配窗口的集合,把所有标题(正则表达式)匹配上的窗口handle都保存在这个集合里 hWndList = self.EnumWindows() for handle in hWndList: title = win32gui.GetWindowText(handle) if PY2: title = title.decode("gbk") if re.match(title_re, title): hn.add(handle) if len(hn) == 0: return -1 return hn def ConnectWindowsByHandle(self, handle): hn = set() # 匹配窗口的集合,把所有handle匹配上的窗口handle都保存在这个集合里 hWndList = self.EnumWindows() for handle_temp in hWndList: if int(handle_temp) == int(handle): hn.add(handle) break if len(hn) == 0: return -1 return hn def ConnectWindow(self, selector): # 目前来说,如下处理,以后添加更多的参数后需修改代码逻辑 argunums = 0 if 'handle' in selector: argunums += 1 if 'title' in selector: argunums += 1 if 'title_re' in selector: argunums += 1 if argunums == 0: raise ValueError("Expect handle or title, got none") elif argunums != 1: raise ValueError("Too many arguments, only need handle or title or title_re") handleSetList = [] if 'title' in selector: handleSetList.append(self.ConnectWindowsByTitle(selector['title'])) if 'handle' in selector: handleSetList.append(self.ConnectWindowsByHandle(selector['handle'])) if "title_re" in selector: handleSetList.append(self.ConnectWindowsByTitleRe(selector['title_re'])) while -1 in handleSetList: handleSetList.remove(-1) # 有些参数没有提供会返回-1.把所有的-1去掉 if len(handleSetList) is 0: raise InvalidSurfaceException(selector, "Can't find any windows by the given parameter") handleSet = reduce(operator.__and__, handleSetList) # 提供了多个参数来确定唯一一个窗口,所以要做交集,取得唯一匹配的窗口 if len(handleSet) == 0: raise InvalidSurfaceException(selector, "Can't find any windows by the given parameter") elif len(handleSet) != 1: raise NonuniqueSurfaceException(selector) else: hn = handleSet.pop() # 取得那个唯一的窗口 self.root = UIAuto.ControlFromHandle(hn) if self.root is None: raise InvalidSurfaceException(selector, "Can't find any windows by the given parameter") self.SetForeground() def run(self): self.reactor = StdRpcReactor() self.reactor.register('Dump', self.Dump) # 注册各种函数 self.reactor.register('SetText', self.SetText) self.reactor.register('GetSDKVersion', self.GetSDKVersion) self.reactor.register('GetDebugProfilingData', self.GetDebugProfilingData) self.reactor.register('GetScreenSize', self.GetScreenSize) self.reactor.register('Screenshot', self.Screenshot) self.reactor.register('Click', self.Click) self.reactor.register('Swipe', self.Swipe) self.reactor.register('LongClick', self.LongClick) self.reactor.register('KeyEvent', self.KeyEvent) self.reactor.register('SetForeground', self.SetForeground) self.reactor.register('ConnectWindow', self.ConnectWindow) self.reactor.register('Scroll', self.Scroll) self.reactor.register('RClick', self.RClick) self.reactor.register('DoubleClick', self.DoubleClick) transport = TcpSocket() transport.bind(self.addr) self.rpc = StdRpcEndpointController(transport, self.reactor) if self.running is False: self.running = True self.rpc.serve_forever()
class PocoSDKWindows(object): def __init__(self, addr=DEFAULT_ADDR): pass def Dump(self, _): pass def SetText(self, id, val2): pass def GetSDKVersion(self): pass def GetDebugProfilingData(self): pass def GetScreenSize(self): pass def GetWindowRect(self): pass def JudgeSize(self): pass def Screenshot(self, width): pass def Click(self, x, y): pass def RClick(self, x, y): pass def DoubleClick(self, x, y): pass def Swipe(self, x1, y1, x2, y2, duration, **kwargs): pass def LongClick(self, x, y, duration, **kwargs): pass def Scroll(self, direction, percent, duration): pass def KeyEvent(self, keycode): pass def SetForeground(self): pass def EnumWindows(self): pass def foo(hwnd, mouse): pass def ConnectWindowsByTitle(self, title): pass def ConnectWindowsByTitleRe(self, title_re): pass def ConnectWindowsByHandle(self, handle): pass def ConnectWindowsByTitle(self, title): pass def run(self): pass
25
0
9
1
9
1
2
0.11
1
12
7
0
23
5
23
23
253
36
211
72
186
24
206
72
181
14
1
2
58
3,511
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/unity3d_poco.py
poco.drivers.unity3d.unity3d_poco.UnityVRSupport
class UnityVRSupport(): def __init__(self, client): self.client = client self.support_vr = False try: self.support_vr = self.client.call("isVrSupported") except InvalidOperationException: raise InvalidOperationException('VR not supported') def hasMovementFinished(self): success, error_msg =self.client.call("hasMovementFinished").wait() print(success) if success != None: return True else: return False def rotateObject(self, x, y, z, camera, follower, speed=0.125): return self.client.call("RotateObject", x, y, z, camera, follower, speed) def objectLookAt(self, name, camera, follower, speed=0.125): return self.client.call("ObjectLookAt", name, camera, follower, speed)
class UnityVRSupport(): def __init__(self, client): pass def hasMovementFinished(self): pass def rotateObject(self, x, y, z, camera, follower, speed=0.125): pass def objectLookAt(self, name, camera, follower, speed=0.125): pass
5
0
5
0
5
0
2
0
0
1
1
0
4
2
4
4
22
3
19
8
14
0
18
8
13
2
0
1
6
3,512
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/unity3d_poco.py
poco.drivers.unity3d.unity3d_poco.UnityPoco
class UnityPoco(StdPoco): """ Poco Unity3D implementation. Args: addr (:py:obj:`tuple`): the endpoint of your Unity3D game, default to ``("localhost", 5001)`` unity_editor (:py:obj:`bool`): whether your Unity3D game is running in UnityEditor or not. default to ``False`` connect_default_device (:py:obj:`bool`): whether connect to a default device if no devices selected manually. default to ``True``. device (:py:obj:`Device`): :py:obj:`airtest.core.device.Device` instance provided by ``airtest``. leave the parameter default and the default device will be chosen. more details refer to ``airtest doc`` options: see :py:class:`poco.pocofw.Poco` Examples: If your game is running on Android, you could initialize poco instance by using following snippet:: from poco.drivers.unity3d import UnityPoco # your phone and your PC/mac should be inside the same sub-net. ip = '<ip address of your phone>' poco = UnityPoco((ip, 5001)) poco('button').click() ... """ def __init__(self, addr=DEFAULT_ADDR, unity_editor=False, connect_default_device=True, device=None, **options): if 'action_interval' not in options: options['action_interval'] = 0.5 if unity_editor: dev = UnityEditorWindow() else: dev = device or current_device() if dev is None and connect_default_device and not current_device(): # currently only connect to Android as default # can apply auto detection in the future dev = connect_device("Android:///") super(UnityPoco, self).__init__(addr[1], dev, ip=addr[0], **options) # If some devices fail to initialize, the UI tree cannot be obtained # self.vr = UnityVRSupport(self.agent.rpc) def send_message(self, message): self.agent.rpc.call("SendMessage", message) def invoke(self, listener, **kwargs): callback = self.agent.rpc.call("Invoke", listener=listener, data=kwargs) value, error = callback.wait() if error is not None: raise Exception(error) return value
class UnityPoco(StdPoco): ''' Poco Unity3D implementation. Args: addr (:py:obj:`tuple`): the endpoint of your Unity3D game, default to ``("localhost", 5001)`` unity_editor (:py:obj:`bool`): whether your Unity3D game is running in UnityEditor or not. default to ``False`` connect_default_device (:py:obj:`bool`): whether connect to a default device if no devices selected manually. default to ``True``. device (:py:obj:`Device`): :py:obj:`airtest.core.device.Device` instance provided by ``airtest``. leave the parameter default and the default device will be chosen. more details refer to ``airtest doc`` options: see :py:class:`poco.pocofw.Poco` Examples: If your game is running on Android, you could initialize poco instance by using following snippet:: from poco.drivers.unity3d import UnityPoco # your phone and your PC/mac should be inside the same sub-net. ip = '<ip address of your phone>' poco = UnityPoco((ip, 5001)) poco('button').click() ... ''' def __init__(self, addr=DEFAULT_ADDR, unity_editor=False, connect_default_device=True, device=None, **options): pass def send_message(self, message): pass def invoke(self, listener, **kwargs): pass
4
1
9
2
6
1
2
1.21
1
2
0
0
3
0
3
34
56
14
19
7
15
23
18
7
14
4
4
1
7
3,513
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/wait_any_ui.py
poco.drivers.unity3d.test.tutorial.wait_any_ui.WaitAnyUITutorial
class WaitAnyUITutorial(TutorialCase): def runTest(self): self.poco(text='wait UI').click() bomb_count = 0 while True: blue_fish = self.poco('fish_emitter').child('blue') yellow_fish = self.poco('fish_emitter').child('yellow') bomb = self.poco('fish_emitter').child('bomb') fish = self.poco.wait_for_any([blue_fish, yellow_fish, bomb]) if fish is bomb: bomb_count += 1 if bomb_count > 3: return else: fish.click() time.sleep(2.5)
class WaitAnyUITutorial(TutorialCase): def runTest(self): pass
2
0
16
1
15
0
4
0
1
0
0
0
1
0
1
3
17
1
16
7
14
0
15
7
13
4
2
3
4
3,514
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/wait_all_ui.py
poco.drivers.unity3d.test.tutorial.wait_all_ui.WaitAnyUITutorial
class WaitAnyUITutorial(TutorialCase): def runTest(self): self.poco(text='wait UI 2').click() blue_fish = self.poco('fish_area').child('blue') yellow_fish = self.poco('fish_area').child('yellow') shark = self.poco('fish_area').child('black') self.poco.wait_for_all([blue_fish, yellow_fish, shark]) self.poco('btn_back').click() time.sleep(2.5)
class WaitAnyUITutorial(TutorialCase): def runTest(self): pass
2
0
10
2
8
0
1
0
1
0
0
0
1
0
1
3
11
2
9
5
7
0
9
5
7
1
2
0
1
3,515
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/scroll2.py
poco.drivers.unity3d.test.tutorial.scroll2.Scroll2Tutorial
class Scroll2Tutorial(TutorialCase): def runTest(self): listView = self.poco('Scroll View') listView.focus([0.5, 0.8]).drag_to(listView.focus([0.5, 0.2])) time.sleep(1)
class Scroll2Tutorial(TutorialCase): def runTest(self): pass
2
0
4
0
4
0
1
0
1
0
0
0
1
0
1
3
5
0
5
3
3
0
5
3
3
1
2
0
1
3,516
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/std/rpc/controller.py
poco.sdk.std.rpc.controller.StdRpcEndpointController
class StdRpcEndpointController(object): def __init__(self, transport, reactor): super(StdRpcEndpointController, self).__init__() self.transport = transport self.reactor = reactor 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 serve_forever(self): while True: cid, data = self.transport.update() if data: packet = self.deserialize(data) if 'method' in packet: result = self.reactor.handle_request(packet) sres = self.serialize(result) self.transport.send(cid, sres) else: self.reactor.handle_response(packet) def call(self, method, *args, **kwargs): req = self.reactor.build_request(method, *args, **kwargs) rid = req['id'] sreq = self.serialize(req) self.transport.send(None, sreq) while True: time.sleep(0.004) res = self.reactor.get_result(rid) if res is not None: if 'result' in res: return res['result'] if 'error' in res: raise RpcRemoteException(res['error']['message']) raise RuntimeError('Invalid response from {}. Got {}'.format(self.transport, res))
class StdRpcEndpointController(object): def __init__(self, transport, reactor): pass def deserialize(self, data): pass def serialize(self, packet): pass def serve_forever(self): pass def call(self, method, *args, **kwargs): pass
6
0
7
0
7
0
3
0
1
3
1
0
5
2
5
5
42
6
36
16
30
0
35
16
29
5
1
3
13
3,517
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/exceptions.py
poco.sdk.exceptions.InvalidSurfaceException
class InvalidSurfaceException(Exception): """ Raised when the device surface is invalid """ def __init__(self, target, msg="None"): msg = 'Target device surface invalid ("{}") . Detail message: "{}"'.format(target, msg) super(InvalidSurfaceException, self).__init__(msg)
class InvalidSurfaceException(Exception): ''' Raised when the device surface is invalid ''' def __init__(self, target, msg="None"): pass
2
1
3
0
3
0
1
0.75
1
1
0
0
1
0
1
11
8
1
4
2
2
3
4
2
2
1
3
0
1
3,518
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/Selector.py
poco.sdk.Selector.Selector
class Selector(ISelector): """ This class implements the standard Selector interface that uses DFS algorithm to travers through tree-like hierarchy structure. It supports flexible query expressions such as parental relationship, attribute predicate, etc. Any combinations of expressions mentioned above are also allowed as the query conditions. The query expression can be defined as follows:: expr := (op0, (expr0, expr1)) expr := ('index', (expr, :obj:`int`)) expr := <other query condition> See implementation of Matcher. - ``op0`` can be one of the following ('>', '/', '-'), each operator stands for as follows:: '>': offsprings, select all offsprings matched expr1 from all roots matched expr0. '/': children, select all children matched expr1 from all roots matched expr0. '-': siblings, select all siblings matched expr1 from all roots matched expr0. '^': parent, select the parent of 1st UI element matched expr0. expr1 is always None. - ``'index'``: select specific n-th UI element from the previous results - ``others``: passes the expression to matcher Args: dumper (any implementation of :py:class:`IDumper <poco.sdk.AbstractDumper.IDumper>`): dumper for the selector matcher (any implementation of :py:class:`IMatcher <poco.sdk.DefaultMatcher.IMatcher>`): :py:class:`DefaultMatcher <poco.sdk.DefaultMatcher.DefaultMatcher>` instance by default. """ def __init__(self, dumper, matcher=None): self.dumper = dumper self.matcher = matcher or DefaultMatcher() def getRoot(self): """ Get a default root node. Returns: default root node from the dumper. """ return self.dumper.getRoot() def select(self, cond, multiple=False): """ See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``. """ return self.selectImpl(cond, multiple, self.getRoot(), 9999, True, True) def selectImpl(self, cond, multiple, root, maxDepth, onlyVisibleNode, includeRoot): """ Selector internal implementation. TODO: add later. .. note:: This doc shows only the outline of the algorithm. Do not call this method in your code as this is an internal method. Args: cond (:obj:`tuple`): query expression multiple (:obj:`bool`): whether or not to select multiple nodes. If true, all nodes that matches the given condition will return, otherwise, only the first node matches will. root (inherited from :py:class:`AbstractNode <poco.sdk.AbstractNode>`): start traversing from the given root node maxDepth (:obj:`bool`): max traversing depth onlyVisibleNode (:obj:`bool`): If True, skip those node which visibility (the value of visible attribute) is False. includeRoot (:obj:`bool`): whether not not to include the root node if its child(ren) match(es) the node Returns: :obj:`list` <inherited from :py:class:`AbstractNode <poco.sdk.AbstractNode>`>: The same as :py:meth:`select <poco.sdk.Selector.ISelector.select>`. """ result = [] if not root: return result op, args = cond if op in ('>', '/'): # children or offsprings # 父子直系相对节点选择 parents = [root] for index, arg in enumerate(args): midResult = [] for parent in parents: if op == '/' and index != 0: _maxDepth = 1 else: _maxDepth = maxDepth # 按路径进行遍历一定要multiple为true才不会漏掉 _res = self.selectImpl(arg, True, parent, _maxDepth, onlyVisibleNode, False) [midResult.append(r) for r in _res if r not in midResult] parents = midResult result = parents elif op == '-': # sibling # 兄弟节点选择 query1, query2 = args result1 = self.selectImpl(query1, multiple, root, maxDepth, onlyVisibleNode, includeRoot) for n in result1: sibling_result = self.selectImpl(query2, multiple, n.getParent(), 1, onlyVisibleNode, includeRoot) [result.append(r) for r in sibling_result if r not in result] elif op == 'index': cond, i = args try: # set multiple=True, self.selectImpl will return a list result = [self.selectImpl(cond, True, root, maxDepth, onlyVisibleNode, includeRoot)[i]] except IndexError: raise NoSuchTargetException( u'Query results index out of range. Index={} condition "{}" from root "{}".'.format(i, cond, root)) elif op == '^': # parent # only select parent of the first matched UI element query1, _ = args result1 = self.selectImpl(query1, False, root, maxDepth, onlyVisibleNode, includeRoot) if result1: parent_node = result1[0].getParent() if parent_node is not None: result = [parent_node] else: self._selectTraverse(cond, root, result, multiple, maxDepth, onlyVisibleNode, includeRoot) return result def _selectTraverse(self, cond, node, outResult, multiple, maxDepth, onlyVisibleNode, includeRoot): # exclude invisible UI element if onlyVisibleNode specified # 剪掉不可见节点branch if onlyVisibleNode and not node.getAttr('visible'): return False if self.matcher.match(cond, node): # To select node from parent or ancestor, the parent or ancestor are excluded. # 父子/祖先后代节点选择时,默认是不包含父节点/祖先节点的 # 在下面的children循环中则需要包含,因为每个child在_selectTraverse中就当做是root if includeRoot: if node not in outResult: outResult.append(node) if not multiple: return True # When maximum search depth reached, children of this node is still require to travers. # 最大搜索深度耗尽并不表示遍历结束,其余child节点仍需遍历 if maxDepth == 0: return False maxDepth -= 1 for child in node.getChildren(): finished = self._selectTraverse(cond, child, outResult, multiple, maxDepth, onlyVisibleNode, True) if finished: return True return False
class Selector(ISelector): ''' This class implements the standard Selector interface that uses DFS algorithm to travers through tree-like hierarchy structure. It supports flexible query expressions such as parental relationship, attribute predicate, etc. Any combinations of expressions mentioned above are also allowed as the query conditions. The query expression can be defined as follows:: expr := (op0, (expr0, expr1)) expr := ('index', (expr, :obj:`int`)) expr := <other query condition> See implementation of Matcher. - ``op0`` can be one of the following ('>', '/', '-'), each operator stands for as follows:: '>': offsprings, select all offsprings matched expr1 from all roots matched expr0. '/': children, select all children matched expr1 from all roots matched expr0. '-': siblings, select all siblings matched expr1 from all roots matched expr0. '^': parent, select the parent of 1st UI element matched expr0. expr1 is always None. - ``'index'``: select specific n-th UI element from the previous results - ``others``: passes the expression to matcher Args: dumper (any implementation of :py:class:`IDumper <poco.sdk.AbstractDumper.IDumper>`): dumper for the selector matcher (any implementation of :py:class:`IMatcher <poco.sdk.DefaultMatcher.IMatcher>`): :py:class:`DefaultMatcher <poco.sdk.DefaultMatcher.DefaultMatcher>` instance by default. ''' def __init__(self, dumper, matcher=None): pass def getRoot(self): ''' Get a default root node. Returns: default root node from the dumper. ''' pass def select(self, cond, multiple=False): ''' See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``. ''' pass def selectImpl(self, cond, multiple, root, maxDepth, onlyVisibleNode, includeRoot): ''' Selector internal implementation. TODO: add later. .. note:: This doc shows only the outline of the algorithm. Do not call this method in your code as this is an internal method. Args: cond (:obj:`tuple`): query expression multiple (:obj:`bool`): whether or not to select multiple nodes. If true, all nodes that matches the given condition will return, otherwise, only the first node matches will. root (inherited from :py:class:`AbstractNode <poco.sdk.AbstractNode>`): start traversing from the given root node maxDepth (:obj:`bool`): max traversing depth onlyVisibleNode (:obj:`bool`): If True, skip those node which visibility (the value of visible attribute) is False. includeRoot (:obj:`bool`): whether not not to include the root node if its child(ren) match(es) the node Returns: :obj:`list` <inherited from :py:class:`AbstractNode <poco.sdk.AbstractNode>`>: The same as :py:meth:`select <poco.sdk.Selector.ISelector.select>`. ''' pass def _selectTraverse(self, cond, node, outResult, multiple, maxDepth, onlyVisibleNode, includeRoot): pass
6
4
24
3
13
8
5
0.94
1
4
2
0
5
2
5
6
153
25
66
25
60
62
60
25
54
13
2
4
25
3,519
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/DefaultMatcher.py
poco.sdk.DefaultMatcher.RegexpComparator
class RegexpComparator(object): """ Compare two objects using regular expression. Available only when the original value is string type. It always returns False if the original value or given pattern are not :obj:`str` type. """ def compare(self, origin, pattern): """ Args: origin (:obj:`str`): original string pattern (:obj:`str`): Regexp pattern string Returns: bool: True if matches otherwise False. """ if origin is None or pattern is None: return False return re.match(pattern, origin) is not None
class RegexpComparator(object): ''' Compare two objects using regular expression. Available only when the original value is string type. It always returns False if the original value or given pattern are not :obj:`str` type. ''' def compare(self, origin, pattern): ''' Args: origin (:obj:`str`): original string pattern (:obj:`str`): Regexp pattern string Returns: bool: True if matches otherwise False. ''' pass
2
2
13
2
4
7
2
2.2
1
0
0
0
1
0
1
1
19
3
5
2
3
11
5
2
3
2
1
1
2
3,520
AirtestProject/Poco
AirtestProject_Poco/poco/exceptions.py
poco.exceptions.PocoException
class PocoException(Exception): """ Base class for errors and exceptions of Poco. It is Python3 compatible. """ def __init__(self, message=None): super(PocoException, self).__init__(message) self.message = message def __str__(self): if six.PY2: if isinstance(self.message, six.text_type): return self.message.encode("utf-8") else: return self.message else: if isinstance(self.message, bytes): return self.message.decode('utf-8') else: return self.message __repr__ = __str__
class PocoException(Exception): ''' Base class for errors and exceptions of Poco. It is Python3 compatible. ''' def __init__(self, message=None): pass def __str__(self): pass
3
1
7
0
7
0
3
0.19
1
2
0
4
2
1
2
12
22
3
16
5
13
3
13
5
10
4
3
2
5
3,521
AirtestProject/Poco
AirtestProject_Poco/poco/exceptions.py
poco.exceptions.InvalidOperationException
class InvalidOperationException(PocoException): """ Raised when the operation performing on target device is foreseen, e.g. instruction to click outside the screen is definitely meaningless, then the ``InvalidOperationException`` is raised. """ pass
class InvalidOperationException(PocoException): ''' Raised when the operation performing on target device is foreseen, e.g. instruction to click outside the screen is definitely meaningless, then the ``InvalidOperationException`` is raised. '''
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
12
7
1
2
1
1
4
2
1
1
0
4
0
0
3,522
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/windows/windowsui_poco.py
poco.drivers.windows.windowsui_poco.WindowsPoco
class WindowsPoco(StdPoco): """ Poco WindowsUI implementation. Args: selector (:py:obj:`dict`): find window by a selector, optional parameters: ``title``, ``handle``, ``title_re`` title: find windows by title handle: find windows by handle title_re: find windows by regular expression of title addr (:py:obj:`tuple`): where the WindowsUI running on, (localhost,15004) by default options: see :py:class:`poco.pocofw.Poco` Examples: If your programme is running, you could initialize poco instance by using following snippet:: from poco.drivers.windows import WindowsPoco # poco = WindowsPoco({'title':'xxx'}) # poco = WindowsPoco({'handle':123456}) # poco = WindowsPoco({'title_re':'[a-z][a-z][a-z]'}) """ def __init__(self, selector=None, addr=DEFAULT_ADDR, **options): if 'action_interval' not in options: options['action_interval'] = 0.1 if addr[0] == "localhost" or addr[0] == "127.0.0.1": from poco.drivers.windows.sdk.WindowsUI import PocoSDKWindows self.sdk = PocoSDKWindows(addr) self.SDKProcess = threading.Thread(target=self.sdk.run) # 创建线程 self.SDKProcess.setDaemon(True) self.SDKProcess.start() dev = VirtualDevice(addr[0]) super(WindowsPoco, self).__init__(addr[1], dev, False, **options) self.selector = selector self.connect_window(self.selector) @sync_wrapper def connect_window(self, selector): return self.agent.rpc.call("ConnectWindow", selector) @sync_wrapper def set_foreground(self): return self.agent.rpc.call("SetForeground") def scroll(self, direction='vertical', percent=1, duration=2.0): # 重写Win下的Scroll函数,percent代表滑动滚轮多少次,正数为向上滑,负数为向下滑,direction无用,只能上下滚 if direction not in ('vertical', 'horizontal'): raise ValueError('Argument `direction` should be one of "vertical" or "horizontal". Got {}'.format(repr(direction))) if direction is 'horizontal': raise InvalidOperationException("Windows does not support horizontal scrolling currently") return self.agent.input.scroll(direction, percent, duration) def rclick(self, pos): return self.agent.input.rclick(pos[0], pos[1]) def double_click(self, pos): return self.agent.input.double_click(pos[0], pos[1]) def keyevent(self, keyname): return self.agent.input.keyevent(keyname)
class WindowsPoco(StdPoco): ''' Poco WindowsUI implementation. Args: selector (:py:obj:`dict`): find window by a selector, optional parameters: ``title``, ``handle``, ``title_re`` title: find windows by title handle: find windows by handle title_re: find windows by regular expression of title addr (:py:obj:`tuple`): where the WindowsUI running on, (localhost,15004) by default options: see :py:class:`poco.pocofw.Poco` Examples: If your programme is running, you could initialize poco instance by using following snippet:: from poco.drivers.windows import WindowsPoco # poco = WindowsPoco({'title':'xxx'}) # poco = WindowsPoco({'handle':123456}) # poco = WindowsPoco({'title_re':'[a-z][a-z][a-z]'}) ''' def __init__(self, selector=None, addr=DEFAULT_ADDR, **options): pass @sync_wrapper def connect_window(self, selector): pass @sync_wrapper def set_foreground(self): pass def scroll(self, direction='vertical', percent=1, duration=2.0): pass def rclick(self, pos): pass def double_click(self, pos): pass def keyevent(self, keyname): pass
10
1
5
1
4
0
2
0.56
1
6
3
0
7
3
7
38
66
17
32
15
21
18
30
13
21
3
4
1
11
3,523
AirtestProject/Poco
AirtestProject_Poco/poco/exceptions.py
poco.exceptions.PocoTargetTimeout
class PocoTargetTimeout(PocoException): """ Raised when the timeout expired while waiting for some condition to be fulfilled, e.g. waiting for the specific UI element but it has not appeared on the screen. """ def __init__(self, action, poco_obj_proxy): super(PocoTargetTimeout, self).__init__() self.message = 'Waiting timeout for {} of "{}"'.format(action, to_text(repr(poco_obj_proxy)))
class PocoTargetTimeout(PocoException): ''' Raised when the timeout expired while waiting for some condition to be fulfilled, e.g. waiting for the specific UI element but it has not appeared on the screen. ''' def __init__(self, action, poco_obj_proxy): pass
2
1
3
0
3
0
1
1
1
1
0
0
1
1
1
13
9
1
4
3
2
4
4
3
2
1
4
0
1
3,524
AirtestProject/Poco
AirtestProject_Poco/poco/utils/regulator.py
poco.utils.regulator.PIDController
class PIDController(ControllerBase): def __init__(self, period, Kp=1, Ki=0, Kd=0, ValueType=float): super(PIDController, self).__init__(period, ValueType) self.Kp = Kp self.Ki = Ki self.Kd = Kd self.sum_error = ValueType(0) def delta_closed_loop_gain(self, feedback): self.current_value = feedback error = self.target_value - self.current_value d_error = error - self.error_1 d2_error = error - 2 * self.error_1 + self.error_2 delta_output = self.Kp * d_error + self.Ki * error + self.Kd * d2_error self.error_2 = self.error_1 self.error_1 = error return delta_output def closed_loop_gain(self, feedback): self.current_value = feedback error = self.target_value - self.current_value self.sum_error += error d_error = error - self.error_1 output = self.Kp * error + self.Ki * self.sum_error + self.Kd * d_error self.error_2 = self.error_1 self.error_1 = error return output
class PIDController(ControllerBase): def __init__(self, period, Kp=1, Ki=0, Kd=0, ValueType=float): pass def delta_closed_loop_gain(self, feedback): pass def closed_loop_gain(self, feedback): pass
4
0
9
1
8
0
1
0
1
2
0
0
3
7
3
9
29
4
25
18
21
0
25
18
21
1
2
0
3
3,525
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/backend/django.py
poco.utils.simplerpc.jsonrpc.backend.django.JSONRPCAPI
class JSONRPCAPI(object): def __init__(self, dispatcher=None): self.dispatcher = dispatcher if dispatcher is not None \ else Dispatcher() @property def urls(self): urls = [ url(r'^$', self.jsonrpc), url(r'map$', self.jsonrpc_map), ] return urls @csrf_exempt def jsonrpc(self, request): """ JSON-RPC 2.0 handler.""" if request.method != "POST": return HttpResponseNotAllowed(["POST"]) request_str = request.body.decode('utf8') try: jsonrpc_request = JSONRPCRequest.from_json(request_str) except (TypeError, ValueError, JSONRPCInvalidRequestException): response = JSONRPCResponseManager.handle( request_str, self.dispatcher) else: jsonrpc_request.params = jsonrpc_request.params or {} jsonrpc_request_params = copy.copy(jsonrpc_request.params) if isinstance(jsonrpc_request.params, dict): jsonrpc_request.params.update(request=request) t1 = time.time() response = JSONRPCResponseManager.handle_request( jsonrpc_request, self.dispatcher) t2 = time.time() logger.info('{0}({1}) {2:.2f} sec'.format( jsonrpc_request.method, jsonrpc_request_params, t2 - t1)) if response: def serialize(s): return json.dumps(s, cls=DatetimeDecimalEncoder) response.serialize = serialize response = response.json return HttpResponse(response, content_type="application/json") def jsonrpc_map(self, request): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return HttpResponse(result)
class JSONRPCAPI(object): def __init__(self, dispatcher=None): pass @property def urls(self): pass @csrf_exempt def jsonrpc(self, request): ''' JSON-RPC 2.0 handler.''' pass def serialize(s): pass def jsonrpc_map(self, request): ''' Map of json-rpc available calls. :return str: ''' pass
8
2
11
2
9
1
2
0.09
1
8
5
0
4
1
4
4
59
11
44
17
36
4
32
15
26
5
1
2
10
3,526
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/backend/flask.py
poco.utils.simplerpc.jsonrpc.backend.flask.JSONRPCAPI
class JSONRPCAPI(object): def __init__(self, dispatcher=None, check_content_type=True): """ :param dispatcher: methods dispatcher :param check_content_type: if True - content-type must be "application/json" :return: """ self.dispatcher = dispatcher if dispatcher is not None \ else Dispatcher() self.check_content_type = check_content_type def as_blueprint(self, name=None): blueprint = Blueprint(name if name else str(uuid4()), __name__) blueprint.add_url_rule( '/', view_func=self.jsonrpc, methods=['POST']) blueprint.add_url_rule( '/map', view_func=self.jsonrpc_map, methods=['GET']) return blueprint def as_view(self): return self.jsonrpc def jsonrpc(self): request_str = self._get_request_str() try: jsonrpc_request = JSONRPCRequest.from_json(request_str) except (TypeError, ValueError, JSONRPCInvalidRequestException): response = JSONRPCResponseManager.handle( request_str, self.dispatcher) else: jsonrpc_request.params = jsonrpc_request.params or {} jsonrpc_request_params = copy.copy(jsonrpc_request.params) t1 = time.time() response = JSONRPCResponseManager.handle_request( jsonrpc_request, self.dispatcher) t2 = time.time() logger.info('{0}({1}) {2:.2f} sec'.format( jsonrpc_request.method, jsonrpc_request_params, t2 - t1)) if response: response.serialize = self._serialize response = response.json return Response(response, content_type="application/json") def jsonrpc_map(self): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return Response(result) def _get_request_str(self): if self.check_content_type or request.data: return request.data return list(request.form.keys())[0] @staticmethod def _serialize(s): return json.dumps(s, cls=DatetimeDecimalEncoder)
class JSONRPCAPI(object): def __init__(self, dispatcher=None, check_content_type=True): ''' :param dispatcher: methods dispatcher :param check_content_type: if True - content-type must be "application/json" :return: ''' pass def as_blueprint(self, name=None): pass def as_view(self): pass def jsonrpc(self): pass def jsonrpc_map(self): ''' Map of json-rpc available calls. :return str: ''' pass def _get_request_str(self): pass @staticmethod def _serialize(s): pass
9
2
9
1
6
1
2
0.19
1
9
5
0
6
2
7
7
68
12
47
19
38
9
37
18
29
3
1
1
12
3,527
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/base.py
poco.utils.simplerpc.jsonrpc.base.JSONRPCBaseResponse
class JSONRPCBaseResponse(JSONSerializable): """ Base class for JSON-RPC 1.0 and JSON-RPC 2.0 responses.""" def __init__(self, **kwargs): self.data = dict() try: self.result = kwargs['result'] except KeyError: pass try: self.error = kwargs['error'] except KeyError: pass self._id = kwargs.get('_id') if 'result' not in kwargs and 'error' not in kwargs: raise ValueError("Either result or error should be used") @property def data(self): return self._data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def json(self): return self.serialize(self.data)
class JSONRPCBaseResponse(JSONSerializable): ''' Base class for JSON-RPC 1.0 and JSON-RPC 2.0 responses.''' def __init__(self, **kwargs): pass @property def data(self): pass @data.setter def data(self): pass @property def json(self): pass
8
1
7
1
5
0
2
0.04
1
3
0
2
4
4
4
6
36
10
25
12
17
1
22
9
17
4
2
1
8
3,528
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/dispatcher.py
poco.utils.simplerpc.jsonrpc.dispatcher.Dispatcher
class Dispatcher(MutableMapping): """ Dictionary like object which maps method_name to method.""" def __init__(self, prototype=None): """ Build method dispatcher. Parameters ---------- prototype : object or dict, optional Initial method mapping. Examples -------- Init object with method dictionary. >>> Dispatcher({"sum": lambda a, b: a + b}) None """ self.method_map = dict() if prototype is not None: self.build_method_map(prototype) def __getitem__(self, key): return self.method_map[key] def __setitem__(self, key, value): self.method_map[key] = value def __delitem__(self, key): del self.method_map[key] def __len__(self): return len(self.method_map) def __iter__(self): return iter(self.method_map) def __repr__(self): return repr(self.method_map) def add_class(self, cls): prefix = cls.__name__.lower() + '.' self.build_method_map(cls(), prefix) def add_object(self, obj): prefix = obj.__class__.__name__.lower() + '.' self.build_method_map(obj, prefix) def add_dict(self, dict, prefix=''): if prefix: prefix += '.' self.build_method_map(dict, prefix) def add_method(self, f, name=None): """ Add a method to the dispatcher. Parameters ---------- f : callable Callable to be added. name : str, optional Name to register (the default is function **f** name) Notes ----- When used as a decorator keeps callable object unmodified. Examples -------- Use as method >>> d = Dispatcher() >>> d.add_method(lambda a, b: a + b, name="sum") <function __main__.<lambda>> Or use as decorator >>> d = Dispatcher() >>> @d.add_method def mymethod(*args, **kwargs): print(args, kwargs) """ self.method_map[name or f.__name__] = f return f def build_method_map(self, prototype, prefix=''): """ Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispatcher. If given prototype is an object then all public methods will be used. prefix: string, optional Prefix of methods """ if not isinstance(prototype, dict): prototype = dict((method, getattr(prototype, method)) for method in dir(prototype) if not method.startswith('_')) for attr, method in prototype.items(): if callable(method): self[prefix + attr] = method
class Dispatcher(MutableMapping): ''' Dictionary like object which maps method_name to method.''' def __init__(self, prototype=None): ''' Build method dispatcher. Parameters ---------- prototype : object or dict, optional Initial method mapping. Examples -------- Init object with method dictionary. >>> Dispatcher({"sum": lambda a, b: a + b}) None ''' pass def __getitem__(self, key): pass def __setitem__(self, key, value): pass def __delitem__(self, key): pass def __len__(self): pass def __iter__(self): pass def __repr__(self): pass def add_class(self, cls): pass def add_object(self, obj): pass def add_dict(self, dict, prefix=''): pass def add_method(self, f, name=None): ''' Add a method to the dispatcher. Parameters ---------- f : callable Callable to be added. name : str, optional Name to register (the default is function **f** name) Notes ----- When used as a decorator keeps callable object unmodified. Examples -------- Use as method >>> d = Dispatcher() >>> d.add_method(lambda a, b: a + b, name="sum") <function __main__.<lambda>> Or use as decorator >>> d = Dispatcher() >>> @d.add_method def mymethod(*args, **kwargs): print(args, kwargs) ''' pass def build_method_map(self, prototype, prefix=''): ''' Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispatcher. If given prototype is an object then all public methods will be used. prefix: string, optional Prefix of methods ''' pass
13
4
8
1
3
4
1
1.21
1
1
0
0
12
1
12
53
114
30
38
17
25
46
36
17
23
4
7
2
17
3,529
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/jsonrpc1.py
poco.utils.simplerpc.jsonrpc.jsonrpc1.JSONRPC10Request
class JSONRPC10Request(JSONRPCBaseRequest): """ JSON-RPC 1.0 Request. A remote method is invoked by sending a request to a remote service. The request is a single object serialized using json. :param str method: The name of the method to be invoked. :param list params: An Array of objects to pass as arguments to the method. :param _id: This can be of any type. It is used to match the response with the request that it is replying to. :param bool is_notification: whether request notification or not. """ JSONRPC_VERSION = "1.0" REQUIRED_FIELDS = set(["method", "params", "id"]) POSSIBLE_FIELDS = set(["method", "params", "id"]) @property def data(self): data = dict((k, v) for k, v in self._data.items()) data["id"] = None if self.is_notification else data["id"] return data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def method(self): return self._data.get("method") @method.setter def method(self, value): if not isinstance(value, six.string_types): raise ValueError("Method should be string") self._data["method"] = str(value) @property def params(self): return self._data.get("params") @params.setter def params(self, value): if not isinstance(value, (list, tuple)): raise ValueError("Incorrect params {0}".format(value)) self._data["params"] = list(value) @property def _id(self): return self._data.get("id") @_id.setter def _id(self, value): self._data["id"] = value @property def is_notification(self): return self._data["id"] is None or self._is_notification @is_notification.setter def is_notification(self, value): if value is None: value = self._id is None if self._id is None and not value: raise ValueError("Can not set attribute is_notification. " + "Request id should not be None") self._is_notification = value @classmethod def from_json(cls, json_str): data = cls.deserialize(json_str) if not isinstance(data, dict): raise ValueError("data should be dict") if cls.REQUIRED_FIELDS <= set(data.keys()) <= cls.POSSIBLE_FIELDS: return cls( method=data["method"], params=data["params"], _id=data["id"] ) else: extra = set(data.keys()) - cls.POSSIBLE_FIELDS missed = cls.REQUIRED_FIELDS - set(data.keys()) msg = "Invalid request. Extra fields: {0}, Missed fields: {1}" raise JSONRPCInvalidRequestException(msg.format(extra, missed))
class JSONRPC10Request(JSONRPCBaseRequest): ''' JSON-RPC 1.0 Request. A remote method is invoked by sending a request to a remote service. The request is a single object serialized using json. :param str method: The name of the method to be invoked. :param list params: An Array of objects to pass as arguments to the method. :param _id: This can be of any type. It is used to match the response with the request that it is replying to. :param bool is_notification: whether request notification or not. ''' @property def data(self): pass @data.setter def data(self): pass @property def method(self): pass @method.setter def method(self): pass @property def params(self): pass @params.setter def params(self): pass @property def _id(self): pass @_id.setter def _id(self): pass @property def is_notification(self): pass @is_notification.setter def is_notification(self): pass @classmethod def from_json(cls, json_str): pass
23
1
5
1
4
0
2
0.15
1
7
1
0
10
2
11
19
93
23
61
33
38
9
46
22
34
3
3
1
19
3,530
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/manager.py
poco.utils.simplerpc.jsonrpc.manager.JSONRPCResponseManager
class JSONRPCResponseManager(object): """ JSON-RPC response manager. Method brings syntactic sugar into library. Given dispatcher it handles request (both single and batch) and handles errors. Request could be handled in parallel, it is server responsibility. :param str request_str: json string. Will be converted into JSONRPC20Request, JSONRPC20BatchRequest or JSONRPC10Request :param dict dispather: dict<function_name:function>. """ RESPONSE_CLASS_MAP = { "1.0": JSONRPC10Response, "2.0": JSONRPC20Response, } @classmethod def handle(cls, request_str, dispatcher): if isinstance(request_str, bytes): request_str = request_str.decode("utf-8") try: json.loads(request_str) except (TypeError, ValueError): return JSONRPC20Response(error=JSONRPCParseError()._data) try: request = JSONRPCRequest.from_json(request_str) except JSONRPCInvalidRequestException: return JSONRPC20Response(error=JSONRPCInvalidRequest()._data) return cls.handle_request(request, dispatcher) @classmethod def handle_request(cls, request, dispatcher): """ Handle request data. At this moment request has correct jsonrpc format. :param dict request: data parsed from request_str. :param jsonrpc.dispatcher.Dispatcher dispatcher: .. versionadded: 1.8.0 """ rs = request if isinstance(request, JSONRPC20BatchRequest) \ else [request] responses = [r for r in cls._get_responses(rs, dispatcher) if r is not None] # notifications if not responses: return if isinstance(request, JSONRPC20BatchRequest): return JSONRPC20BatchResponse(*responses) else: return responses[0] @classmethod def _get_responses(cls, requests, dispatcher): """ Response to each single JSON-RPC Request. :return iterator(JSONRPC20Response): .. versionadded: 1.9.0 TypeError inside the function is distinguished from Invalid Params. """ for request in requests: def response(**kwargs): return cls.RESPONSE_CLASS_MAP[request.JSONRPC_VERSION]( _id=request._id, **kwargs) try: method = dispatcher[request.method] except KeyError: output = response(error=JSONRPCMethodNotFound()._data) else: try: result = method(*request.args, **request.kwargs) except JSONRPCDispatchException as e: output = response(error=e.error._data) except Exception as e: data = { "type": e.__class__.__name__, "args": e.args, "message": str(e), } if isinstance(e, TypeError) and is_invalid_params( method, *request.args, **request.kwargs): output = response( error=JSONRPCInvalidParams(data=data)._data) else: # logger.exception("API Exception: {0}".format(data)) print("API Exception: {0}".format(data)) output = response( error=JSONRPCServerError(data=data)._data) else: output = response(result=result) finally: if not request.is_notification: yield output
class JSONRPCResponseManager(object): ''' JSON-RPC response manager. Method brings syntactic sugar into library. Given dispatcher it handles request (both single and batch) and handles errors. Request could be handled in parallel, it is server responsibility. :param str request_str: json string. Will be converted into JSONRPC20Request, JSONRPC20BatchRequest or JSONRPC10Request :param dict dispather: dict<function_name:function>. ''' @classmethod def handle(cls, request_str, dispatcher): pass @classmethod def handle_request(cls, request, dispatcher): ''' Handle request data. At this moment request has correct jsonrpc format. :param dict request: data parsed from request_str. :param jsonrpc.dispatcher.Dispatcher dispatcher: .. versionadded: 1.8.0 ''' pass @classmethod def _get_responses(cls, requests, dispatcher): ''' Response to each single JSON-RPC Request. :return iterator(JSONRPC20Response): .. versionadded: 1.9.0 TypeError inside the function is distinguished from Invalid Params. ''' pass def response(**kwargs): pass
8
3
21
3
15
3
4
0.33
1
17
11
0
0
0
3
3
107
22
64
18
56
21
45
14
40
7
1
4
16
3,531
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_dispatcher.py
poco.utils.simplerpc.jsonrpc.tests.test_dispatcher.TestDispatcher
class TestDispatcher(unittest.TestCase): """ Test Dispatcher functionality.""" def test_getter(self): d = Dispatcher() with self.assertRaises(KeyError): d["method"] d["add"] = lambda *args: sum(args) self.assertEqual(d["add"](1, 1), 2) def test_in(self): d = Dispatcher() d["method"] = lambda: "" self.assertIn("method", d) def test_add_method(self): d = Dispatcher() @d.add_method def add(x, y): return x + y self.assertIn("add", d) self.assertEqual(d["add"](1, 1), 2) def test_add_class(self): d = Dispatcher() d.add_class(Math) self.assertIn("math.sum", d) self.assertIn("math.diff", d) self.assertEqual(d["math.sum"](3, 8), 11) self.assertEqual(d["math.diff"](6, 9), -3) def test_add_object(self): d = Dispatcher() d.add_object(Math()) self.assertIn("math.sum", d) self.assertIn("math.diff", d) self.assertEqual(d["math.sum"](5, 2), 7) self.assertEqual(d["math.diff"](15, 9), 6) def test_add_dict(self): d = Dispatcher() d.add_dict({"sum": lambda *args: sum(args)}, "util") self.assertIn("util.sum", d) self.assertEqual(d["util.sum"](13, -2), 11) def test_add_method_keep_function_definitions(self): d = Dispatcher() @d.add_method def one(x): return x self.assertIsNotNone(one) def test_del_method(self): d = Dispatcher() d["method"] = lambda: "" self.assertIn("method", d) del d["method"] self.assertNotIn("method", d) def test_to_dict(self): d = Dispatcher() func = lambda: "" d["method"] = func self.assertEqual(dict(d), {"method": func}) def test_init_from_object_instance(self): class Dummy(): def one(self): pass def two(self): pass dummy = Dummy() d = Dispatcher(dummy) self.assertIn("one", d) self.assertIn("two", d) self.assertNotIn("__class__", d) def test_init_from_dictionary(self): dummy = { 'one': lambda x: x, 'two': lambda x: x, } d = Dispatcher(dummy) self.assertIn("one", d) self.assertIn("two", d) def test_dispatcher_representation(self): d = Dispatcher() self.assertEqual('{}', repr(d))
class TestDispatcher(unittest.TestCase): ''' Test Dispatcher functionality.''' def test_getter(self): pass def test_in(self): pass def test_add_method(self): pass @d.add_method def add(x, y): pass def test_add_class(self): pass def test_add_object(self): pass def test_add_dict(self): pass def test_add_method_keep_function_definitions(self): pass @d.add_method def one(x): pass def test_del_method(self): pass def test_to_dict(self): pass def test_init_from_object_instance(self): pass class Dummy(): def one(x): pass def two(self): pass def test_init_from_dictionary(self): pass def test_dispatcher_representation(self): pass
20
1
7
1
5
0
1
0.01
1
5
3
0
12
0
12
84
111
34
76
35
56
1
71
33
53
1
2
1
16
3,532
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_examples20.py
poco.utils.simplerpc.jsonrpc.tests.test_examples20.TestJSONRPCExamples
class TestJSONRPCExamples(unittest.TestCase): def setUp(self): self.dispatcher = { "subtract": lambda a, b: a - b, } def test_rpc_call_with_positional_parameters(self): req = '{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}' # noqa response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": 19, "id": 1}' )) req = '{"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}' # noqa response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": -19, "id": 2}' )) def test_rpc_call_with_named_parameters(self): def subtract(minuend=None, subtrahend=None): return minuend - subtrahend dispatcher = { "subtract": subtract, "sum": lambda *args: sum(args), "get_data": lambda: ["hello", 5], } req = '{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}' # noqa response = JSONRPCResponseManager.handle(req, dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": 19, "id": 3}' )) req = '{"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}' # noqa response = JSONRPCResponseManager.handle(req, dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": 19, "id": 4}', )) def test_notification(self): req = '{"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertEqual(response, None) req = '{"jsonrpc": "2.0", "method": "foobar"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertEqual(response, None) def test_rpc_call_of_non_existent_method(self): req = '{"jsonrpc": "2.0", "method": "foobar", "id": "1"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}' # noqa )) def test_rpc_call_with_invalid_json(self): req = '{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}' # noqa )) def test_rpc_call_with_invalid_request_object(self): req = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa )) def test_rpc_call_batch_invalid_json(self): req = """[ {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method" ]""" response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}' # noqa )) def test_rpc_call_with_an_empty_array(self): req = '[]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa )) def test_rpc_call_with_rpc_call_with_an_invalid_batch_but_not_empty(self): req = '[1]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa )) def test_rpc_call_with_invalid_batch(self): req = '[1,2,3]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue( response, json.loads("""[ {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}, {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}, {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null} ]""") ) def test_rpc_call_batch(self): req = """[ {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"}, {"foo": "boo"}, {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"}, {"jsonrpc": "2.0", "method": "get_data", "id": "9"} ]""" response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue( response, json.loads("""[ {"jsonrpc": "2.0", "result": 7, "id": "1"}, {"jsonrpc": "2.0", "result": 19, "id": "2"}, {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}, {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "5"}, {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"} ]""") ) def test_rpc_call_batch_all_notifications(self): req = """[ {"jsonrpc": "2.0", "method": "notify_sum", "params": [1,2,4]}, {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]} ]""" response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertEqual(response, None)
class TestJSONRPCExamples(unittest.TestCase): def setUp(self): pass def test_rpc_call_with_positional_parameters(self): pass def test_rpc_call_with_named_parameters(self): pass def subtract(minuend=None, subtrahend=None): pass def test_notification(self): pass def test_rpc_call_of_non_existent_method(self): pass def test_rpc_call_with_invalid_json(self): pass def test_rpc_call_with_invalid_request_object(self): pass def test_rpc_call_batch_invalid_json(self): pass def test_rpc_call_with_an_empty_array(self): pass def test_rpc_call_with_rpc_call_with_an_invalid_batch_but_not_empty(self): pass def test_rpc_call_with_invalid_batch(self): pass def test_rpc_call_batch_invalid_json(self): pass def test_rpc_call_batch_all_notifications(self): pass
15
0
10
0
10
1
1
0.07
1
1
1
0
13
1
13
85
152
17
135
41
120
10
63
41
48
1
2
0
14
3,533
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_manager.py
poco.utils.simplerpc.jsonrpc.tests.test_manager.TestJSONRPCResponseManager
class TestJSONRPCResponseManager(unittest.TestCase): def setUp(self): def raise_(e): raise e self.long_time_method = MagicMock() self.dispatcher = { "add": sum, "multiply": lambda a, b: a * b, "list_len": len, "101_base": lambda **kwargs: int("101", **kwargs), "error": lambda: raise_(KeyError("error_explanation")), "type_error": lambda: raise_(TypeError("TypeError inside method")), "long_time_method": self.long_time_method, "dispatch_error": lambda x: raise_( JSONRPCDispatchException(code=4000, message="error", data={"param": 1})), } def test_dispatch_error(self): request = JSONRPC20Request("dispatch_error", ["test"], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "error") self.assertEqual(response.error["code"], 4000) self.assertEqual(response.error["data"], {"param": 1}) def test_returned_type_response(self): request = JSONRPC20Request("add", [[]], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) def test_returned_type_butch_response(self): request = JSONRPC20BatchRequest( JSONRPC20Request("add", [[]], _id=0)) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20BatchResponse)) def test_returned_type_response_rpc10(self): request = JSONRPC10Request("add", [[]], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC10Response)) def test_parse_error(self): req = '{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Parse error") self.assertEqual(response.error["code"], -32700) def test_invalid_request(self): req = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid Request") self.assertEqual(response.error["code"], -32600) def test_method_not_found(self): request = JSONRPC20Request("does_not_exist", [[]], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Method not found") self.assertEqual(response.error["code"], -32601) def test_invalid_params(self): request = JSONRPC20Request("add", {"a": 0}, _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) self.assertIn(response.error["data"]["message"], [ 'sum() takes no keyword arguments', "sum() got an unexpected keyword argument 'a'", ]) def test_invalid_params_custom_function(self): request = JSONRPC20Request("multiply", [0], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) request = JSONRPC20Request("multiply", [0, 1, 2], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) request = JSONRPC20Request("multiply", {"a": 1}, _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) request = JSONRPC20Request("multiply", {"a": 1, "b": 2, "c": 3}, _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) def test_server_error(self): request = JSONRPC20Request("error", _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Server error") self.assertEqual(response.error["code"], -32000) self.assertEqual(response.error["data"], { "type": "KeyError", "args": ('error_explanation',), "message": "'error_explanation'", }) def test_notification_calls_method(self): request = JSONRPC20Request("long_time_method", is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) self.long_time_method.assert_called_once_with() def test_notification_does_not_return_error_does_not_exist(self): request = JSONRPC20Request("does_not_exist", is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) def test_notification_does_not_return_error_invalid_params(self): request = JSONRPC20Request("add", {"a": 0}, is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) def test_notification_does_not_return_error(self): request = JSONRPC20Request("error", is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) def test_type_error_inside_method(self): request = JSONRPC20Request("type_error", _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Server error") self.assertEqual(response.error["code"], -32000) self.assertEqual(response.error["data"], { "type": "TypeError", "args": ('TypeError inside method',), "message": 'TypeError inside method', }) def test_invalid_params_before_dispatcher_error(self): request = JSONRPC20Request( "dispatch_error", ["invalid", "params"], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602)
class TestJSONRPCResponseManager(unittest.TestCase): def setUp(self): pass def raise_(e): pass def test_dispatch_error(self): pass def test_returned_type_response(self): pass def test_returned_type_butch_response(self): pass def test_returned_type_response_rpc10(self): pass def test_parse_error(self): pass def test_invalid_request(self): pass def test_method_not_found(self): pass def test_invalid_params(self): pass def test_invalid_params_custom_function(self): pass def test_server_error(self): pass def test_notification_calls_method(self): pass def test_notification_does_not_return_error_does_not_exist(self): pass def test_notification_does_not_return_error_invalid_params(self): pass def test_notification_does_not_return_error_does_not_exist(self): pass def test_type_error_inside_method(self): pass def test_invalid_params_before_dispatcher_error(self): pass
19
0
8
0
7
0
1
0
1
11
8
0
17
2
17
89
152
20
132
53
113
0
108
53
89
1
2
0
18
3,534
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/jsonrpc/tests/test_utils.py
poco.utils.simplerpc.jsonrpc.tests.test_utils.TestUtils
class TestUtils(unittest.TestCase): """ Test utils functions.""" def test_is_invalid_params_builtin(self): self.assertTrue(is_invalid_params(sum, 0, 0)) # NOTE: Function generates TypeError already # self.assertFalse(is_invalid_params(sum, [0, 0])) def test_is_invalid_params_args(self): self.assertTrue(is_invalid_params(lambda a, b: None, 0)) self.assertTrue(is_invalid_params(lambda a, b: None, 0, 1, 2)) def test_is_invalid_params_kwargs(self): self.assertTrue(is_invalid_params(lambda x: None, **{})) self.assertTrue(is_invalid_params(lambda x: None, **{"x": 0, "y": 1})) def test_invalid_params_correct(self): # self.assertFalse(is_invalid_params(lambda: None)) self.assertFalse(is_invalid_params(lambda a: None, 0)) self.assertFalse(is_invalid_params(lambda a, b=0: None, 0))
class TestUtils(unittest.TestCase): ''' Test utils functions.''' def test_is_invalid_params_builtin(self): pass def test_is_invalid_params_args(self): pass def test_is_invalid_params_kwargs(self): pass def test_invalid_params_correct(self): pass
5
1
3
0
3
0
1
0.33
1
0
0
0
4
0
4
76
21
5
12
5
7
4
12
5
7
1
2
0
4
3,535
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/rpcclient.py
poco.utils.simplerpc.rpcclient.RpcClient
class RpcClient(RpcAgent): INIT, CONNECTING, CONNECTED, CLOSED = 0, 1, 2, 3 """docstring for RpcClient""" def __init__(self, conn): super(RpcClient, self).__init__() self._status = self.INIT self.conn = conn self.conn.connect_cb = self.on_connect self.conn.close_cb = self.on_close def connect(self, timeout=10): self._status = self.CONNECTING self.conn.connect() self._wait_connected(timeout) def get_connection(self): return self.conn def wait_connected(self): warnings.warn(DeprecationWarning()) return self.connect() def _wait_connected(self, timeout): for i in range(timeout): if self._status == self.CONNECTED: return True elif self._status == self.CONNECTING: print("[rpc]waiting for connection...%s" % i) time.sleep(0.5) else: raise RpcConnectionError("Rpc Connection Closed") raise RpcConnectionError("Connecting Timeout") def close(self): self.conn.close() self._status = self.CLOSED def on_connect(self): print("[rpc]connected") if self._status == self.CONNECTING: self._status = self.CONNECTED def on_close(self): print("[rpc]closed") self._status = self.CLOSED def call(self, func, *args, **kwargs): msg, cb = self.format_request(func, *args, **kwargs) self.conn.send(msg) return cb def update(self): if self._status != self.CONNECTED: return data = self.conn.recv() if not data: return for msg in data: self.handle_message(msg, self.conn) @property def DEBUG(self): return simplerpc.DEBUG @DEBUG.setter def DEBUG(self, value): simplerpc.DEBUG = value
class RpcClient(RpcAgent): def __init__(self, conn): pass def connect(self, timeout=10): pass def get_connection(self): pass def wait_connected(self): pass def _wait_connected(self, timeout): pass def close(self): pass def on_connect(self): pass def on_close(self): pass def call(self, func, *args, **kwargs): pass def update(self): pass @property def DEBUG(self): pass @DEBUG.setter def DEBUG(self): pass
15
0
4
0
4
0
2
0.02
1
4
1
0
12
2
12
21
69
13
55
22
40
1
51
20
38
4
2
2
19
3,536
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/simplerpc.py
poco.utils.simplerpc.simplerpc.AsyncResponse
class AsyncResponse(object): def __init__(self): self.conn = None self.rid = None def setup(self, conn, rid): self.conn = conn self.rid = rid def result(self, result): ret = JSONRPC20Response(_id=self.rid, result=result) if DEBUG: print("-->", ret) self.conn.send(ret.json) def error(self, error): assert isinstance(error, Exception), "%s must be Exception" % error data = { "type": error.__class__.__name__, "args": error.args, "message": str(error), } ret = JSONRPC20Response( _id=self.rid, error=JSONRPCServerError(data=data)._data) if DEBUG: print("-->", ret) self.conn.send(ret.json)
class AsyncResponse(object): def __init__(self): pass def setup(self, conn, rid): pass def result(self, result): pass def error(self, error): pass
5
0
6
0
6
0
2
0
1
4
2
0
4
2
4
4
28
5
23
10
18
0
19
10
14
2
1
1
6
3,537
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/windows/sdk/WindowsUINode.py
poco.drivers.windows.sdk.WindowsUINode.WindowsUINode
class WindowsUINode(AbstractNode): def __init__(self, control, dumper): self.Control = control self.Children = [] self.dumper = dumper def getParent(self): return WindowsUINode(self.Control.GetParentControl(), self.dumper) def getChildren(self): if len(self.Children): # 防止多次获取children,提高性能 for node in self.Children: yield WindowsUINode(node, self.dumper) else: self.Children = self.Control.GetChildren() for node in self.Children: yield WindowsUINode(node, self.dumper) def getAttr(self, attrName): if attrName == 'name': strr = self.Control.Name if strr != "": return strr return self.Control.ControlTypeName.replace("Control", "") if attrName == 'originType': return self.Control.ControlTypeName if attrName == 'type': return self.Control.ControlTypeName.replace("Control", "") if attrName == 'pos': rect = self.Control.BoundingRectangle # 计算比例 pos1 = float(rect[0] + (rect[2] - rect[0]) / 2.0 - self.dumper.RootLeft) / float(self.dumper.RootWidth) pos2 = float(rect[1] + (rect[3] - rect[1]) / 2.0 - self.dumper.RootTop) / float(self.dumper.RootHeight) return [pos1, pos2] if attrName == 'size': rect = self.Control.BoundingRectangle pos1 = float(rect[2] - rect[0]) / float(self.dumper.RootWidth) pos2 = float(rect[3] - rect[1]) / float(self.dumper.RootHeight) return [pos1, pos2] if attrName == 'text': # 先判断控件是否有text属性 if ((isinstance(self.Control, UIAuto.ValuePattern) and self.Control.IsValuePatternAvailable())): return self.Control.CurrentValue() else: return None if attrName == '_instanceId': return self.Control.Handle return super(WindowsUINode, self).getAttr(attrName) def setAttr(self, attrName, val): if attrName != 'text': raise UnableToSetAttributeException(attrName, self) else: if ((isinstance(self.Control, UIAuto.ValuePattern) and self.Control.IsValuePatternAvailable())): self.Control.SetValue(val) return True else: raise UnableToSetAttributeException(attrName, self) def getAvailableAttributeNames(self): if ((isinstance(self.Control, UIAuto.ValuePattern) and self.Control.IsValuePatternAvailable())): return super(WindowsUINode, self).getAvailableAttributeNames() + ('text', '_instanceId', 'originType') else: return super(WindowsUINode, self).getAvailableAttributeNames() + ('_instanceId', 'originType')
class WindowsUINode(AbstractNode): def __init__(self, control, dumper): pass def getParent(self): pass def getChildren(self): pass def getAttr(self, attrName): pass def setAttr(self, attrName, val): pass def getAvailableAttributeNames(self): pass
7
0
11
1
9
1
4
0.05
1
3
1
0
6
3
6
12
73
14
57
15
50
3
52
15
45
10
2
2
21
3,538
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/simplerpc.py
poco.utils.simplerpc.simplerpc.Callback
class Callback(object): """Callback Proxy""" WAITING, RESULT, ERROR, CANCELED = 0, 1, 2, 3 def __init__(self, rid, agent=None): super(Callback, self).__init__() self.rid = rid self.agent = agent self.result_callback = None self.error_callback = None self.status = self.WAITING self.result = None self.error = None def on_result(self, func): if not callable(func): raise RuntimeError("%s should be callbale" % func) self.result_callback = func def on_error(self, func): if not callable(func): raise RuntimeError("%s should be callbale" % func) self.error_callback = func def rpc_result(self, data): self.result = data if callable(self.result_callback): # callback function, set result as function return value try: self.result_callback(data) except Exception: traceback.print_exc() self.status = self.RESULT def rpc_error(self, data): self.error = data if callable(self.error_callback): try: self.error_callback(data) except Exception: traceback.print_exc() self.status = self.ERROR def cancel(self): self.result_callback = None self.error_callback = None self.status = self.CANCELED def wait(self, timeout=None): start_time = time.time() while True: if not BACKEND_UPDATE: self.agent.update() if self.status == self.WAITING: time.sleep(0.005) if timeout and time.time() - start_time > timeout: raise RpcTimeoutError(self) else: break return self.result, self.error def __str__(self): conn = self.agent.get_connection() return '{} (rid={}) (connection="{}")'.format(repr(self), self.rid, conn)
class Callback(object): '''Callback Proxy''' def __init__(self, rid, agent=None): pass def on_result(self, func): pass def on_error(self, func): pass def rpc_result(self, data): pass def rpc_error(self, data): pass def cancel(self): pass def wait(self, timeout=None): pass def __str__(self): pass
9
1
7
0
7
0
2
0.04
1
4
1
0
8
7
8
8
65
9
54
19
45
2
53
19
44
5
1
3
18
3,539
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/simplerpc.py
poco.utils.simplerpc.simplerpc.RpcConnectionError
class RpcConnectionError(Exception): pass
class RpcConnectionError(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,540
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/simplerpc.py
poco.utils.simplerpc.simplerpc.RpcTimeoutError
class RpcTimeoutError(Exception): pass
class RpcTimeoutError(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,541
AirtestProject/Poco
AirtestProject_Poco/poco/freezeui/hierarchy.py
poco.freezeui.hierarchy.FrozenUIHierarchy
class FrozenUIHierarchy(HierarchyInterface): """ Locally implementation of hierarchy interface with a given dumper and all other behaviours by default. As all information can only be retrieve from a fixed UI hierarchy data created by dumper and all UI elements are immutable, this class is called frozen hierarchy. With the help of this class, only very few of the methods are required to implement. See :py:class:`AbstractNode <poco.sdk.AbstractNode>` or poco-sdk integration guide to get more details about this. This class makes it much easier to integrate poco-sdk and optimizes performance in some situations, but it is not sensitive enough to the changes of UI hierarchy in the app. For example, you should call ``select`` explicitly to re-crawl a new UI hierarchy when some UI elements changed on screen. Otherwise you are using attributes that are out of date. """ def __init__(self, dumper, attributor=None): super(FrozenUIHierarchy, self).__init__() self.dumper = dumper self.selector = Selector(self.dumper) self.attributor = attributor or Attributor() def dump(self): return self.dumper.dumpHierarchy() def getAttr(self, nodes, name): """ get node attribute """ return self.attributor.getAttr(nodes, name) def setAttr(self, nodes, name, value): """ set node attribute """ return self.attributor.setAttr(nodes, name, value) def select(self, query, multiple=False): """ select nodes by query """ return self.selector.select(query, multiple)
class FrozenUIHierarchy(HierarchyInterface): ''' Locally implementation of hierarchy interface with a given dumper and all other behaviours by default. As all information can only be retrieve from a fixed UI hierarchy data created by dumper and all UI elements are immutable, this class is called frozen hierarchy. With the help of this class, only very few of the methods are required to implement. See :py:class:`AbstractNode <poco.sdk.AbstractNode>` or poco-sdk integration guide to get more details about this. This class makes it much easier to integrate poco-sdk and optimizes performance in some situations, but it is not sensitive enough to the changes of UI hierarchy in the app. For example, you should call ``select`` explicitly to re-crawl a new UI hierarchy when some UI elements changed on screen. Otherwise you are using attributes that are out of date. ''' def __init__(self, dumper, attributor=None): pass def dump(self): pass def getAttr(self, nodes, name): ''' get node attribute ''' pass def setAttr(self, nodes, name, value): ''' set node attribute ''' pass def select(self, query, multiple=False): ''' select nodes by query ''' pass
6
4
5
1
3
2
1
1.43
1
3
2
0
5
3
5
9
43
9
14
9
8
20
14
9
8
1
2
0
5
3,542
AirtestProject/Poco
AirtestProject_Poco/poco/freezeui/hierarchy.py
poco.freezeui.hierarchy.Node
class Node(AbstractNode): def __init__(self, node): super(Node, self).__init__() self.node = node def setParent(self, p): self.node['__parent__'] = p def getParent(self): return self.node.get('__parent__') def getChildren(self): for child in self.node.get('children') or []: yield Node(child) def getAttr(self, attrName): return self.node['payload'].get(attrName) def setAttr(self, attrName, val): # cannot set any attributes on local nodes raise UnableToSetAttributeException(attrName, self.node) def getAvailableAttributeNames(self): return self.node['payload'].keys()
class Node(AbstractNode): def __init__(self, node): pass def setParent(self, p): pass def getParent(self): pass def getChildren(self): pass def getAttr(self, attrName): pass def setAttr(self, attrName, val): pass def getAvailableAttributeNames(self): pass
8
0
2
0
2
0
1
0.06
1
2
1
0
7
1
7
13
24
6
17
10
9
1
17
10
9
2
2
1
8
3,543
AirtestProject/Poco
AirtestProject_Poco/poco/gesture.py
poco.gesture.PendingGestureAction
class PendingGestureAction(object): def __init__(self, pocoobj, uiproxy_or_pos): super(PendingGestureAction, self).__init__() self.pocoobj = pocoobj self.track = MotionTrack() if isinstance(uiproxy_or_pos, (list, tuple)): self.track.start(uiproxy_or_pos) else: self.track.start(uiproxy_or_pos.get_position()) def hold(self, t): self.track.hold(t) return self def to(self, pos): if isinstance(pos, (list, tuple)): self.track.move(pos) else: uiobj = pos self.track.move(uiobj.get_position()) return self def up(self): self.pocoobj.apply_motion_tracks([self.track])
class PendingGestureAction(object): def __init__(self, pocoobj, uiproxy_or_pos): pass def hold(self, t): pass def to(self, pos): pass def up(self): pass
5
0
5
0
5
0
2
0
1
4
1
0
4
2
4
4
24
3
21
8
16
0
19
8
14
2
1
1
6
3,544
AirtestProject/Poco
AirtestProject_Poco/poco/proxy.py
poco.proxy.ReevaluationContext
class ReevaluationContext(object): """ volatile attributes的重运算同一批次内只执行一次,无需多次执行 """ def __init__(self, proxy): self.target = proxy self.with_this_batch = hasattr(self.target, '__reevaluation_context__') def __enter__(self): if not self.with_this_batch: setattr(self.target, '__reevaluation_context__', True) return self def __exit__(self, exc_type, exc_val, exc_tb): if not self.with_this_batch: delattr(self.target, '__reevaluation_context__')
class ReevaluationContext(object): ''' volatile attributes的重运算同一批次内只执行一次,无需多次执行 ''' def __init__(self, proxy): pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass
4
1
3
0
3
0
2
0.27
1
0
0
0
3
2
3
3
17
3
11
6
7
3
11
6
7
2
1
1
5
3,545
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/AbstractDumper.py
poco.sdk.AbstractDumper.AbstractDumper
class AbstractDumper(IDumper): """ This class partially implements ``IDumper`` using general traversal algorithm. In order to dump the hierarchy from the root node, this dumper first retrieves all available attributes of the root node and also the list all its children and then applies the same procedures as described on each child (i.e. treats each child as a root node) until the node that has no child(ren) is reached. """ def dumpHierarchy(self, onlyVisibleNode=True): """ Returns: :obj:`dict`: json serializable dict holding the whole hierarchy data """ return self.dumpHierarchyImpl(self.getRoot(), onlyVisibleNode) def dumpHierarchyImpl(self, node, onlyVisibleNode=True): """ Crawl the hierarchy tree using the simple DFS algorithm. The ``dump`` procedure is the engine independent as the hierarchy structure is wrapped by :py:class:`AbstractNode <poco.sdk.AbstractNode>` and therefore the ``dump`` procedure can be algorithmized. Following code demonstrates the simplest implementation. Feel free to implement your own algorithms to optimize the performance. .. note:: Do not explicitly call this method as this is an internal function, call :py:meth:`dumpHierarchy() <poco.sdk.AbstractDumper.AbstractDumper.dumpHierarchy>` function instead if you want to dump the hierarchy. Args: node(:py:class:`inherit from AbstractNode <poco.sdk.AbstractNode>`): root node of the hierarchy to be dumped onlyVisibleNode(:obj:`bool`): dump only the visible nodes or all nodes, default to True Returns: :obj:`dict`: json serializable dict holding the whole hierarchy data """ if not node: return None payload = {} # filter out all None values for attrName, attrVal in node.enumerateAttrs(): if attrVal is not None: payload[attrName] = attrVal result = {} children = [] for child in node.getChildren(): if not onlyVisibleNode or child.getAttr('visible'): children.append(self.dumpHierarchyImpl(child, onlyVisibleNode)) if len(children) > 0: result['children'] = children result['name'] = payload.get('name') or node.getAttr('name') result['payload'] = payload return result
class AbstractDumper(IDumper): ''' This class partially implements ``IDumper`` using general traversal algorithm. In order to dump the hierarchy from the root node, this dumper first retrieves all available attributes of the root node and also the list all its children and then applies the same procedures as described on each child (i.e. treats each child as a root node) until the node that has no child(ren) is reached. ''' def dumpHierarchy(self, onlyVisibleNode=True): ''' Returns: :obj:`dict`: json serializable dict holding the whole hierarchy data ''' pass def dumpHierarchyImpl(self, node, onlyVisibleNode=True): ''' Crawl the hierarchy tree using the simple DFS algorithm. The ``dump`` procedure is the engine independent as the hierarchy structure is wrapped by :py:class:`AbstractNode <poco.sdk.AbstractNode>` and therefore the ``dump`` procedure can be algorithmized. Following code demonstrates the simplest implementation. Feel free to implement your own algorithms to optimize the performance. .. note:: Do not explicitly call this method as this is an internal function, call :py:meth:`dumpHierarchy() <poco.sdk.AbstractDumper.AbstractDumper.dumpHierarchy>` function instead if you want to dump the hierarchy. Args: node(:py:class:`inherit from AbstractNode <poco.sdk.AbstractNode>`): root node of the hierarchy to be dumped onlyVisibleNode(:obj:`bool`): dump only the visible nodes or all nodes, default to True Returns: :obj:`dict`: json serializable dict holding the whole hierarchy data ''' pass
3
3
26
6
10
11
4
1.35
1
0
0
3
2
0
2
4
60
13
20
8
17
27
20
8
17
7
2
2
8
3,546
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/Attributor.py
poco.sdk.Attributor.Attributor
class Attributor(object): """ This is a helper class to access the node attributes. In some cases it is not possible to explicitly invoke the node member functions thus the following two functions are introduced. The instance of this class will be used in implementation of :py:class:`HierarchyInterface \ <poco.sdk.interfaces.hierarchy.HierarchyInterface>`. .. note:: Do not call these methods explicitly in the test codes. """ def getAttr(self, node, attrName): if type(node) in (list, tuple): node_ = node[0] else: node_ = node return node_.getAttr(attrName) def setAttr(self, node, attrName, attrVal): if type(node) in (list, tuple): node_ = node[0] else: node_ = node node_.setAttr(attrName, attrVal)
class Attributor(object): ''' This is a helper class to access the node attributes. In some cases it is not possible to explicitly invoke the node member functions thus the following two functions are introduced. The instance of this class will be used in implementation of :py:class:`HierarchyInterface <poco.sdk.interfaces.hierarchy.HierarchyInterface>`. .. note:: Do not call these methods explicitly in the test codes. ''' def getAttr(self, node, attrName): pass def setAttr(self, node, attrName, attrVal): pass
3
1
6
0
6
0
2
0.54
1
3
0
2
2
0
2
2
24
4
13
5
10
7
11
5
8
2
1
1
4
3,547
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/DefaultMatcher.py
poco.sdk.DefaultMatcher.DefaultMatcher
class DefaultMatcher(IMatcher): """ Default matcher implementation for poco hierarchy traversing. Including logical query condition and predicate expression. When traversing through the hierarchy tree, matcher will apply the match method on each node of the tree. The formal definition of query condition as follows:: expr := (op0, (expr0, expr1, ...)) expr := (op1, (arg1, arg2)) - ``op0``:obj:`str` is logical operator ('or' or 'and') which has the same semantics as in python, e.g. 'or' means this expression/condition matches if any of the exprN matches - ``op1``:obj:`str` is comparator, can be one of as follows:: op1 := 'attr=' op1 := 'attr.*=' op1 := ... (other customized) - ``attr=`` corresponds to :py:class:`EqualizationComparator <poco.sdk.DefaultMatcher.EqualizationComparator>`. - ``attr.*=`` corresponds to :py:class:`RegexpComparator <poco.sdk.DefaultMatcher.RegexpComparator>`. The ``op1`` must be a string. The ``Matcher`` will help to map to ``Comparator`` object. """ def __init__(self): super(DefaultMatcher, self).__init__() self.comparators = { 'attr=': EqualizationComparator(), 'attr.*=': RegexpComparator(), } def match(self, cond, node): """ See Also: :py:meth:`IMatcher.match <poco.sdk.DefaultMatcher.IMatcher.match>` """ op, args = cond # 条件匹配 if op == 'and': for arg in args: if not self.match(arg, node): return False return True if op == 'or': for arg in args: if self.match(arg, node): return True return False # 属性匹配 comparator = self.comparators.get(op) if comparator: attribute, value = args targetValue = node.getAttr(attribute) return comparator.compare(targetValue, value) raise NoSuchComparatorException(op, 'poco.sdk.DefaultMatcher')
class DefaultMatcher(IMatcher): ''' Default matcher implementation for poco hierarchy traversing. Including logical query condition and predicate expression. When traversing through the hierarchy tree, matcher will apply the match method on each node of the tree. The formal definition of query condition as follows:: expr := (op0, (expr0, expr1, ...)) expr := (op1, (arg1, arg2)) - ``op0``:obj:`str` is logical operator ('or' or 'and') which has the same semantics as in python, e.g. 'or' means this expression/condition matches if any of the exprN matches - ``op1``:obj:`str` is comparator, can be one of as follows:: op1 := 'attr=' op1 := 'attr.*=' op1 := ... (other customized) - ``attr=`` corresponds to :py:class:`EqualizationComparator <poco.sdk.DefaultMatcher.EqualizationComparator>`. - ``attr.*=`` corresponds to :py:class:`RegexpComparator <poco.sdk.DefaultMatcher.RegexpComparator>`. The ``op1`` must be a string. The ``Matcher`` will help to map to ``Comparator`` object. ''' def __init__(self): pass def match(self, cond, node): ''' See Also: :py:meth:`IMatcher.match <poco.sdk.DefaultMatcher.IMatcher.match>` ''' pass
3
2
17
3
12
3
5
0.84
1
4
3
0
2
1
2
3
59
13
25
9
22
21
22
9
19
8
2
3
9
3,548
AirtestProject/Poco
AirtestProject_Poco/poco/sdk/DefaultMatcher.py
poco.sdk.DefaultMatcher.EqualizationComparator
class EqualizationComparator(object): """ Compare two objects using the native equivalence (==) comparison operator """ def compare(self, l, r): return l == r
class EqualizationComparator(object): ''' Compare two objects using the native equivalence (==) comparison operator ''' def compare(self, l, r): pass
2
1
2
0
2
0
1
1
1
0
0
0
1
0
1
1
7
1
3
2
1
3
3
2
1
1
1
0
1
3,549
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/scroll1.py
poco.drivers.unity3d.test.tutorial.scroll1.Scroll1Tutorial
class Scroll1Tutorial(TutorialCase): def runTest(self): # swipe the list view up self.poco('Scroll View').swipe([0, -0.1]) self.poco('Scroll View').swipe('up') # the same as above, also have down/left/right self.poco('Scroll View').swipe('down') # perform swipe without UI selected x, y = self.poco('Scroll View').get_position() end = [x, y - 0.1] dir = [0, -0.1] self.poco.swipe([x, y], end) # drag from point A to point B self.poco.swipe([x, y], direction=dir)
class Scroll1Tutorial(TutorialCase): def runTest(self): pass
2
0
12
1
9
5
1
0.5
1
0
0
0
1
0
1
3
13
1
10
4
8
5
10
4
8
1
2
0
1
3,550
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/overview.py
poco.drivers.unity3d.test.tutorial.overview.OverviewTutorial
class OverviewTutorial(TutorialCase): def runTest(self): self.poco('btn_start').click() time.sleep(1) self.poco(textMatches='drag.*').click() time.sleep(1) shell = self.poco('shell').focus('center') for star in self.poco('star'): star.drag_to(shell) time.sleep(1) self.assertEqual(self.poco('scoreVal').get_text(), "100", "score correct.") self.poco('btn_back', type='Button').click() def tearDown(self): time.sleep(2)
class OverviewTutorial(TutorialCase): def runTest(self): pass def tearDown(self): pass
3
0
8
2
7
0
2
0
1
0
0
0
2
0
2
4
18
4
14
5
11
0
14
5
11
2
2
1
3
3,551
AirtestProject/Poco
AirtestProject_Poco/poco/exceptions.py
poco.exceptions.PocoTargetRemovedException
class PocoTargetRemovedException(PocoException): """ Raised when the hierarchy structure changed over the selection or when accessing the UI element that is already recycled. In most cases, there is no need to handle this exception manually. If this exception occurs, it usually means it is a bug in your code rather than application itself. Check your code first. The most of misuses comes from as follows. Examples: :: button1 = poco('button1') time.sleep(10) # waiting for long enough before the UI hierarchy changing button1.click() # PocoTargetRemovedException will raise at this line. Because the 'button1' is not on the screen. """ def __init__(self, action, objproxy): super(PocoTargetRemovedException, self).__init__() objproxy = to_text(repr(objproxy)) self.message = 'Remote ui object "{}" has been removed from hierarchy during {}.'.format(objproxy, action)
class PocoTargetRemovedException(PocoException): ''' Raised when the hierarchy structure changed over the selection or when accessing the UI element that is already recycled. In most cases, there is no need to handle this exception manually. If this exception occurs, it usually means it is a bug in your code rather than application itself. Check your code first. The most of misuses comes from as follows. Examples: :: button1 = poco('button1') time.sleep(10) # waiting for long enough before the UI hierarchy changing button1.click() # PocoTargetRemovedException will raise at this line. Because the 'button1' is not on the screen. ''' def __init__(self, action, objproxy): pass
2
1
4
0
4
0
1
2.4
1
1
0
0
1
1
1
13
21
4
5
3
3
12
5
3
3
1
4
0
1
3,552
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/local_positioning3.py
poco.drivers.unity3d.test.tutorial.local_positioning3.LocalPositioning1Tutorial
class LocalPositioning1Tutorial(TutorialCase): def runTest(self): # focus is immutable fish = self.poco('fish').child(type='Image') fish_right_edge = fish.focus([1, 0.5]) fish.long_click() # still click the center time.sleep(0.2) fish_right_edge.long_click() # will click the right edge time.sleep(0.2)
class LocalPositioning1Tutorial(TutorialCase): def runTest(self): pass
2
0
8
0
7
3
1
0.38
1
0
0
0
1
0
1
3
9
0
8
4
6
3
8
4
6
1
2
0
1
3,553
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/long_click.py
poco.drivers.unity3d.test.tutorial.long_click.LongClickTutorial
class LongClickTutorial(TutorialCase): def runTest(self): self.poco('btn_start').click() self.poco('basic').click() self.poco('star_single').long_click() self.poco('star_single').long_click(duration=5)
class LongClickTutorial(TutorialCase): def runTest(self): pass
2
0
5
0
5
0
1
0
1
0
0
0
1
0
1
3
6
0
6
2
4
0
6
2
4
1
2
0
1
3,554
AirtestProject/Poco
AirtestProject_Poco/poco/utils/track.py
poco.utils.track.MotionTrackBatch
class MotionTrackBatch(object): def __init__(self, tracks): super(MotionTrackBatch, self).__init__() self.tracks = tracks def discretize(self, accuracy=0.004): if accuracy < 0.001: accuracy = 0.001 events = [] discretized_tracks = [t.discretize(i, accuracy) for i, t in enumerate(self.tracks)] while discretized_tracks: # take motion events for dtrack in discretized_tracks: while True: evt = dtrack[0] if evt[0] != 's': events.append(evt) dtrack.pop(0) else: break if not dtrack: break discretized_tracks = list(filter(lambda a: a != [], discretized_tracks)) # take sleep events while discretized_tracks and all(dtrack[0][0] == 's' for dtrack in discretized_tracks): evt_sleep = discretized_tracks[0][0] if events: prev_evt = events[-1] if prev_evt[0] == 's': prev_evt[1] += evt_sleep[1] events[-1] = prev_evt else: events.append(evt_sleep) else: events.append(evt_sleep) for dtrack in discretized_tracks: dtrack.pop(0) discretized_tracks = list(filter(lambda a: a != [], discretized_tracks)) return events
class MotionTrackBatch(object): def __init__(self, tracks): pass def discretize(self, accuracy=0.004): pass
3
0
21
3
18
1
6
0.06
1
4
0
0
2
1
2
2
44
6
36
10
33
2
33
10
30
11
1
4
12
3,555
AirtestProject/Poco
AirtestProject_Poco/poco/utils/track.py
poco.utils.track.MotionTrack
class MotionTrack(object): def __init__(self, points=None, speed=0.4): super(MotionTrack, self).__init__() self.speed = speed self.timestamp = 0 self.event_points = [] # [ts, (x, y), contact_id], timestamp as arrival time if points: for p in points: self.move(p) @property def last_point(self): if self.event_points: return self.event_points[-1][1] return None def start(self, p): return self.move(p) def move(self, p): if self.last_point: dt = (Vec2(p) - Vec2(self.last_point)).length / self.speed self.timestamp += dt self.event_points.append([self.timestamp, p, 0]) return self def hold(self, t): self.timestamp += t if self.event_points: self.move(self.last_point) return self def set_contact_id(self, _id): for ep in self.event_points: ep[2] = _id def discretize(self, contact_id=0, accuracy=0.004, dt=0.001): """ Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference """ if not self.event_points: return [] events = [] action_dt = accuracy / self.speed dt = dt or action_dt ep0 = self.event_points[0] for _ in range(int(ep0[0] / dt)): events.append(['s', dt]) events.append(['d', ep0[1], contact_id]) for i, ep in enumerate(self.event_points[1:]): prev_ts = self.event_points[i][0] curr_ts = ep[0] p0 = self.event_points[i][1] p1 = ep[1] if p0 == p1: # hold for _ in range(int((curr_ts - prev_ts) / dt)): events.append(['s', dt]) else: # move dpoints = track_sampling([p0, p1], accuracy) for p in dpoints: events.append(['m', p, contact_id]) for _ in range(int(action_dt / dt)): events.append(['s', dt]) events.append(['u', contact_id]) return events
class MotionTrack(object): def __init__(self, points=None, speed=0.4): pass @property def last_point(self): pass def start(self, p): pass def move(self, p): pass def hold(self, t): pass def set_contact_id(self, _id): pass def discretize(self, contact_id=0, accuracy=0.004, dt=0.001): ''' Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference ''' pass
9
1
10
1
8
1
3
0.18
1
5
1
0
7
3
7
7
77
12
56
26
47
10
54
25
46
8
1
4
20
3,556
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/utils.py
poco.utils.simplerpc.utils.RemoteError
class RemoteError(Exception): pass
class RemoteError(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,557
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/transport/ws/main.py
poco.utils.simplerpc.transport.ws.main.WebSocketClient
class WebSocketClient(IClient): def __init__(self, addr=DEFAULT_ADDR): super(WebSocketClient, self).__init__() self.addr = addr self._inbox = [] self._ws = None self._ws_thread = None def __str__(self): return self.addr __repr__ = __str__ def connect(self): if self._ws_thread: self.close() print("connecting server..") self._init_ws_thread() def send(self, msg): if not isinstance(msg, six.text_type): msg = msg.decode("utf-8") self._ws.send(msg) def recv(self): msgs, self._inbox = self._inbox, [] return msgs def close(self): print("closing connection..") self._ws.close() self._ws_thread = None def _init_ws_thread(self): self._ws = self._init_ws() t = Thread(target=self._ws.run_forever) t.daemon = True t.start() self._ws_thread = t def _init_ws(self): ws = websocket.WebSocketApp(self.addr, on_open=self._on_ws_open, on_message=self._on_ws_message, on_error=self._on_ws_error, on_close=self._on_ws_close) # ws.enableTrace(True) return ws def _on_ws_message(self, ws, message): self._inbox.append(message) def _on_ws_error(self, ws, error): print("on error", error) self.on_close() def _on_ws_close(self, ws, *args, **kwargs): print("on close") self.on_close() def _on_ws_open(self, ws): print('on open') self.on_connect()
class WebSocketClient(IClient): 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 def _init_ws_thread(self): pass def _init_ws_thread(self): pass def _on_ws_message(self, ws, message): pass def _on_ws_error(self, ws, error): pass def _on_ws_close(self, ws, *args, **kwargs): pass def _on_ws_open(self, ws): pass
13
0
4
0
4
0
1
0.02
1
2
0
0
12
4
12
19
63
12
50
21
37
1
46
21
33
2
3
1
14
3,558
AirtestProject/Poco
AirtestProject_Poco/poco/utils/simplerpc/transport/tcp/safetcp.py
poco.utils.simplerpc.transport.tcp.safetcp.Client
class Client(object): """safe and exact recv & send""" def __init__(self, address, on_connect=None, on_close=None): """address is (host, port) tuple""" self.address = address self.on_connect = on_connect self.on_close = on_close self.sock = None self.buf = b"" def connect(self): # create a new socket every time self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(DEFAULT_TIMEOUT) self.sock.connect(self.address) self._handle_connect() def send(self, msg): totalsent = 0 while totalsent < len(msg): sent = self.sock.send(msg[totalsent:]) if sent == 0: self._handle_close() raise socket.error("socket connection broken") totalsent += sent def recv(self, size=DEFAULT_SIZE): trunk = self.sock.recv(size) if trunk == b"": self._handle_close() raise socket.error("socket connection broken") return trunk def recv_all(self, size): while len(self.buf) < size: trunk = self.recv(min(size-len(self.buf), DEFAULT_SIZE)) self.buf += trunk ret, self.buf = self.buf[:size], self.buf[size:] return ret def settimeout(self, timeout): self.sock.settimeout(timeout) 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 is not always right 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): self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() self._handle_close() def _handle_connect(self): if callable(self.on_connect): self.on_connect() def _handle_close(self): if callable(self.on_close): self.on_close()
class Client(object): '''safe and exact recv & send''' def __init__(self, address, on_connect=None, on_close=None): '''address is (host, port) tuple''' pass def connect(self): pass def send(self, msg): pass def recv(self, size=DEFAULT_SIZE): pass def recv_all(self, size): pass def settimeout(self, timeout): pass def recv_nonblocking(self, size): pass def close(self): pass def _handle_connect(self): pass def _handle_close(self): pass
11
2
6
0
6
1
2
0.14
1
1
0
0
10
5
10
10
71
9
56
23
45
8
54
22
43
4
1
2
19
3,559
AirtestProject/Poco
AirtestProject_Poco/poco/acceleration.py
poco.acceleration.PocoAccelerationMixin
class PocoAccelerationMixin(object): """ This class provides some high-level method to reduce redundant code implementations. As this is a MixinClass, please do not introduce new state in methods. """ def dismiss(self, targets, exit_when=None, sleep_interval=0.5, appearance_timeout=20, timeout=120): """ Automatically dismiss the target objects Args: targets (:obj:`list`): list of poco objects to be dropped exit_when: termination condition, default is None which means to automatically exit when list of ``targets`` is empty sleep_interval: time interval between each actions for the given targets, default is 0.5s appearance_timeout: time interval to wait for given target to appear on the screen, automatically exit when timeout, default is 20s timeout: dismiss function timeout, default is 120s Raises: PocoTargetTimeout: when dismiss time interval timeout, under normal circumstances, this should not happen and if happens, it will be reported """ try: self.wait_for_any(targets, timeout=appearance_timeout) except PocoTargetTimeout: # here returns only when timeout # 仅当超时时自动退出 warnings.warn('Waiting timeout when trying to dismiss something before them appear. Targets are {}' .encode('utf-8').format(targets)) return start_time = time.time() while True: no_target = True for t in targets: if t.exists(): try: for n in t: try: n.click(sleep_interval=sleep_interval) no_target = False except: pass except: # Catch the NodeHasBeenRemoved exception if some node was removed over the above iteration # and just ignore as this will not affect the result. # 遍历(__iter__: for n in t)过程中如果节点正好被移除了,可能会报远程节点被移除的异常 # 这个报错忽略就行 pass time.sleep(sleep_interval) should_exit = exit_when() if exit_when else False if no_target or should_exit: return if time.time() - start_time > timeout: raise PocoTargetTimeout('dismiss', targets)
class PocoAccelerationMixin(object): ''' This class provides some high-level method to reduce redundant code implementations. As this is a MixinClass, please do not introduce new state in methods. ''' def dismiss(self, targets, exit_when=None, sleep_interval=0.5, appearance_timeout=20, timeout=120): ''' Automatically dismiss the target objects Args: targets (:obj:`list`): list of poco objects to be dropped exit_when: termination condition, default is None which means to automatically exit when list of ``targets`` is empty sleep_interval: time interval between each actions for the given targets, default is 0.5s appearance_timeout: time interval to wait for given target to appear on the screen, automatically exit when timeout, default is 20s timeout: dismiss function timeout, default is 120s Raises: PocoTargetTimeout: when dismiss time interval timeout, under normal circumstances, this should not happen and if happens, it will be reported ''' pass
2
2
52
5
27
20
11
0.86
1
1
1
1
1
0
1
1
58
6
28
7
26
24
27
7
25
11
1
6
11
3,560
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/android/uiautomation.py
poco.drivers.android.uiautomation.AndroidPocoAgent
class AndroidPocoAgent(PocoAgent): def __init__(self, endpoint, ime, use_airtest_input=False): self.client = AndroidRpcClient(endpoint) remote_poco = self.client.remote('poco-uiautomation-framework') dumper = remote_poco.dumper selector = remote_poco.selector attributor = remote_poco.attributor hierarchy = RemotePocoHierarchy(dumper, selector, attributor) if use_airtest_input: inputer = AirtestInput() else: inputer = remote_poco.inputer super(AndroidPocoAgent, self).__init__(hierarchy, inputer, ScreenWrapper(remote_poco.screen), None)
class AndroidPocoAgent(PocoAgent): def __init__(self, endpoint, ime, use_airtest_input=False): pass
2
0
13
1
12
0
2
0
1
5
4
0
1
1
1
7
14
1
13
9
11
0
12
9
10
2
2
1
2
3,561
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/android/uiautomation.py
poco.drivers.android.uiautomation.AndroidRpcClient
class AndroidRpcClient(RpcClient): def __init__(self, endpoint): self.endpoint = endpoint super(AndroidRpcClient, self).__init__(HttpTransport) def initialize_transport(self): return HttpTransport(self.endpoint, self)
class AndroidRpcClient(RpcClient): def __init__(self, endpoint): pass def initialize_transport(self): pass
3
0
3
0
3
0
1
0
1
1
0
0
2
1
2
2
7
1
6
4
3
0
6
4
3
1
1
0
2
3,562
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/android/uiautomation.py
poco.drivers.android.uiautomation.AndroidUiautomationHelper
class AndroidUiautomationHelper(object): _nuis = {} @classmethod def get_instance(cls, device): """ This is only a slot to store and get already initialized poco instance rather than initializing again. You can simply pass the ``current device instance`` provided by ``airtest`` to get the AndroidUiautomationPoco instance. If no such AndroidUiautomationPoco instance, a new instance will be created and stored. Args: device (:py:obj:`airtest.core.device.Device`): more details refer to ``airtest doc`` Returns: poco instance """ if cls._nuis.get(device) is None: cls._nuis[device] = AndroidUiautomationPoco(device) return cls._nuis[device]
class AndroidUiautomationHelper(object): @classmethod def get_instance(cls, device): ''' This is only a slot to store and get already initialized poco instance rather than initializing again. You can simply pass the ``current device instance`` provided by ``airtest`` to get the AndroidUiautomationPoco instance. If no such AndroidUiautomationPoco instance, a new instance will be created and stored. Args: device (:py:obj:`airtest.core.device.Device`): more details refer to ``airtest doc`` Returns: poco instance ''' pass
3
1
16
3
4
9
2
1.29
1
1
1
0
0
0
1
1
20
4
7
4
4
9
6
3
4
2
1
1
2
3,563
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/android/uiautomation.py
poco.drivers.android.uiautomation.AndroidUiautomationPoco
class AndroidUiautomationPoco(Poco): """ Poco Android implementation for testing **Android native apps**. Args: device (:py:obj:`Device`): :py:obj:`airtest.core.device.Device` instance provided by ``airtest``. leave the parameter default and the default device will be chosen. more details refer to ``airtest doc`` using_proxy (:py:obj:`bool`): whether use adb forward to connect the Android device or not force_restart (:py:obj:`bool`): whether always restart the poco-service-demo running on Android device or not options: see :py:class:`poco.pocofw.Poco` Examples: The simplest way to initialize AndroidUiautomationPoco instance and no matter your device network status:: from poco.drivers.android.uiautomation import AndroidUiautomationPoco poco = AndroidUiautomationPoco() poco('android:id/title').click() ... """ def __init__(self, device=None, using_proxy=True, force_restart=False, use_airtest_input=False, **options): # 加这个参数为了不在最新的pocounit方案中每步都截图 self.screenshot_each_action = True if options.get('screenshot_each_action') is False: self.screenshot_each_action = False self.device = device or default_device() self.adb_client = self.device.adb if using_proxy: self.device_ip = self.adb_client.host or "127.0.0.1" else: self.device_ip = self.device.get_ip_address() # save current top activity (@nullable) try: current_top_activity_package = self.device.get_top_activity_name() except AirtestError as e: # 在一些极端情况下,可能获取不到top activity的信息 print(e) current_top_activity_package = None if current_top_activity_package is not None: current_top_activity_package = current_top_activity_package.split('/')[0] # install ime self.ime = YosemiteIme(self.adb_client) # install self._instrument_proc = None self._install_service() # forward self.forward_list = [] if using_proxy: p0, _ = self.adb_client.setup_forward("tcp:10080") p1, _ = self.adb_client.setup_forward("tcp:10081") self.forward_list.extend(["tcp:%s" % p0, "tcp:%s" % p1]) else: p0 = 10080 p1 = 10081 # start ready = self._start_instrument(p0, force_restart=force_restart) if not ready: # 之前启动失败就卸载重装,现在改为尝试kill进程或卸载uiautomator self._kill_uiautomator() ready = self._start_instrument(p0) if current_top_activity_package is not None: current_top_activity2 = self.device.get_top_activity_name() if current_top_activity2 is None or current_top_activity_package not in current_top_activity2: self.device.start_app(current_top_activity_package, activity=True) if not ready: raise RuntimeError("unable to launch AndroidUiautomationPoco") if ready: # 首次启动成功后,在后台线程里监控这个进程的状态,保持让它不退出 self._keep_running_thread = KeepRunningInstrumentationThread(self, p0) self._keep_running_thread.start() endpoint = "http://{}:{}".format(self.device_ip, p1) agent = AndroidPocoAgent(endpoint, self.ime, use_airtest_input) super(AndroidUiautomationPoco, self).__init__(agent, **options) def _install_service(self): updated = install(self.adb_client, os.path.join(this_dir, 'lib', 'pocoservice-debug.apk')) return updated def _is_running(self, package_name): """ use ps |grep to check whether the process exists :param package_name: package name(e.g., com.github.uiautomator) or regular expression(e.g., poco\|airtest\|uiautomator\|airbase) :return: pid or None """ cmd = r' |echo $(grep -E {package_name})'.format(package_name=package_name) if self.device.sdk_version > 25: cmd = r'ps -A' + cmd else: cmd = r'ps' + cmd processes = self.adb_client.shell(cmd).splitlines() for ps in processes: if ps: ps = ps.split() return ps[1] return None def _start_instrument(self, port_to_ping, force_restart=False): if not force_restart: try: state = requests.get('http://{}:{}/uiautomation/connectionState'.format(self.device_ip, port_to_ping), timeout=10) state = state.json() if state.get('connected'): # skip starting instrumentation if UiAutomation Service already connected. return True except: pass if self._instrument_proc is not None: if self._instrument_proc.poll() is None: self._instrument_proc.kill() self._instrument_proc = None ready = False # self.adb_client.shell(['am', 'force-stop', PocoServicePackage]) # 启动instrument之前,先把主类activity启动起来,不然instrumentation可能失败 self.adb_client.shell('am start -n {}/.TestActivity'.format(PocoServicePackage)) instrumentation_cmd = [ 'am', 'instrument', '-w', '-e', 'debug', 'false', '-e', 'class', '{}.InstrumentedTestAsLauncher'.format(PocoServicePackage), '{}/androidx.test.runner.AndroidJUnitRunner'.format(PocoServicePackage)] self._instrument_proc = self.adb_client.start_shell(instrumentation_cmd) def cleanup_proc(proc): def wrapped(): try: proc.kill() except: pass return wrapped atexit.register(cleanup_proc(self._instrument_proc)) time.sleep(2) for i in range(10): try: requests.get('http://{}:{}'.format(self.device_ip, port_to_ping), timeout=10) ready = True break except requests.exceptions.Timeout: break except requests.exceptions.ConnectionError: if self._instrument_proc.poll() is not None: warnings.warn("[pocoservice.apk] instrumentation test server process is no longer alive") stdout = self._instrument_proc.stdout.read() stderr = self._instrument_proc.stderr.read() print('[pocoservice.apk] stdout: {}'.format(stdout)) print('[pocoservice.apk] stderr: {}'.format(stderr)) time.sleep(1) print("still waiting for uiautomation ready.") try: self.adb_client.shell( ['monkey', '-p', {PocoServicePackage}, '-c', 'android.intent.category.LAUNCHER', '1']) except Exception as e: pass self.adb_client.shell('am start -n {}/.TestActivity'.format(PocoServicePackage)) instrumentation_cmd = [ 'am', 'instrument', '-w', '-e', 'debug', 'false', '-e', 'class', '{}.InstrumentedTestAsLauncher'.format(PocoServicePackage), '{}/androidx.test.runner.AndroidJUnitRunner'.format(PocoServicePackage)] self._instrument_proc = self.adb_client.start_shell(instrumentation_cmd) continue return ready def _kill_uiautomator(self): """ poco-service无法与其他instrument启动的apk同时存在,因此在启动前,需要杀掉一些可能的进程: 比如 io.appium.uiautomator2.server, com.github.uiautomator, com.netease.open.pocoservice等 :return: """ pid = self._is_running("uiautomator") if pid: warnings.warn('{} should not run together with "uiautomator". "uiautomator" will be killed.' .format(self.__class__.__name__)) self.adb_client.shell(['am', 'force-stop', PocoServicePackage]) try: self.adb_client.shell(['kill', pid]) except AdbShellError: # 没有root权限 uninstall(self.adb_client, UiAutomatorPackage) def on_pre_action(self, action, ui, args): if self.screenshot_each_action: # airteset log用 from airtest.core.api import snapshot msg = repr(ui) if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') snapshot(msg=msg) def stop_running(self): print('[pocoservice.apk] stopping PocoService') self._keep_running_thread.stop() self._keep_running_thread.join(3) self.remove_forwards() self.adb_client.shell(['am', 'force-stop', PocoServicePackage]) def remove_forwards(self): for p in self.forward_list: self.adb_client.remove_forward(p) self.forward_list = []
class AndroidUiautomationPoco(Poco): ''' Poco Android implementation for testing **Android native apps**. Args: device (:py:obj:`Device`): :py:obj:`airtest.core.device.Device` instance provided by ``airtest``. leave the parameter default and the default device will be chosen. more details refer to ``airtest doc`` using_proxy (:py:obj:`bool`): whether use adb forward to connect the Android device or not force_restart (:py:obj:`bool`): whether always restart the poco-service-demo running on Android device or not options: see :py:class:`poco.pocofw.Poco` Examples: The simplest way to initialize AndroidUiautomationPoco instance and no matter your device network status:: from poco.drivers.android.uiautomation import AndroidUiautomationPoco poco = AndroidUiautomationPoco() poco('android:id/title').click() ... ''' def __init__(self, device=None, using_proxy=True, force_restart=False, use_airtest_input=False, **options): pass def _install_service(self): pass def _is_running(self, package_name): ''' use ps |grep to check whether the process exists :param package_name: package name(e.g., com.github.uiautomator) or regular expression(e.g., poco\|airtest\|uiautomator\|airbase) :return: pid or None ''' pass def _start_instrument(self, port_to_ping, force_restart=False): pass def cleanup_proc(proc): pass def wrapped(): pass def _kill_uiautomator(self): ''' poco-service无法与其他instrument启动的apk同时存在,因此在启动前,需要杀掉一些可能的进程: 比如 io.appium.uiautomator2.server, com.github.uiautomator, com.netease.open.pocoservice等 :return: ''' pass def on_pre_action(self, action, ui, args): pass def stop_running(self): pass def remove_forwards(self): pass
11
3
20
2
16
3
4
0.27
1
6
2
0
8
8
8
38
218
32
146
42
134
40
134
40
122
11
3
3
39
3,564
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/android/uiautomation.py
poco.drivers.android.uiautomation.AttributorWrapper
class AttributorWrapper(Attributor): """ 部分手机上仍不支持Accessibility.ACTION_SET_TEXT,使用YosemiteIme还是兼容性最好的方案 这个class会hook住set_text,然后改用ime的text方法 """ def __init__(self, remote, ime): self.remote = remote self.ime = ime def getAttr(self, node, attrName): return self.remote.getAttr(node, attrName) def setAttr(self, node, attrName, attrVal): if attrName == 'text' and attrVal != '': # 先清除了再设置,虽然这样不如直接用ime的方法好,但是也能凑合用着 current_val = self.remote.getAttr(node, 'text') if current_val: self.remote.setAttr(node, 'text', '') self.ime.text(attrVal) else: self.remote.setAttr(node, attrName, attrVal)
class AttributorWrapper(Attributor): ''' 部分手机上仍不支持Accessibility.ACTION_SET_TEXT,使用YosemiteIme还是兼容性最好的方案 这个class会hook住set_text,然后改用ime的text方法 ''' def __init__(self, remote, ime): pass def getAttr(self, node, attrName): pass def setAttr(self, node, attrName, attrVal): pass
4
1
5
0
4
0
2
0.36
1
0
0
0
3
2
3
5
22
3
14
7
10
5
13
7
9
3
2
2
5
3,565
AirtestProject/Poco
AirtestProject_Poco/poco/utils/vector.py
poco.utils.vector.Vec2
class Vec2(object): def __init__(self, x=0.0, y=0.0): if type(x) in (list, tuple): self.x = x[0] self.y = x[1] else: self.x = x self.y = y @staticmethod def from_radian(rad): x = math.cos(rad) y = math.sin(rad) return Vec2(x, y) def __add__(self, other): return Vec2(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vec2(self.x - other.x, self.y - other.y) def __radd__(self, other): return Vec2(other.x + self.x, other.y + self.y) def __rsub__(self, other): return Vec2(other.x - self.x, other.y - self.y) def __mul__(self, other): return Vec2(self.x * other, self.y * other) def __rmul__(self, other): return Vec2(self.x * other, self.y * other) def to_list(self): return [self.x, self.y] @classmethod def intersection_angle(cls, v1, v2): cosval = cls.dot_product(v1, v2) / (v1.length * v2.length) if -2 < cosval < -1: cosval = -1 elif 1 < cosval < 2: cosval = 1 return math.acos(cosval) * (1 if cls.cross_product(v1, v2) > 0 else -1) @staticmethod def dot_product(v1, v2): return v1.x * v2.x + v1.y * v2.y @staticmethod def cross_product(v1, v2): return v1.x * v2.y - v2.x * v1.y @property def length(self): return math.sqrt(self.x ** 2 + self.y ** 2) def unit(self): length = self.length return Vec2(self.x / length, self.y / length) def rotate(self, radian): qx = math.cos(radian) * self.x - math.sin(radian) * self.y qy = math.sin(radian) * self.x + math.cos(radian) * self.y self.x, self.y = qx, qy def __str__(self): return '({}, {})'.format(self.x, self.y) __repr__ = __str__
class Vec2(object): def __init__(self, x=0.0, y=0.0): pass @staticmethod def from_radian(rad): pass def __add__(self, other): pass def __sub__(self, other): pass def __radd__(self, other): pass def __rsub__(self, other): pass def __mul__(self, other): pass def __rmul__(self, other): pass def to_list(self): pass @classmethod def intersection_angle(cls, v1, v2): pass @staticmethod def dot_product(v1, v2): pass @staticmethod def cross_product(v1, v2): pass @property def length(self): pass def unit(self): pass def rotate(self, radian): pass def __str__(self): pass
22
0
3
0
3
0
1
0
1
3
0
0
12
2
16
16
69
15
54
31
32
0
47
26
30
4
1
1
20
3,566
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/android/uiautomation.py
poco.drivers.android.uiautomation.KeepRunningInstrumentationThread
class KeepRunningInstrumentationThread(threading.Thread): """Keep pocoservice running""" def __init__(self, poco, port_to_ping): super(KeepRunningInstrumentationThread, self).__init__() self._stop_event = threading.Event() self.poco = poco self.port_to_ping = port_to_ping self.daemon = True def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() def run(self): while not self.stopped(): if not self.stopped(): self.poco._start_instrument(self.port_to_ping) # 尝试重启 time.sleep(1)
class KeepRunningInstrumentationThread(threading.Thread): '''Keep pocoservice running''' def __init__(self, poco, port_to_ping): pass def stop(self): pass def stopped(self): pass def run(self): pass
5
1
4
0
4
0
2
0.13
1
2
0
0
4
4
4
29
21
4
16
9
11
2
16
9
11
3
1
2
6
3,567
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/cocosjs/__init__.py
poco.drivers.cocosjs.CocosJsPoco
class CocosJsPoco(Poco): """docstring for CocosJsPoco""" def __init__(self, addr=DEFAULT_ADDR, device=None, **options): if not isinstance(addr, (tuple, list, six.string_types)): raise TypeError('Argument "addr" should be `tuple[2]`, `list[2]` or `string` only. Got {}' .format(type(addr))) try: if isinstance(addr, (list, tuple)): ip, port = addr else: port = urlparse(addr).port if not port: raise ValueError ip = urlparse(addr).hostname except ValueError: raise ValueError('Argument "addr" should be a tuple[2] or string format. e.g. ' '["localhost", 5003] or "ws://localhost:5003". Got {}'.format(repr(addr))) agent = CocosJsPocoAgent(port, device, ip=ip) if 'action_interval' not in options: options['action_interval'] = 0.5 super(CocosJsPoco, self).__init__(agent, **options)
class CocosJsPoco(Poco): '''docstring for CocosJsPoco''' def __init__(self, addr=DEFAULT_ADDR, device=None, **options): pass
2
1
21
2
19
0
6
0.05
1
7
1
0
1
0
1
31
24
3
20
4
18
1
17
4
15
6
3
3
6
3,568
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/cocosjs/__init__.py
poco.drivers.cocosjs.CocosJsPocoAgent
class CocosJsPocoAgent(PocoAgent): def __init__(self, port, device=None, ip=None): if ip is None or ip == "localhost": self.device = device or default_device() platform_name = device_platform(self.device) if platform_name == 'Android': local_port, _ = self.device.adb.setup_forward('tcp:{}'.format(port)) ip = self.device.adb.host or 'localhost' port = local_port elif platform_name == 'IOS': port, _ = self.device.setup_forward(port) if self.device.is_local_device: ip = 'localhost' else: ip = self.device.ip else: ip = self.device.get_ip_address() # transport self.conn = WebSocketClient('ws://{}:{}'.format(ip, port)) self.c = RpcClient(self.conn) self.c.connect() hierarchy = FrozenUIHierarchy(Dumper(self.c)) screen = AirtestScreen() inputs = AirtestInput() super(CocosJsPocoAgent, self).__init__(hierarchy, inputs, screen, None) @property def rpc(self): return self.c def get_sdk_version(self): return self.rpc.call("getSDKVersion")
class CocosJsPocoAgent(PocoAgent): def __init__(self, port, device=None, ip=None): pass @property def rpc(self): pass def get_sdk_version(self): pass
5
0
10
1
9
0
2
0.03
1
7
6
0
3
3
3
9
35
5
29
13
24
1
25
12
21
5
2
3
7
3,569
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/osx/sdk/OSXUINode.py
poco.drivers.osx.sdk.OSXUINode.OSXUINode
class OSXUINode(AbstractNode): def __init__(self, control, dumper): self.Control = control self.dumper = dumper def getParent(self): return OSXUINode(self.Control.AXParent, self.dumper) def getChildren(self): childs = self.Control.AXChildren if childs is not None: for node in childs: yield OSXUINode(node, self.dumper) def getAttr(self, attrName): attrs = self.Control.getAttributes() if attrName == 'name': if 'AXTitle' in attrs: if self.Control.AXTitle != "" and self.Control.AXTitle is not None: return self.Control.AXTitle if 'AXRole' in attrs: return self.Control.AXRole[2:] if attrName == 'originType': if 'AXRole' in attrs: return self.Control.AXRole return "Unknow" if attrName == 'type': if 'AXRole' in attrs: return self.Control.AXRole[2:] return "Unknow" if attrName == 'pos': pos = self.Control.AXPosition size = self.Control.AXSize return [float(pos[0] + size[0] / 2.0 - self.dumper.RootLeft) / float(self.dumper.RootWidth), float(pos[1] + size[1] / 2.0 - self.dumper.RootTop) / float(self.dumper.RootHeight)] if attrName == 'size': pos = self.Control.AXPosition size = self.Control.AXSize return [size[0] / float(self.dumper.RootWidth), size[1] / float(self.dumper.RootHeight)] if attrName == 'text': if 'AXValue' in attrs: if isinstance(self.Control.AXValue, string_types): return self.Control.AXValue if isinstance(self.Control.AXValue, int): return str(self.Control.AXValue) if isinstance(self.Control.AXValue, float): return str(self.Control.AXValue) return None return super(OSXUINode, self).getAttr(attrName) def setAttr(self, attrName, val): attrs = self.Control.getAttributes() if attrName != 'text': raise UnableToSetAttributeException(attrName, self) else: if 'AXValue' in attrs: self.Control.AXValue = val else: raise UnableToSetAttributeException(attrName, self) def getAvailableAttributeNames(self): if 'AXValue' in self.Control.getAttributes(): return super(OSXUINode, self).getAvailableAttributeNames() + ('text', 'originType') else: return super(OSXUINode, self).getAvailableAttributeNames() + ('originType', )
class OSXUINode(AbstractNode): def __init__(self, control, dumper): pass def getParent(self): pass def getChildren(self): pass def getAttr(self, attrName): pass def setAttr(self, attrName, val): pass def getAvailableAttributeNames(self): pass
7
0
11
1
10
0
4
0
1
5
1
0
6
2
6
12
73
14
59
15
52
0
56
15
49
16
2
3
26
3,570
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/osx/sdk/OSXUIFunc.py
poco.drivers.osx.sdk.OSXUIFunc.OSXFunc
class OSXFunc(object): @classmethod def getRunningApps(cls): ws = AppKit.NSWorkspace.sharedWorkspace() apps = ws.runningApplications() return apps @classmethod def getAppRefByPid(cls, pid): return _a11y.getAppRefByPid(atomac.AXClasses.NativeUIElement, pid) @classmethod def getAppRefByBundleId(cls, bundleId): """ Get the top level element for the application with the specified bundle ID, such as com.vmware.fusion. """ ra = AppKit.NSRunningApplication # return value (apps) is always an array. if there is a match it will # have an item, otherwise it won't. apps = ra.runningApplicationsWithBundleIdentifier_(bundleId) if len(apps) == 0: raise ValueError(('Specified bundle ID not found in ' 'running apps: %s' % bundleId)) pid = apps[0].processIdentifier() return cls.getAppRefByPid(pid) @classmethod def getAppRefByLocalizedName(cls, name): apps = cls.getRunningApps() for app in apps: if fnmatch.fnmatch(app.localizedName(), name): pid = app.processIdentifier() return cls.getAppRefByPid(pid) raise ValueError('Specified application not found in running apps.') @staticmethod def press(x, y, button=1): event = Quartz.CGEventCreateMouseEvent(None, pressID[button], (x, y), button - 1) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) @staticmethod def release(x, y, button=1): event = Quartz.CGEventCreateMouseEvent(None, releaseID[button], (x, y), button - 1) Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) @staticmethod def click(x, y, button=1): theEvent = Quartz.CGEventCreateMouseEvent(None, pressID[button], (x, y), button - 1) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) Quartz.CGEventSetType(theEvent, Quartz.kCGEventLeftMouseUp) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) @staticmethod def rclick(x, y, button=2): theEvent = Quartz.CGEventCreateMouseEvent(None, pressID[button], (x, y), button - 1) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) Quartz.CGEventSetType(theEvent, releaseID[button]) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) @staticmethod def doubleclick(x, y, button=1): theEvent = Quartz.CGEventCreateMouseEvent(None, pressID[button], (x, y), button - 1) Quartz.CGEventSetIntegerValueField(theEvent, Quartz.kCGMouseEventClickState, 2) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) Quartz.CGEventSetType(theEvent, Quartz.kCGEventLeftMouseUp) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) Quartz.CGEventSetType(theEvent, Quartz.kCGEventLeftMouseDown) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) Quartz.CGEventSetType(theEvent, Quartz.kCGEventLeftMouseUp) Quartz.CGEventPost(Quartz.kCGHIDEventTap, theEvent) @staticmethod def move(x, y): move = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, (x, y), 0) Quartz.CGEventPost(Quartz.kCGHIDEventTap, move) @staticmethod def drag(x, y): drag = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventLeftMouseDragged, (x, y), 0) Quartz.CGEventPost(Quartz.kCGHIDEventTap, drag) @staticmethod def scroll(vertical=None, horizontal=None, depth=None): # Local submethod for generating Mac scroll events in one axis at a time def scroll_event(y_move=0, x_move=0, z_move=0, n=1): for _ in range(abs(n)): scrollWheelEvent = Quartz.CGEventCreateScrollWheelEvent( None, # No source Quartz.kCGScrollEventUnitLine, # Unit of measurement is lines 3, # Number of wheels(dimensions) y_move, x_move, z_move) Quartz.CGEventPost(Quartz.kCGHIDEventTap, scrollWheelEvent) # Execute vertical then horizontal then depth scrolling events if vertical is not None: vertical = int(vertical) if vertical == 0: # Do nothing with 0 distance pass elif vertical > 0: # Scroll up if positive scroll_event(y_move=1, n=vertical) else: # Scroll down if negative scroll_event(y_move=-1, n=abs(vertical)) if horizontal is not None: horizontal = int(horizontal) if horizontal == 0: # Do nothing with 0 distance pass elif horizontal > 0: # Scroll right if positive scroll_event(x_move=1, n=horizontal) else: # Scroll left if negative scroll_event(x_move=-1, n=abs(horizontal)) if depth is not None: depth = int(depth) if depth == 0: # Do nothing with 0 distance pass elif vertical > 0: # Scroll "out" if positive scroll_event(z_move=1, n=depth) else: # Scroll "in" if negative scroll_event(z_move=-1, n=abs(depth))
class OSXFunc(object): @classmethod def getRunningApps(cls): pass @classmethod def getAppRefByPid(cls, pid): pass @classmethod def getAppRefByBundleId(cls, bundleId): ''' Get the top level element for the application with the specified bundle ID, such as com.vmware.fusion. ''' pass @classmethod def getAppRefByLocalizedName(cls, name): pass @staticmethod def press(x, y, button=1): pass @staticmethod def release(x, y, button=1): pass @staticmethod def click(x, y, button=1): pass @staticmethod def rclick(x, y, button=2): pass @staticmethod def doubleclick(x, y, button=1): pass @staticmethod def move(x, y): pass @staticmethod def drag(x, y): pass @staticmethod def scroll(vertical=None, horizontal=None, depth=None): pass def scroll_event(y_move=0, x_move=0, z_move=0, n=1): pass
26
1
8
0
8
2
2
0.2
1
3
0
0
0
0
12
12
122
13
101
43
75
20
76
31
62
10
1
2
26
3,571
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/osx/sdk/OSXUIDumper.py
poco.drivers.osx.sdk.OSXUIDumper.OSXUIDumper
class OSXUIDumper(AbstractDumper): def __init__(self, root): self.RootControl = root self.RootHeight = self.RootControl.AXSize[1] self.RootWidth = self.RootControl.AXSize[0] self.RootLeft = self.RootControl.AXPosition[0] self.RootTop = self.RootControl.AXPosition[1] if self.RootWidth == 0 or self.RootHeight == 0: raise InvalidSurfaceException(self, "You may have minimized your window or the window is too small!") def getRoot(self): return OSXUINode(self.RootControl, self)
class OSXUIDumper(AbstractDumper): def __init__(self, root): pass def getRoot(self): pass
3
0
5
0
5
0
2
0
1
2
2
0
2
5
2
6
13
2
11
8
8
0
11
8
8
2
3
1
3
3,572
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/osx/sdk/OSXUI.py
poco.drivers.osx.sdk.OSXUI.PocoSDKOSX
class PocoSDKOSX(object): def __init__(self, addr=DEFAULT_ADDR): self.reactor = None self.addr = addr self.running = False self.root = None self.keyboard = Controller() def Dump(self, _): res = OSXUIDumper(self.root).dumpHierarchy() return res def SetForeground(self): self.root.AXMinimized = False self.app.AXFrontmost = True def GetSDKVersion(self): return '0.0.1' def GetDebugProfilingData(self): return {} def GetScreenSize(self): Width = self.root.AXSize[0] Height = self.root.AXSize[1] return [Width, Height] def GetWindowRect(self): Width = self.root.AXSize[0] Height = self.root.AXSize[1] return [self.root.AXPosition[0], self.root.AXPosition[1], self.root.AXPosition[0] + Width, self.root.AXPosition[1] + Height] def KeyEvent(self, keycode): waittime = 0.05 for c in keycode: self.keyboard.press(key=c) self.keyboard.release(key=c) time.sleep(waittime) return True def Screenshot(self, width): self.SetForeground() size = self.root.AXSize pos = self.root.AXPosition pyautogui.screenshot('Screenshot.png', (pos[0], pos[1], size[0], size[1])).save('Screenshot.png') f = open(r'Screenshot.png', 'rb') deflated = zlib.compress(f.read()) ls_f = base64.b64encode(deflated) f.close() return [ls_f, "png.deflate"] # self.root.ToBitmap().ToFile('Screenshot.bmp') # f = open(r'Screenshot.bmp', 'rb') # ls_f = base64.b64encode(f.read()) # f.close() # return [ls_f, "bmp"] def Click(self, x, y): self.SetForeground() size = self.root.AXSize pos = self.root.AXPosition OSXFunc.click(pos[0] + size[0] * x, pos[1] + size[1] * y) return True def RClick(self, x, y): self.SetForeground() size = self.root.AXSize pos = self.root.AXPosition OSXFunc.rclick(pos[0] + size[0] * x, pos[1] + size[1] * y) return True def DoubleClick(self, x, y): self.SetForeground() size = self.root.AXSize pos = self.root.AXPosition OSXFunc.doubleclick(pos[0] + size[0] * x, pos[1] + size[1] * y) return True def Swipe(self, x1, y1, x2, y2, duration): self.SetForeground() Left = self.root.AXPosition[0] Top = self.root.AXPosition[1] Width = self.root.AXSize[0] Height = self.root.AXSize[1] x1 = Left + Width * x1 y1 = Top + Height * y1 x2 = Left + Width * x2 y2 = Top + Height * y2 sx = abs(x1 - x2) sy = abs(y1 - y2) stepx = sx / (duration * 10.0) # 将滑动距离分割,实现平滑的拖动 stepy = sy / (duration * 10.0) OSXFunc.move(x1, y1) OSXFunc.press(x1, y1) duration = int(duration * 10.0) for i in range(duration + 1): OSXFunc.drag(x1 + stepx * i, y1 + stepy * i) time.sleep(0.1) OSXFunc.release(x2, y2) return True def LongClick(self, x, y, duration, **kwargs): self.SetForeground() # poco std暂不支持选择鼠标按键 button = kwargs.get("button", "left") if button not in ("left", "right"): raise ValueError("Unknow button: " + button) if button is "left": button = 1 else: button = 2 Left = self.root.AXPosition[0] Top = self.root.AXPosition[1] Width = self.root.AXSize[0] Height = self.root.AXSize[1] x = Left + Width * x y = Top + Height * y OSXFunc.move(x, y) OSXFunc.press(x, y, button=button) time.sleep(duration) OSXFunc.release(x, y, button=button) return True def Scroll(self, direction, percent, duration): if direction not in ('vertical', 'horizontal'): raise ValueError('Argument `direction` should be one of "vertical" or "horizontal". Got {}'.format(repr(direction))) x = 0.5 # 先把鼠标移到窗口中间,这样才能保证滚动的是这个窗口。 y = 0.5 steps = percent Left = self.GetWindowRect()[0] Top = self.GetWindowRect()[1] Width = self.GetScreenSize()[0] Height = self.GetScreenSize()[1] x = Left + Width * x y = Top + Height * y x = int(x) y = int(y) OSXFunc.move(x, y) if direction == 'horizontal': interval = float(duration) / (abs(steps) + 1) if steps < 0: for i in range(0, abs(steps)): time.sleep(interval) OSXFunc.scroll(None, 1) else: for i in range(0, abs(steps)): time.sleep(interval) OSXFunc.scroll(None, -1) else: interval = float(duration) / (abs(steps) + 1) if steps < 0: for i in range(0, abs(steps)): time.sleep(interval) OSXFunc.scroll(1) else: for i in range(0, abs(steps)): time.sleep(interval) OSXFunc.scroll(-1) return True def EnumWindows(self, selector): names = [] # 一个应用程序会有多个窗口,因此我们要先枚举一个应用程序里的所有窗口 if 'bundleid' in selector: self.app = OSXFunc.getAppRefByBundleId(selector['bundleid']) windows = self.app.windows() for i, w in enumerate(windows): names.append((w.AXTitle, i)) return names if 'appname' in selector: self.app = OSXFunc.getAppRefByLocalizedName(selector['appname']) windows = self.app.windows() for i, w in enumerate(windows): names.append((w.AXTitle, i)) return names if 'appname_re' in selector: # 此方法由于MacOS API,问题较多 apps = OSXFunc.getRunningApps() # 获取当前运行的所有应用程序 appset = [] # 应用程序集合 appnameset = set() # 应用程序标题集合 for t in apps: tempapp = OSXFunc.getAppRefByPid(t.processIdentifier()) if str(tempapp) == str(atomac.AXClasses.NativeUIElement()): # 通过trick判断应用程序是都否为空 continue attrs = tempapp.getAttributes() if 'AXTitle' in attrs: tit = tempapp.AXTitle if re.match(selector['appname_re'], tit): appset.append(tempapp) appnameset.add(tit) # 这里有Bug,可能会获取到进程的不同副本,所以要通过名字去判断是否唯一 if len(appnameset) is 0: raise InvalidSurfaceException(selector, "Can't find any applications by the given parameter") if len(appnameset) != 1: raise NonuniqueSurfaceException(selector) while len(names) is 0: # 有可能有多个副本,但只有一个真的应用程序有窗口,所以要枚举去找 if len(appset) is 0: return names self.app = appset.pop() windows = self.app.windows() # 获取当前应用程序的所有窗口 for i, w in enumerate(windows): names.append((w.AXTitle, i)) return names return names def ConnectWindowsByWindowTitle(self, selector, wlist): hn = set() for n in wlist: if selector['windowtitle'] == n[0]: hn.add(n[1]) # 添加窗口索引到集合里 if len(hn) == 0: return -1 return hn def ConnectWindowsByWindowTitleRe(self, selector, wlist): hn = set() for n in wlist: if re.match(selector['windowtitle_re'], n[0]): hn.add(n[1]) # 添加窗口索引到集合里 if len(hn) == 0: return -1 return hn def ConnectWindow(self, selector): # 目前来说,如下处理,以后添加更多的参数后需修改代码逻辑 argunums = 0 if 'bundleid' in selector: argunums += 1 if 'appname' in selector: argunums += 1 if 'appname_re' in selector: argunums += 1 if argunums == 0: raise ValueError("Expect bundleid or appname, got none") elif argunums != 1: raise ValueError("Too many arguments, only need bundleid or appname or appname_re") winlist = self.EnumWindows(selector) handleSetList = [] if 'windowtitle' in selector: handleSetList.append(self.ConnectWindowsByWindowTitle(selector, winlist)) if 'windowindex' in selector: handleSetList.append(set([selector['windowindex']])) if "windowtitle_re" in selector: handleSetList.append(self.ConnectWindowsByWindowTitleRe(selector, winlist)) while -1 in handleSetList: handleSetList.remove(-1) # 有些参数没有提供会返回-1.把所有的-1去掉 if len(handleSetList) == 0: # 三种方法都找不到窗口 raise InvalidSurfaceException(selector, "Can't find any applications by the given parameter") handleSet = reduce(operator.__and__, handleSetList) # 提供了多个参数来确定唯一一个窗口,所以要做交集,取得唯一匹配的窗口 if len(handleSet) == 0: raise InvalidSurfaceException(selector, "Can't find any applications by the given parameter") elif len(handleSet) != 1: raise NonuniqueSurfaceException(selector) else: hn = handleSet.pop() # 取得该窗口的索引 w = self.app.windows() if len(w) <= hn: raise IndexError("Unable to find the specified window through the index, you may have closed the specified window during the run") self.root = self.app.windows()[hn] self.SetForeground() return True def run(self): self.reactor = StdRpcReactor() self.reactor.register('Dump', self.Dump) self.reactor.register('GetSDKVersion', self.GetSDKVersion) self.reactor.register('GetDebugProfilingData', self.GetDebugProfilingData) self.reactor.register('GetScreenSize', self.GetScreenSize) self.reactor.register('Screenshot', self.Screenshot) self.reactor.register('Click', self.Click) self.reactor.register('Swipe', self.Swipe) self.reactor.register('LongClick', self.LongClick) self.reactor.register('SetForeground', self.SetForeground) self.reactor.register('ConnectWindow', self.ConnectWindow) self.reactor.register('Scroll', self.Scroll) self.reactor.register('RClick', self.RClick) self.reactor.register('DoubleClick', self.DoubleClick) self.reactor.register('KeyEvent', self.KeyEvent) transport = TcpSocket() transport.bind(self.addr) self.rpc = StdRpcEndpointController(transport, self.reactor) if self.running is False: self.running = True self.rpc.serve_forever()
class PocoSDKOSX(object): def __init__(self, addr=DEFAULT_ADDR): pass def Dump(self, _): pass def SetForeground(self): pass def GetSDKVersion(self): pass def GetDebugProfilingData(self): pass def GetScreenSize(self): pass def GetWindowRect(self): pass def KeyEvent(self, keycode): pass def Screenshot(self, width): pass def Click(self, x, y): pass def RClick(self, x, y): pass def DoubleClick(self, x, y): pass def Swipe(self, x1, y1, x2, y2, duration): pass def LongClick(self, x, y, duration, **kwargs): pass def Scroll(self, direction, percent, duration): pass def EnumWindows(self, selector): pass def ConnectWindowsByWindowTitle(self, selector, wlist): pass def ConnectWindowsByWindowTitleRe(self, selector, wlist): pass def ConnectWindowsByWindowTitle(self, selector, wlist): pass def run(self): pass
21
0
13
1
13
1
3
0.09
1
15
7
0
20
7
20
20
296
35
254
90
233
24
247
90
226
15
1
4
66
3,573
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/osx/osxui_poco.py
poco.drivers.osx.osxui_poco.OSXPoco
class OSXPoco(StdPoco): def __init__(self, selector=None, addr=DEFAULT_ADDR, **options): if 'action_interval' not in options: options['action_interval'] = 0.1 if addr[0] == "localhost" or addr[0] == "127.0.0.1": from poco.drivers.osx.sdk.OSXUI import PocoSDKOSX self.sdk = PocoSDKOSX(addr) self.SDKProcess = threading.Thread(target=self.sdk.run) # 创建线程 self.SDKProcess.setDaemon(True) self.SDKProcess.start() dev = VirtualDevice(addr[0]) super(OSXPoco, self).__init__(addr[1], dev, False, **options) self.selector = selector self.connect_window(self.selector) @sync_wrapper def connect_window(self, selector): return self.agent.rpc.call("ConnectWindow", selector) @sync_wrapper def set_foreground(self): return self.agent.rpc.call("SetForeground") def scroll(self, direction='vertical', percent=1, duration=2.0): # 重写Mac下的Scroll函数,percent代表滑动滚轮多少次,正数为向上滑,负数为向下滑 if direction not in ('vertical', 'horizontal'): raise ValueError('Argument `direction` should be one of "vertical" or "horizontal". Got {}'.format(repr(direction))) return self.agent.input.scroll(direction, percent, duration) def rclick(self, pos): return self.agent.input.rclick(pos[0], pos[1]) def double_click(self, pos): return self.agent.input.double_click(pos[0], pos[1]) def keyevent(self, keyname): return self.agent.input.keyevent(keyname)
class OSXPoco(StdPoco): def __init__(self, selector=None, addr=DEFAULT_ADDR, **options): pass @sync_wrapper def connect_window(self, selector): pass @sync_wrapper def set_foreground(self): pass def scroll(self, direction='vertical', percent=1, duration=2.0): pass def rclick(self, pos): pass def double_click(self, pos): pass def keyevent(self, keyname): pass
10
0
4
0
4
0
1
0.07
1
5
2
0
7
3
7
38
41
10
30
15
19
2
28
13
19
3
4
1
10
3,574
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/netease/internal.py
poco.drivers.netease.internal.NeteasePocoAgent
class NeteasePocoAgent(PocoAgent): def __init__(self, hunter): client = hunter.rpc client.set_timeout(25) remote_poco = client.remote('poco-uiautomation-framework-2') # hierarchy dumper = remote_poco.dumper selector = remote_poco.selector attributor = remote_poco.attributor hierarchy = RemotePocoHierarchy(dumper, selector, attributor) # input input = AirtestInput() # screen screen = AirtestScreen() # command command = HunterCommand(hunter) super(NeteasePocoAgent, self).__init__(hierarchy, input, screen, command) self._rpc_client = client
class NeteasePocoAgent(PocoAgent): def __init__(self, hunter): pass
2
0
22
5
13
4
1
0.29
1
5
4
0
1
1
1
7
23
5
14
11
12
4
14
11
12
1
2
0
1
3,575
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/netease/internal.py
poco.drivers.netease.internal.NeteasePoco
class NeteasePoco(Poco): def __init__(self, process, hunter=None, **options): if hunter: self._hunter = hunter else: apitoken = open_platform.get_api_token(process) self._hunter = AirtestHunter(apitoken, process) agent = NeteasePocoAgent(self._hunter) super(NeteasePoco, self).__init__(agent, **options) self._last_proxy = None self.screenshot_each_action = False if 'screenshot_each_action' in options: self.screenshot_each_action = options['screenshot_each_action'] def on_pre_action(self, action, ui, args): if self.screenshot_each_action: # airteset log用 from airtest.core.api import snapshot msg = repr(ui) if not isinstance(msg, six.text_type): msg = msg.decode('utf-8') snapshot(msg=msg)
class NeteasePoco(Poco): def __init__(self, process, hunter=None, **options): pass def on_pre_action(self, action, ui, args): pass
3
0
10
0
10
1
3
0.05
1
2
1
0
2
3
2
32
22
1
20
10
16
1
19
10
15
3
3
2
6
3,576
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/cocosjs/__init__.py
poco.drivers.cocosjs.Dumper
class Dumper(FrozenUIDumper): def __init__(self, rpcclient): super(Dumper, self).__init__() self.rpcclient = rpcclient @sync_wrapper def dumpHierarchy(self, onlyVisibleNode=True): # NOTE: cocosjs 的driver里,这个rpc方法名首字母是小写,特别注意! return self.rpcclient.call("dump", onlyVisibleNode)
class Dumper(FrozenUIDumper): def __init__(self, rpcclient): pass @sync_wrapper def dumpHierarchy(self, onlyVisibleNode=True): pass
4
0
3
0
3
1
1
0.14
1
1
0
0
2
1
2
9
9
1
7
5
3
1
6
4
3
1
4
0
2
3,577
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/cocosjs/test/simple.py
poco.drivers.cocosjs.test.simple.SimpleTest
class SimpleTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.poco = CocosJsPoco("ws://localhost:15003") @classmethod def tearDownClass(cls): time.sleep(1) def test_dump(self): print(self.poco.agent.hierarchy.dump())
class SimpleTest(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_dump(self): pass
6
0
2
0
2
0
1
0
1
1
1
0
1
0
3
75
11
2
9
6
3
0
7
4
3
1
2
0
3
3,578
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/ios/__init__.py
poco.drivers.ios.iosDumper
class iosDumper(FrozenUIDumper): def __init__(self, client): super(iosDumper, self).__init__() self.client = client self.size = client.display_info["window_width"], client.display_info["window_height"] def dumpHierarchy(self, onlyVisibleNode=True): # 当使用了appium/WebDriverAgent时,ipad横屏且在桌面下,坐标需要按照竖屏坐标额外转换一次 # 判断条件如下: # 当ios.using_ios_tagent有值、且为false,说明使用的是appium/WebDriverAgent # airtest<=1.2.4时,没有ios.using_ios_tagent的值,说明也是用的appium/wda if ((hasattr(self.client, "using_ios_tagent") and not self.client.using_ios_tagent) or (not hasattr(self.client, "using_ios_tagent"))) \ and (self.client.is_pad and self.client.orientation != 'PORTRAIT' and self.client.home_interface()): switch_flag = True else: switch_flag = False jsonObj = self.client.driver.source(format='json') w, h = self.size if self.client.orientation in ['LANDSCAPE', 'UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT']: w, h = h, w data = json_parser(jsonObj, (w, h), switch_flag=switch_flag, ori=self.client.orientation) return data def dumpHierarchy_xml(self): xml = self.client.driver.source() xml = xml.encode("utf-8") data = ios_dump_xml(xml, self.size) return data
class iosDumper(FrozenUIDumper): def __init__(self, client): pass def dumpHierarchy(self, onlyVisibleNode=True): pass def dumpHierarchy_xml(self): pass
4
0
9
0
7
1
2
0.17
1
1
0
0
3
2
3
10
30
3
23
12
19
4
20
12
16
3
4
1
5
3,579
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/android/uiautomation.py
poco.drivers.android.uiautomation.ScreenWrapper
class ScreenWrapper(ScreenInterface): def __init__(self, screen): super(ScreenWrapper, self).__init__() self.screen = screen def getScreen(self, width): # Android上PocoService的实现为仅返回b64编码的图像,格式固定位jpg b64img = self.screen.getScreen(width) return b64img, 'jpg' def getPortSize(self): return self.screen.getPortSize()
class ScreenWrapper(ScreenInterface): def __init__(self, screen): pass def getScreen(self, width): pass def getPortSize(self): pass
4
0
3
0
3
0
1
0.11
1
1
0
0
3
1
3
5
12
2
9
6
5
1
9
6
5
1
2
0
3
3,580
AirtestProject/Poco
AirtestProject_Poco/test/body.py
test.body.Case
class Case(PocoTestCase): @classmethod def setUpClass(cls): super(Case, cls).setUpClass() if not current_device(): connect_device('Android:///') def runTest(self): from poco.drivers.cocosjs import CocosJsPoco poco = CocosJsPoco() for n in poco(): print(n.get_name())
class Case(PocoTestCase): @classmethod def setUpClass(cls): pass def runTest(self): pass
4
0
5
0
5
0
2
0
1
2
1
0
1
0
2
2
12
1
11
6
6
0
10
5
6
2
1
1
4
3,581
AirtestProject/Poco
AirtestProject_Poco/poco/utils/track.py
poco.utils.track.MotionTrackHold
class MotionTrackHold(object): def __init__(self, how_long): super(MotionTrackHold, self).__init__() self.how_long = how_long
class MotionTrackHold(object): def __init__(self, how_long): pass
2
0
3
0
3
0
1
0
1
1
0
0
1
1
1
1
4
0
4
3
2
0
4
3
2
1
1
0
1
3,582
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/std/test/simple.py
poco.drivers.std.test.simple.TestStandardFunction
class TestStandardFunction(unittest.TestCase): @classmethod def setUpClass(cls): # u3d game 默认5001 # cocos2dx-lua 默认15004 connect_device('Android:///') # connect_device('Windows:///?class_name=UnityWndClass&title_re=Unity.*') cls.poco = StdPoco(15004) @classmethod def tearDownClass(cls): time.sleep(1) def test_dump(self): h = self.poco.agent.hierarchy.dump() s = json.dumps(h, indent=4) print(s) self.assertNotIn('"visible": false', s) def test_dump_include_invisible_node(self): h = self.poco.agent.hierarchy.dumper.dumpHierarchy(onlyVisibleNode=False) # .hierarchy是FrozenUIHierarchy s = json.dumps(h, indent=4) print(s) self.assertIn('"visible": false', s) def test_getSdkVersion(self): print(self.poco.agent.get_sdk_version()) def test_no_such_rpc_method(self): @sync_wrapper def wrapped(*args, **kwargs): return self.poco.agent.c.call('no_such_method') with self.assertRaises(RemoteError): wrapped() try: wrapped() except: traceback.print_exc() def test_get_screen(self): b64img, fmt = self.poco.snapshot() with open('screen.{}'.format(fmt), 'wb') as f: f.write(base64.b64decode(b64img)) def test_get_screen_size(self): print(self.poco.get_screen_size()) def test_motion_events(self): ui = self.poco()[0] ui.click() time.sleep(0.5) ui.long_click() time.sleep(0.5) ui.swipe([0.1, 0.1]) def test_set_text(self): textval = 'hello 中国!' node = self.poco(typeMatches='TextField|InputField|EditBox') node.set_text(textval) node.invalidate() actualVal = node.get_text() or node.offspring(text=textval).get_text() print(repr(actualVal)) self.assertEqual(actualVal, textval) def test_clear_text(self): node = self.poco(typeMatches='TextField|InputField|EditBox') node.set_text('val2333') node.set_text('') node.invalidate() actual_val = node.get_text() if actual_val is None: actual_val = node.offspring(text='').get_text() self.assertEqual(actual_val, '') def test_instanceId(self): for n in self.poco(): instance_id = n.attr('_instanceId') if instance_id: print(instance_id)
class TestStandardFunction(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_dump(self): pass def test_dump_include_invisible_node(self): pass def test_getSdkVersion(self): pass def test_no_such_rpc_method(self): pass @sync_wrapper def wrapped(*args, **kwargs): pass def test_get_screen(self): pass def test_get_screen_size(self): pass def test_motion_events(self): pass def test_set_text(self): pass def test_clear_text(self): pass def test_instanceId(self): pass
17
0
5
0
5
0
1
0.06
1
2
2
2
10
0
12
84
80
12
65
31
48
4
62
27
48
3
2
2
17
3,583
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/std/__init__.py
poco.drivers.std.StdPocoAgent
class StdPocoAgent(PocoAgent): def __init__(self, addr=DEFAULT_ADDR, use_airtest_input=True): self.conn = TcpClient(addr) self.c = RpcClient(self.conn) self.c.DEBUG = False self.c.connect() hierarchy = FrozenUIHierarchy(StdDumper(self.c), StdAttributor(self.c)) screen = StdScreen(self.c) if use_airtest_input: inputs = AirtestInput() else: inputs = StdInput(self.c) super(StdPocoAgent, self).__init__(hierarchy, inputs, screen, None) @property def rpc(self): return self.c @sync_wrapper def get_debug_profiling_data(self): return self.c.call("GetDebugProfilingData") @sync_wrapper def get_sdk_version(self): return self.c.call('GetSDKVersion')
class StdPocoAgent(PocoAgent): def __init__(self, addr=DEFAULT_ADDR, use_airtest_input=True): pass @property def rpc(self): pass @sync_wrapper def get_debug_profiling_data(self): pass @sync_wrapper def get_sdk_version(self): pass
8
0
5
0
5
0
1
0
1
9
8
0
4
2
4
10
26
4
22
13
14
0
18
10
13
2
2
1
5
3,584
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/std/inputs.py
poco.drivers.std.inputs.StdInput
class StdInput(InputInterface): def __init__(self, client): super(StdInput, self).__init__() self.client = client # 根据需要修改构造函数的签名 # 并修改对应的调用处 @sync_wrapper def click(self, x, y): return self.client.call("Click", x, y) @sync_wrapper def swipe(self, x1, y1, x2, y2, duration): return self.client.call("Swipe", x1, y1, x2, y2, duration) @sync_wrapper def longClick(self, x, y, duration): return self.client.call("LongClick", x, y, duration) @sync_wrapper def keyevent(self, keycode): return self.client.call("KeyEvent", keycode) @sync_wrapper def scroll(self, direction='vertical', percent=1, duration=2.0): return self.client.call("Scroll", direction, percent, duration) @sync_wrapper def rclick(self, x, y): return self.client.call("RClick", x, y) @sync_wrapper def double_click(self, x, y): return self.client.call("DoubleClick", x, y)
class StdInput(InputInterface): def __init__(self, client): pass @sync_wrapper def click(self, x, y): pass @sync_wrapper def swipe(self, x1, y1, x2, y2, duration): pass @sync_wrapper def longClick(self, x, y, duration): pass @sync_wrapper def keyevent(self, keycode): pass @sync_wrapper def scroll(self, direction='vertical', percent=1, duration=2.0): pass @sync_wrapper def rclick(self, x, y): pass @sync_wrapper def double_click(self, x, y): pass
16
0
2
0
2
0
1
0.08
1
1
0
0
8
1
8
16
34
7
25
17
9
2
18
10
9
1
2
0
8
3,585
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/std/screen.py
poco.drivers.std.screen.StdScreen
class StdScreen(ScreenInterface): def __init__(self, client): super(StdScreen, self).__init__() self.client = client @sync_wrapper def _getScreen(self, width): return self.client.call("Screenshot", width) def getScreen(self, width): b64, fmt = self._getScreen(width) if fmt.endswith('.deflate'): fmt = fmt[:-len('.deflate')] imgdata = base64.b64decode(b64) imgdata = zlib.decompress(imgdata) b64 = base64.b64encode(imgdata) return b64, fmt @sync_wrapper def getPortSize(self): return self.client.call("GetScreenSize")
class StdScreen(ScreenInterface): def __init__(self, client): pass @sync_wrapper def _getScreen(self, width): pass def getScreen(self, width): pass @sync_wrapper def getPortSize(self): pass
7
0
4
0
4
0
1
0
1
1
0
0
4
1
4
6
21
3
18
10
11
0
16
8
11
2
2
1
5
3,586
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/ue4/ue4_poco.py
poco.drivers.ue4.ue4_poco.UE4Poco
class UE4Poco(StdPoco): def __init__(self, addr=DEFAULT_ADDR, ue4_editor=False, connect_default_device=True, device=None, **options): if 'action_interval' not in options: options['action_interval'] = 0.5 if ue4_editor: dev = UE4EditorWindow() else: dev = device or current_device() if dev is None and connect_default_device and not current_device(): dev = connect_device("Android:///") super(UE4Poco, self).__init__(addr[1], dev, ip=addr[0], **options)
class UE4Poco(StdPoco): def __init__(self, addr=DEFAULT_ADDR, ue4_editor=False, connect_default_device=True, device=None, **options): pass
2
0
13
3
10
0
4
0
1
1
0
0
1
0
1
32
15
4
11
3
9
0
10
3
8
4
4
1
4
3,587
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/test.py
poco.drivers.unity3d.test.test.TestU3dDriverAndroid
class TestU3dDriverAndroid(TestStandardFunction): @classmethod def setUpClass(cls): connect_device('Android:///') cls.poco = UnityPoco()
class TestU3dDriverAndroid(TestStandardFunction): @classmethod def setUpClass(cls): pass
3
0
3
0
3
0
1
0
1
1
1
0
0
0
1
85
5
0
5
3
2
0
4
2
2
1
3
0
1
3,588
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/std/__init__.py
poco.drivers.std.StdPoco
class StdPoco(Poco): """ Poco standard implementation for PocoSDK protocol. Args: port (:py:obj:`int`): the port number of the server that listens on the target device. default to 15004. device (:py:obj:`Device`): :py:obj:`airtest.core.device.Device` instance provided by ``airtest``. leave the parameter default and the default device will be chosen. more details refer to ``airtest doc`` options: see :py:class:`poco.pocofw.Poco` Examples: The simplest way to connect to a cocos2dx-lua game:: from poco.drivers.std import StdPoco from airtest.core.api import connect_device # connect a device first, then initialize poco object device = connect_device('Android:///') poco = StdPoco(10054, device) # or use ip:port to initialize poco object poco = StdPoco(port=10054, ip='xx.xx.xx.xx') # now you can play with poco ui = poco('...') ui.click() ... """ def __init__(self, port=DEFAULT_PORT, device=None, use_airtest_input=True, ip=None, **kwargs): if ip is None or ip == "localhost": self.device = device or default_device() platform_name = device_platform(self.device) if platform_name == 'Android': # always forward for android device to avoid network unreachable local_port, _ = self.device.adb.setup_forward('tcp:{}'.format(port)) ip = self.device.adb.host or 'localhost' port = local_port elif platform_name == 'IOS': port, _ = self.device.setup_forward(port) if self.device.is_local_device: ip = 'localhost' else: ip = self.device.ip else: try: ip = self.device.get_ip_address() except AttributeError: try: ip = socket.gethostbyname(socket.gethostname()) except socket.gaierror: # 某些特殊情况下会出现这个error,无法正确获取本机ip地址 ip = 'localhost' agent = StdPocoAgent((ip, port), use_airtest_input) kwargs['reevaluate_volatile_attributes'] = True super(StdPoco, self).__init__(agent, **kwargs)
class StdPoco(Poco): ''' Poco standard implementation for PocoSDK protocol. Args: port (:py:obj:`int`): the port number of the server that listens on the target device. default to 15004. device (:py:obj:`Device`): :py:obj:`airtest.core.device.Device` instance provided by ``airtest``. leave the parameter default and the default device will be chosen. more details refer to ``airtest doc`` options: see :py:class:`poco.pocofw.Poco` Examples: The simplest way to connect to a cocos2dx-lua game:: from poco.drivers.std import StdPoco from airtest.core.api import connect_device # connect a device first, then initialize poco object device = connect_device('Android:///') poco = StdPoco(10054, device) # or use ip:port to initialize poco object poco = StdPoco(port=10054, ip='xx.xx.xx.xx') # now you can play with poco ui = poco('...') ui.click() ... ''' def __init__(self, port=DEFAULT_PORT, device=None, use_airtest_input=True, ip=None, **kwargs): pass
2
1
29
2
25
2
7
0.88
1
3
1
5
1
1
1
31
59
10
26
6
24
23
23
6
21
7
3
4
7
3,589
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/qt/__init__.py
poco.drivers.qt.QtPoco
class QtPoco(StdPoco): """ Poco Qt implementation. """ def __init__(self, addr=DEFAULT_ADDR, **options): dev = VirtualDevice(addr[0]) super(QtPoco, self).__init__(addr[1], dev, **options)
class QtPoco(StdPoco): ''' Poco Qt implementation. ''' def __init__(self, addr=DEFAULT_ADDR, **options): pass
2
1
3
0
3
0
1
0.75
1
2
1
0
1
0
1
32
8
1
4
3
2
3
4
3
2
1
4
0
1
3,590
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/test.py
poco.drivers.unity3d.test.test.TestU3dDriverUnityEditor
class TestU3dDriverUnityEditor(TestStandardFunction): @classmethod def setUpClass(cls): cls.poco = UnityPoco(unity_editor=True)
class TestU3dDriverUnityEditor(TestStandardFunction): @classmethod def setUpClass(cls): pass
3
0
2
0
2
0
1
0
1
1
1
0
0
0
1
85
4
0
4
3
1
0
3
2
1
1
3
0
1
3,591
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/std/attributor.py
poco.drivers.std.attributor.StdAttributor
class StdAttributor(Attributor): def __init__(self, client): super(StdAttributor, self).__init__() self.client = client def setAttr(self, node, attrName, attrVal): if attrName == 'text': if type(node) in (list, tuple): node = node[0] instance_id = node.getAttr('_instanceId') if instance_id: success = self.client.call('SetText', instance_id, attrVal) if success: return True raise UnableToSetAttributeException(attrName, node)
class StdAttributor(Attributor): def __init__(self, client): pass def setAttr(self, node, attrName, attrVal): pass
3
0
7
0
7
0
3
0
1
5
1
0
2
1
2
4
15
1
14
6
11
0
14
6
11
5
2
3
6
3,592
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/buttons_and_labels.py
poco.drivers.unity3d.test.tutorial.buttons_and_labels.ButtonsAndLabelsTutorial
class ButtonsAndLabelsTutorial(TutorialCase): def runTest(self): self.poco('btn_start').click() self.poco(text='basic').click() star = self.poco('star_single') if star.exists(): pos = star.get_position() input_field = self.poco('pos_input') time.sleep(1) input_field.set_text('x={:.02f}, y={:.02f}'.format(*pos)) time.sleep(3) title = self.poco('title').get_text() if title == 'Basic test': self.poco('btn_back', type='Button').click() self.poco('btn_back', type='Button').click()
class ButtonsAndLabelsTutorial(TutorialCase): def runTest(self): pass
2
0
16
2
14
0
3
0
1
0
0
0
1
0
1
3
17
2
15
6
13
0
15
6
13
3
2
1
3
3,593
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/case.py
poco.drivers.unity3d.test.tutorial.case.TutorialCase
class TutorialCase(PocoTestCase): @classmethod def setUpClass(cls): from airtest.core.api import connect_device connect_device('Android:///') cls.poco = UnityPoco() action_tracker = ActionTracker(cls.poco) cls.register_addon(action_tracker) @classmethod def tearDownClass(cls): time.sleep(1)
class TutorialCase(PocoTestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass
5
0
5
1
4
0
1
0
1
1
1
16
0
0
2
2
13
2
11
7
5
0
9
5
5
1
1
0
2
3,594
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/click.py
poco.drivers.unity3d.test.tutorial.click.ClickTutorial
class ClickTutorial(TutorialCase): def runTest(self): self.poco('btn_start').click()
class ClickTutorial(TutorialCase): def runTest(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
3
0
3
2
1
0
3
2
1
1
2
0
1
3,595
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/drag.py
poco.drivers.unity3d.test.tutorial.drag.DragTutorial
class DragTutorial(TutorialCase): def runTest(self): self.poco('star').drag_to(self.poco('shell'))
class DragTutorial(TutorialCase): def runTest(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
3
0
3
2
1
0
3
2
1
1
2
0
1
3,596
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/exception1.py
poco.drivers.unity3d.test.tutorial.exception1.InvalidOperationExceptionTutorial
class InvalidOperationExceptionTutorial(TutorialCase): def runTest(self): try: self.poco.click([1.1, 1.1]) # click outside screen except InvalidOperationException: print('oops') time.sleep(1)
class InvalidOperationExceptionTutorial(TutorialCase): def runTest(self): pass
2
0
6
0
6
1
2
0.14
1
1
1
0
1
0
1
3
7
0
7
2
5
1
7
2
5
2
2
1
2
3,597
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/exception2.py
poco.drivers.unity3d.test.tutorial.exception2.InvalidOperationExceptionTutorial
class InvalidOperationExceptionTutorial(TutorialCase): def runTest(self): node = self.poco('not existed node') # select will never raise any exceptions try: node.click() except PocoNoSuchNodeException: print('oops!') time.sleep(1) try: node.attr('text') except PocoNoSuchNodeException: print('oops!') time.sleep(1) print(node.exists()) # => False. this method will not raise time.sleep(0.2)
class InvalidOperationExceptionTutorial(TutorialCase): def runTest(self): pass
2
0
16
2
14
2
3
0.13
1
1
1
0
1
0
1
3
17
2
15
3
13
2
15
3
13
3
2
1
3
3,598
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/exception3.py
poco.drivers.unity3d.test.tutorial.exception3.InvalidOperationExceptionTutorial
class InvalidOperationExceptionTutorial(TutorialCase): def runTest(self): # UI is very slow self.poco('btn_start').click() star = self.poco('star') try: star.wait_for_appearance(timeout=3) # wait until appearance within 3s except PocoTargetTimeout: print('oops!') time.sleep(1)
class InvalidOperationExceptionTutorial(TutorialCase): def runTest(self): pass
2
0
9
0
8
2
2
0.22
1
1
1
0
1
0
1
3
10
0
9
3
7
2
9
3
7
2
2
1
2
3,599
AirtestProject/Poco
AirtestProject_Poco/poco/drivers/unity3d/test/tutorial/frozen_ui.py
poco.drivers.unity3d.test.tutorial.frozen_ui.FrozenUITutorial
class FrozenUITutorial(TutorialCase): def using_freezing(self): with self.poco.freeze() as frozen_poco: t0 = time.time() for item in frozen_poco('Scroll View').offspring(type='Text'): print(item.get_text()) t1 = time.time() print(t1 - t0) def no_using_freezing(self): t0 = time.time() for item in self.poco('Scroll View').offspring(type='Text'): print(item.get_text()) t1 = time.time() print(t1 - t0) def runTest(self): self.using_freezing() self.no_using_freezing()
class FrozenUITutorial(TutorialCase): def using_freezing(self): pass def no_using_freezing(self): pass def runTest(self): pass
4
0
5
0
5
0
2
0
1
0
0
0
3
0
3
5
19
2
17
11
13
0
17
10
13
2
2
2
5