### Initializing Test Setup with Hunter and RPC in Python Source: https://github.com/airtestproject/poco/blob/master/doc/netease-internal-use-template.rst The `setUp` method is executed before each test method. This snippet demonstrates how to use `self.hunter.script` to execute remote commands and `self.hunter.rpc.remote` to obtain an RPC object for interacting with remote services, facilitating test environment setup or data retrieval. ```python def setUp(self): # 调用hunter指令可以这样写 self.hunter.script('print 23333', lang='python') # hunter rpc对象可以这样获取 remote_obj = self.hunter.rpc.remote('safaia-rpc-test') # see http://hunter.nie.netease.com/mywork/instruction?insids=3086 print(remote_obj.get_value()) ``` -------------------------------- ### Getting Poco SDK - Cloning Repository Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst First clone the poco-sdk repository. Each language's SDK is located separately within 'poco-sdk/sdk/*'. You can copy the source code of the corresponding language to your project script folder. ```bash git clone https://github.com/AirtestProject/Poco-SDK.git ``` -------------------------------- ### Setting up a SimpleRPC Server (Python) Source: https://github.com/airtestproject/poco/blob/master/poco/utils/simplerpc/README.md This snippet illustrates the basic setup for a SimpleRPC server. It shows how to instantiate an RpcServer, providing it with a chosen transport layer like TCP or SSZMQ, and then start the server to listen for incoming RPC requests. ```Python ### server from simplerpc.rpcserver import RpcServer from simplerpc.transport.tcp import TcpServer from simplerpc.transport.sszmq import SSZmqServer s = RpcServer(TcpServer()) # s = RpcServer(SSZmqServer()) s.run() ``` -------------------------------- ### Installing PocoUnit Framework with pip (Bash) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/play_with_unittest_framework.rst This snippet provides the command-line instruction to install the `pocounit` testing framework using pip, the Python package installer. It's a prerequisite for using `pocounit` in Python projects. ```bash pip install pocounit ``` -------------------------------- ### Installing Poco UI for Android Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/android-native-app.rst This command installs the Poco UI library, which is essential for interacting with Android native applications. It's the first step to set up the testing environment. ```bash pip install pocoui ``` -------------------------------- ### Performing a Click Operation - Poco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst This snippet executes a click action on the `start` UI element. This is a basic interaction to trigger an event associated with the element. ```Python start.click() ``` -------------------------------- ### Installing Poco Python Library (Bash) Source: https://github.com/airtestproject/poco/blob/master/README.rst This Bash command installs the `pocoui` Python library using `pip`. This library is the host-side component required to interact with the Poco SDK integrated into the target application, enabling UI automation. ```Bash pip install pocoui ``` -------------------------------- ### Installing Poco Python Library with pip (Bash) Source: https://github.com/airtestproject/poco/blob/master/DocBuilder/index.rst This snippet demonstrates how to install the Poco Python library using the pip package manager. This is the first step to set up Poco on your host machine, enabling you to write UI automation scripts. ```bash pip install pocoui ``` -------------------------------- ### Defining a TestFlow Poco Test Case in Python Source: https://github.com/airtestproject/poco/blob/master/doc/netease-internal-use-template.rst This snippet defines the `MyTestCase` class, inheriting from `CommonCase`, which is the standard structure for a `testflow` test. It encapsulates the entire test lifecycle, including setup, test execution, and teardown phases, providing a complete example of a UI automation test. ```python from testflow.lib.case.netease_case import CommonCase # 一个文件里建议就只有一个CommonCase # 一个Case做的事情尽量简单,不要把一大串操作都放到一起 class MyTestCase(CommonCase): def setUp(self): # 调用hunter指令可以这样写 self.hunter.script('print 23333', lang='python') # hunter rpc对象可以这样获取 remote_obj = self.hunter.rpc.remote('safaia-rpc-test') # see http://hunter.nie.netease.com/mywork/instruction?insids=3086 print(remote_obj.get_value()) def runTest(self): # 普通语句跟原来一样,但是必须都要用self开头,这是为了以后动态代理 self.poco(text='角色').click() # 断言语句跟python unittest写法一模一样 self.assertTrue(self.poco(text='最大生命').wait(3).exists(), "看到了最大生命") self.poco('btn_close').click() self.poco('movetouch_panel').offspring('point_img').swipe('up') self.assertTrue(False, '肯定错!') def tearDown(self): # 如果没有清场操作,这个函数就不用写出来 # 记得下面这句话是会报错的 a = 1 / 0 ``` -------------------------------- ### Installing Dependencies for OSX Poco SDK (Bash) Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/osx-app.rst This snippet shows how to install the necessary Python libraries, `pyatomac` and `pyautogui`, required to run the OSX Poco SDK. Xcode must be installed prior to these Python dependencies. ```bash pip install pyatomac pyautogui ``` -------------------------------- ### Implementing AbstractNode and AbstractDumper Classes - Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst To create a custom Poco SDK version, implement the AbstractNode and AbstractDumper classes/interfaces and override their abstract methods. This includes methods for getting parent/children, and managing attributes for nodes, and getting the root for the dumper. ```python class YourNode(AbstractNode): def __init__(self, yourElement): self.Element = yourElement def getParent(self): pass def getChildren(self): pass def getAttr(self, attrName): pass def setAttr(self, attrName, val): pass # Can override this function if needed def getAvailableAttributeNames(self): pass class YourDumper(AbstractDumper): def __init__(self, root): pass def getRoot(self): pass ``` -------------------------------- ### Initializing Poco SDK RPC Service - Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst After implementing basic functions, establish client-server communication using Poco's simple RPC service. Register all implemented functions with the RPC reactor and bind a TCP socket to a port to enable the RPC listening service. ```python from poco.sdk.std.rpc.controller import StdRpcEndpointController from poco.sdk.std.rpc.reactor import StdRpcReactor from poco.utils.net.transport.tcp import TcpSocket reactor = StdRpcReactor() reactor.register('Dump', Dump) reactor.register('Screenshot', Screenshot) reactor.register('Click', Click) reactor.register('Swipe', Swipe) reactor.register('LongClick', LongClick) # If you have implemented other functions, don't forget to register it. transport = TcpSocket() transport.bind(("localhost", 15004)) # Listening to a port rpc = StdRpcEndpointController(transport, reactor) rpc.serve_forever() # Enable RPC listening service and listen for messages sent by the client. ``` -------------------------------- ### Illustrating PocoTargetRemovedException Behavior in UnityPoco Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst This snippet provides context for PocoTargetRemovedException, specifically noting that in some poco-sdk implementations (like StdPoco), this exception might not be raised. It sets up a UnityPoco instance and selects a 'start' node, implying that the behavior of PocoTargetRemovedException can vary and requires careful existence checks. ```python # coding=utf-8 from poco.drivers.unity3d import UnityPoco from airtest.core.api import connect_device poco = UnityPoco() # no PocoTargetRemovedException case start = poco('start') ``` -------------------------------- ### Getting and Setting UI Attributes with Poco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/interact_with_buttons_and_labels.rst This example illustrates how to retrieve and modify attributes of UI elements using Poco. It covers getting an element's position, setting text in an input field, and retrieving text from a label, demonstrating conditional interactions and attribute manipulation. ```python # coding=utf-8 import time from poco.drivers.unity3d import UnityPoco poco = UnityPoco() poco('btn_start').click() poco(text='basic').click() star = poco('star_single') if star.exists(): pos = star.get_position() input_field = poco('pos_input') time.sleep(1) input_field.set_text('x={:.02f}, y={:.02f}'.format(*pos)) # very fast time.sleep(3) title = poco('title').get_text() if title == 'Basic test': back = poco('btn_back', type='Button') back.click() back.click() ``` -------------------------------- ### Repeating Click with Unity3D Behavior - Poco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst This snippet performs another click on the `start` element. A crucial note for Unity3D is that this operation will click the same coordinate as before, irrespective of the element's actual state or visibility. ```Python start.click() ``` -------------------------------- ### Configuring PocoSDK for NeoX Engine in Python Source: https://github.com/airtestproject/poco/blob/master/doc/integration.rst This Python snippet configures PocoSDK for the NeoX engine by appending it to the Hunter __init__ instruction. It installs the core Safaia module, integrates the Poco UI automation module specific to NeoX, and sets up the inspector extension with screen and dumper handlers for debugging and interaction. ```python # core (add only if not present) Safaia().install(require('safaia.init.core')) # poco uiautomation PocoUiautomation = require('support.poco.neox.uiautomation') Safaia().install(PocoUiautomation) # inspector extension screen_handler = require('support.poco.neox.screen')() InspectorExt = require('support.poco.safaia.inspector') InspectorExt.screen = screen_handler InspectorExt.dumper = require('support.poco.neox.Dumper')() Safaia().install(InspectorExt) ``` -------------------------------- ### Implementing a PocoUnit Test Case for In-Game Shop (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/play_with_unittest_framework.rst This comprehensive Python snippet demonstrates how to create a `pocounit` test case (`TestBuyShopItem`) for automating interactions with an in-game shop. It includes `setUpClass` for Poco initialization and addon registration, `setUp` for test preparation (e.g., granting resources, clearing limits, navigating to the shop), `runTest` for the core logic of buying all available items and verifying inventory, and `tearDown` for cleanup. It utilizes Poco for UI automation and `pocounit` for assertions and test structure. ```python # coding=utf-8 import time from pocounit.case import PocoTestCase from pocounit.addons.poco.action_tracking import ActionTracker from pocounit.addons.hunter.runtime_logging import AppRuntimeLogging class CommonCase(PocoTestCase): @classmethod def setUpClass(cls): super(CommonCase, cls).setUpClass() cls.poco = Poco(...) action_tracker = ActionTracker(cls.poco) cls.register_addon(action_tracker) class TestBuyShopItem(CommonCase): """ 去商城里把所有的道具都买一遍,验证所有道具都可以购买 """ def setUp(self): # 准备好足够的水晶和背包空间 self.poco.command('***********') self.poco.command('***************************') # 清除掉每日购买次数限制 self.poco.command('**********') # 打开商店界面 if not self.poco('entry_list').exists(): self.poco('switch_mode_btn').click() self.poco(text='商店').click() self.poco(textMatches='.*常规补给物资.*').click() def runTest(self): # 先买 bought_items = set() bought_new = True while bought_new: bought_new = False for item in self.poco('main_node').child('list_item').offspring('name'): item_name = item.get_text() # 已经买过的就不再买了 if item_name not in bought_items: item.click() self.poco(text='购买').click() bought_items.add(item_name) bought_new = True item.click() # 向上卷动 if bought_new: item_list = self.poco('main_node').child('list_item').child('list') item_list.focus([0.5, 0.8]).drag_to(item_list.focus([0.5, 0.25])) self.poco.dismiss([self.poco('btn_close')]) # 再去背包验证 self.poco('btn_bag').click() time.sleep(2) item_count = len(self.poco('bag_node').child('list').offspring('obj_frame_spr')) self.assertEqual(item_count, len(bought_items), '购买道具总数量验证') def tearDown(self): # 关掉界面 self.poco.dismiss([self.poco('btn_close')]) if __name__ == '__main__': import pocounit pocounit.main() ``` -------------------------------- ### Initializing Poco for UnityEditor on Windows Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/unity3d.rst This example shows how to initialize a Poco instance for debugging Unity games directly within the UnityEditor. It uses `poco.drivers.unity3d.device.UnityEditorWindow` to specify the device object and connects to the Poco SDK component running on the default port 5001. ```Python # import unity poco driver from this path from poco.drivers.unity3d import UnityPoco from poco.drivers.unity3d.device import UnityEditorWindow # specify to work on UnityEditor in this way dev = UnityEditorWindow() # make sure your poco-sdk component listens on the following port. # default value will be 5001. change to any other if your like. # IP is not used for now addr = ('', 5001) # then initialize the poco instance in the following way # specifying the device object poco = UnityPoco(addr, device=dev) # now you can play with poco ui = poco('...') ui.click() ``` -------------------------------- ### Configuring PocoSDK for Messiah Engine in Python Source: https://github.com/airtestproject/poco/blob/master/doc/integration.rst This Python snippet configures PocoSDK for the Messiah engine, to be appended to the Hunter __init__ instruction. It installs the core Safaia module, integrates the Poco UI automation module specific to Messiah, and sets up the inspector extension with screen and dumper handlers for debugging and interaction. ```python # core (add only if not present) Safaia().install(require('safaia.init.core')) # poco uiautomation PocoUiautomation = require('support.poco.messiah.uiautomation') Safaia().install(PocoUiautomation) # inspector extension screen_handler = require('support.poco.messiah.screen')() InspectorExt = require('support.poco.safaia.inspector') InspectorExt.screen = screen_handler InspectorExt.dumper = require('support.poco.cocos2dx.Dumper')() Safaia().install(InspectorExt) ``` -------------------------------- ### Checking Initial Element Existence - Poco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst This snippet uses `start.exists()` to verify if a UI element is present before any interaction. It prints the boolean result, expected to be `True` initially. ```Python print(start.exists()) # => True. ``` -------------------------------- ### Starting ADB Server for Android Native Apps - Shell Source: https://github.com/airtestproject/poco/blob/master/doc/about-standalone-inspector.rst This command is used to manually start the ADB (Android Debug Bridge) server. It is required on some systems if the ADB server does not start automatically when an Android device is plugged in, ensuring the hierarchy viewer can properly communicate with the device. ```Shell adb start-server ``` -------------------------------- ### Initializing Poco for Unity3D Applications (Python) Source: https://github.com/airtestproject/poco/blob/master/README.rst This Python snippet shows how to set up a Poco instance specifically for automating Unity3D applications. It imports `UnityPoco` and creates an object, ready for UI element selection and interaction. A commented line provides an example for connecting to a Unity editor. ```Python from poco.drivers.unity3d import UnityPoco poco = UnityPoco() # for unity editor on windows # poco = UnityPoco(('localhost', 5001), unity_editor=True) ui = poco('...') ui.click() ``` -------------------------------- ### Running PocoUnit Test Script in Python Source: https://github.com/airtestproject/poco/blob/master/doc/netease-internal-use-template.rst This standard Python `if __name__ == '__main__':` block serves as the entry point for executing the test script. It imports `pocounit` and calls `pocounit.main()`, which discovers and runs the defined test cases within the file. ```python if __name__ == '__main__': import pocounit pocounit.main() ``` -------------------------------- ### Executing a TestFlow Script via Bash Source: https://github.com/airtestproject/poco/blob/master/doc/netease-internal-use-template.rst This snippet provides the command-line instruction to run the Python `testflow` script. It demonstrates how to invoke the test file directly using the `python` interpreter from a bash shell, initiating the test execution. ```bash python testflow/scripts/test1.py ``` -------------------------------- ### Handling PocoNoSuchNodeException for Non-Existent Nodes Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst This example illustrates how to handle PocoNoSuchNodeException when attempting to interact with a UI node that does not exist. It demonstrates catching the exception for both click and attribute access operations, and also shows the use of the .exists() method to check for node presence without raising an exception. ```python # coding=utf-8 from poco.drivers.unity3d import UnityPoco from poco.exceptions import PocoNoSuchNodeException poco = UnityPoco() node = poco('not existed node') # select will never raise any exceptions try: node.click() except PocoNoSuchNodeException: print('oops!') try: node.attr('text') except PocoNoSuchNodeException: print('oops!') print(node.exists()) # => False. this method will not raise ``` -------------------------------- ### Iterating Over a Collection of Poco UI Objects (Python) Source: https://github.com/airtestproject/poco/blob/master/README.rst Demonstrates how to iterate through a collection of selected UI objects. This allows processing each item individually, for example, to interact with its children or retrieve its properties. ```Python # traverse through every item items = poco('main_node').child('list_item').offspring('item') for item in items: item.child('icn_item') ``` -------------------------------- ### Getting Root UI Element for Poco Dumper in Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst This function, part of `AbstractDumper`, is responsible for returning the root UI surface of the device. It's crucial for Poco to traverse the UI hierarchy and access properties of child elements using overridden `getChildren` and `getAttr` functions. ```python def getRoot(self): return YourNode(YourAPI.GetRootElement()) ``` -------------------------------- ### Testing Multiple Windows Simultaneously with WindowsPoco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/windows-app.rst This example illustrates how to simultaneously test multiple Windows applications by creating distinct `WindowsPoco` instances, each configured to target a different window using unique regular expressions and local port assignments. It demonstrates interacting with elements in each separate window, such as setting text, highlighting Poco's capability to manage concurrent UI automation tasks. ```Python from poco.drivers.windows import WindowsPoco # import time poco1 = WindowsPoco({"title_re": "[0-9][0-9][0-9]"}, ("localhost", 10086)) poco2 = WindowsPoco({"title_re": "[a][b][c]"}, ("localhost", 10087)) poco1("文本编辑器").set_text("this is window 123") poco2("文本编辑器").set_text("this is window abc") time.sleep(1) # wait for the server to finish processing and exit gracefully ``` -------------------------------- ### Implementing Screenshot Function - Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst If needed, implement this function to allow Poco to capture screenshots. The function should return a list containing a base64 encoded string of the screenshot and its format (e.g., 'bmp'). ```python def Screenshot(self, width): return [base64.b64encode(YourAPI.GetScreenshot(width)), "bmp"] ``` -------------------------------- ### Automating Unity3D Game UI with Poco (Python) Source: https://github.com/airtestproject/poco/blob/master/README.rst This Python snippet demonstrates a comprehensive UI automation flow for a Unity3D game using Poco. It initializes `UnityPoco`, simulates user interactions like clicking a start button, dragging multiple 'star' elements to a 'shell', and validating a score. This requires an Android device connected via USB with ADB debug mode enabled. ```Python # coding=utf-8 import time from poco.drivers.unity3d import UnityPoco poco = UnityPoco() poco('btn_start').click() time.sleep(1.5) shell = poco('shell').focus('center') for star in poco('star'): star.drag_to(shell) time.sleep(1) assert poco('scoreVal').get_text() == "100", "score correct." poco('btn_back', type='Button').click() ``` -------------------------------- ### Initializing Poco for Unity3D on Specific Android Device Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/unity3d.rst This example shows how to initialize a Poco instance when multiple Android devices are connected. It uses `airtest.core.api.connect_device` to select a specific device by serial number and specifies the Poco SDK listening port (default 5001) for the connection. ```Python # import unity poco driver from this path from poco.drivers.unity3d import UnityPoco from airtest.core.api import connect_device # select one of your android device first by given serialno dev = connect_device('Android:///') # make sure your poco-sdk in the game runtime listens on the following port. # default value will be 5001 # IP is not used for now addr = ('', 5001) # then initialize the poco instance in the following way # specifying the device object poco = UnityPoco(addr, device=dev) # now you can play with poco ui = poco('...') ui.click() ``` -------------------------------- ### Performing UI Interactions with OSXPoco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/osx-app.rst This example illustrates how to perform a UI interaction, specifically a click, on an element within a MacOS application using an initialized `OSXPoco` instance. It first initializes Poco by finding a window matching a regular expression for the app name, then locates and clicks a UI control named '通用'. ```python from poco.drivers.osx.osxui_poco import OSXPoco poco = OSXPoco({"appname_re": "系统偏好", "windowindex": 0}) poco("通用").click() ``` -------------------------------- ### Initializing PocoSDK in Cocos Creator Source: https://github.com/airtestproject/poco/blob/master/doc/integration.rst This code snippet shows how to integrate and initialize PocoSDK within a Cocos Creator component's onLoad function. It requires the Poco module using a relative path, instantiates it, and assigns the instance to window.poco to ensure its persistence and availability throughout the game. ```javascript cc.Class({ extends: cc.Component, ..... //remember to put code in onLoad function onLoad: function () { ..... var poco = require("./Poco") // use your own relative path window.poco = new poco(); // not destroy cc.log(window.poco); }, ..... }); ``` -------------------------------- ### Performing Basic UI Interactions with WindowsPoco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/windows-app.rst This snippet provides a practical example of performing various UI interactions within a Windows application using an initialized `WindowsPoco` instance. It showcases common automation actions like clicking at specific coordinates within a UI element, dragging an element from one point to another, and performing a swipe gesture, demonstrating how to simulate user input for testing purposes. ```Python from poco.drivers.windows import WindowsPoco poco = WindowsPoco({"title_re": ".+?画图$"}) for p in range(1, 10): poco("Pane").child("Pane").click([0.2, p / 10.0]) poco("Pane").child("Pane").click() # will draw a point in the middle poco("Pane").child("Pane").focus([0.25, 0.25]).drag_to([0.5, 0.7]) poco("Pane").child("Pane").focus([0.7, 0.7]).swipe([-0.1, 0.1]) ``` -------------------------------- ### Verifying Element Disappearance After Click - Poco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst After a click, this snippet re-checks the element's existence using `start.exists()`. It prints the result, which is expected to be `False` if the element is consumed or removed by the click. ```Python print(start.exists()) # => False ``` -------------------------------- ### Copying WebSocketServer Modules for Cocos2dx-js Source: https://github.com/airtestproject/poco/blob/master/doc/integration.rst This bash script copies the necessary WebSocketServer module files and their source to the Cocos2dx-js project directory. This step is crucial because WebSocketServer is part of the cocos2dx framework but not included by default, enabling its functionality for PocoSDK. ```bash cp -r cocos2dx-js/3rd/websockets /frameworks/cocos2d-x/external/websockets cp cocos2dx-js/3rd/src/* /frameworks/runtime-src/Classes ``` -------------------------------- ### Retrieving Properties of Poco UI Objects (Python) Source: https://github.com/airtestproject/poco/blob/master/README.rst Illustrates how to obtain various properties of a selected UI object. Examples include retrieving the `type` attribute, the displayed text using `get_text()` or `attr('text')`, and checking the object's existence on the screen with `exists()`. ```Python mission_btn = poco('bg_mission') print(mission_btn.attr('type')) # 'Button' print(mission_btn.get_text()) # '据点支援' print(mission_btn.attr('text')) # '据点支援' equivalent to .get_text() print(mission_btn.exists()) # True/False, exists in the screen or not ``` -------------------------------- ### Executing UI Test Logic with Poco and Assertions in Python Source: https://github.com/airtestproject/poco/blob/master/doc/netease-internal-use-template.rst The `runTest` method contains the primary test logic. It illustrates using `self.poco` for UI interactions like clicking elements and performing swipes, and demonstrates standard `unittest`-style assertions (`self.assertTrue`) to validate the state of UI elements. All operations must be prefixed with `self` for dynamic proxying. ```python def runTest(self): # 普通语句跟原来一样,但是必须都要用self开头,这是为了以后动态代理 self.poco(text='角色').click() # 断言语句跟python unittest写法一模一样 self.assertTrue(self.poco(text='最大生命').wait(3).exists(), "看到了最大生命") self.poco('btn_close').click() self.poco('movetouch_panel').offspring('point_img').swipe('up') self.assertTrue(False, '肯定错!') ``` -------------------------------- ### Modifying AppDelegate.cpp for Cocos2dx-js WebSocketServer Source: https://github.com/airtestproject/poco/blob/master/doc/integration.rst This C++ snippet illustrates the required modifications to 'AppDelegate.cpp' in a Cocos2dx-js project. It includes the 'jsb_websocketserver.h' header and registers the 'register_jsb_websocketserver' callback, which is essential for integrating the WebSocketServer module with the JavaScript bindings. ```cpp // include it at top #include "jsb_websocketserver.h" // register callbacks of websocketserver sc->addRegisterCallback(register_jsb_websocketserver); ``` -------------------------------- ### Performing Scroll Operation in Poco ScrollView (Python) Source: https://github.com/airtestproject/poco/blob/master/README.rst Demonstrates how to perform a scroll operation on a `ScrollView` element using `focus` to define start and end points. The `drag_to` method simulates the scroll action between these points. ```Python scrollView = poco(type='ScollView') scrollView.focus([0.5, 0.8]).drag_to(scrollView.focus([0.5, 0.2])) ``` -------------------------------- ### Connecting to a Specific Android Device with Poco Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/android-native-app.rst This example shows how to connect to a specific Android device using its serial number before initializing Poco. It ensures that Poco operates on the intended device when multiple devices are connected. ```python from poco.drivers.android.uiautomation import AndroidUiautomationPoco from airtest.core.api import connect_device connect_device('Android://014E05DE0F02000E/') # connect device first by serialno. poco = AndroidUiautomationPoco() poco.device.wake() ``` -------------------------------- ### Initializing PocoSDK in Cocos2dx-JS Source: https://github.com/airtestproject/poco/blob/master/doc/integration.rst This snippet demonstrates how to initialize the PocoSDK in a Cocos2dx-JS project. It retrieves the PocoManager from the window object, creates a new instance of PocoManager, and then assigns this instance to window.poco to ensure it persists throughout the game's lifetime and is not destroyed. ```javascript var PocoManager = window.PocoManager var poco = new PocoManager() // add poco on window object to persist window.poco = poco ``` -------------------------------- ### Subscribing to Poco Messages (C#) Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/unity3d.rst This C# snippet demonstrates how to subscribe to Poco messages by adding an OnPocoMessageReceived handler to the PocoManager.MessageReceived event. This setup ensures that the specified function is invoked whenever a message is received from the Poco side, enabling Unity to react to Poco communications. ```csharp PocoManager.MessageReceived += OnPocoMessageReceived; ``` -------------------------------- ### Waiting for UI Element Disappearance and Appearance - UnityPoco Python Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/waiting_events.rst This snippet demonstrates how to wait for a UI element to disappear and another to appear using Poco. It initializes UnityPoco, clicks a 'start' button, waits for its disappearance, then waits for an 'exit' button to appear before clicking it. This ensures synchronization with scene transitions. ```python # coding=utf-8 from poco.drivers.unity3d import UnityPoco poco = UnityPoco() # start and waiting for switching scene start_btn = poco('start') start_btn.click() start_btn.wait_for_disappearance() # waiting for the scene ready then click exit_btn = poco('exit') exit_btn.wait_for_appearance() exit_btn.click() ``` -------------------------------- ### Setting Node Attributes in Poco Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst This function allows setting an attribute's value on a UI node. It shows how to handle 'text' and 'name' attributes by calling `SetText` and `SetName` on `self.Element`, and raises an `UnableToSetAttributeException` if an attribute cannot be set. ```python def setAttr(self, attrName, val): if attrName == 'text': self.Element.SetText(val) if attrName == 'name': self.Element.SetName(val) raise UnableToSetAttributeException(attrName, self) ``` -------------------------------- ### Example of Poco UI Hierarchy Structure Source: https://github.com/airtestproject/poco/blob/master/DocBuilder/index.rst This snippet illustrates the JSON structure of a dumped UI hierarchy element. It shows how UI elements are represented as dictionaries with properties like `name`, `payload` (containing type, visibility, position, size, etc.), and `children` for nested elements. This format provides a standardized way to inspect and interact with the UI tree. ```python ... { "name": "OctopusArea", "payload": { "name": "OctopusArea", "type": "GameObject", "visible": true, "clickable": true, "zOrders": { "global": 0, "local": -10 }, "scale": [ 1, 1 ], "anchorPoint": [ 0.5, 0.5 ], "pos": [ 0.130729169, 0.44907406 ], "size": [ 0.0859375, 0.125 ] } "children": [ {...}, ... ], } ... ``` -------------------------------- ### Handling PocoTargetTimeout for UI Appearance Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst This snippet demonstrates catching PocoTargetTimeout when waiting for a UI element to appear within a specified timeout period. It simulates a slow UI scenario where wait_for_appearance might time out, and shows how to handle the exception to maintain synchronization with the application's UI state. ```python # coding=utf-8 from poco.drivers.unity3d import UnityPoco from airtest.core.api import connect_device from poco.exceptions import PocoTargetTimeout poco = UnityPoco() # UI is very slow poco('btn_start').click() star = poco('star') try: star.wait_for_appearance(timeout=3) # wait until appearance within 3s except PocoTargetTimeout: print('oops!') time.sleep(1) ``` -------------------------------- ### Polling for Any UI Element Appearance - UnityPoco Python Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/waiting_events.rst This example illustrates how to use `poco.wait_for_any` to poll for the appearance of multiple UI elements simultaneously. It continuously checks for either a blue fish, yellow fish, or a bomb. If a fish appears, it's clicked; if a bomb appears, it's skipped, and a counter is incremented to exit after three bombs. ```python # coding=utf-8 from poco.drivers.unity3d import UnityPoco from poco.exceptions import PocoTargetTimeout poco = UnityPoco() bomb_count = 0 while True: blue_fish = poco('fish_emitter').child('blue') yellow_fish = poco('fish_emitter').child('yellow') bomb = poco('fish_emitter').child('bomb') fish = poco.wait_for_any([blue_fish, yellow_fish, bomb]) if fish is bomb: # skip the bomb and count to 3 to exit bomb_count += 1 if bomb_count > 3: return else: # otherwise click the fish to collect. fish.click() time.sleep(2.5) ``` -------------------------------- ### Iterating and Extracting Text from Nested UI Elements in Poco (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/iteration_over_elements.rst This example illustrates how to traverse a hierarchy of UI elements ('plays' -> 'fish' -> 'name') and print the text content of each 'name' element using Poco. It initializes UnityPoco and iterates through the selected child elements to extract their text values. ```Python # coding=utf-8 import time from poco.drivers.unity3d import UnityPoco poco = UnityPoco() for name in poco('plays').offspring('fish').child('name'): print(name.get_text()) # pearl/shark/balloonfish ``` -------------------------------- ### Updating Android.mk for Cocos2dx-js WebSocketServer Source: https://github.com/airtestproject/poco/blob/master/doc/integration.rst This snippet details the necessary modifications to 'Android.mk' (or 'proj.android-studio/jni/Android.mk') for Cocos2dx-js projects. It adds WebSocketServer source files, include paths, and static libraries to the build configuration, ensuring the module is properly compiled into the Android application. ```Android.mk ... $(call import-add-path, $(LOCAL_PATH)/../../../cocos2d-x/external) LOCAL_SRC_FILES := hellojavascript/main.cpp \ ../../Classes/AppDelegate.cpp \ ../../Classes/WebSocketServer.cpp \ ../../Classes/jsb_websocketserver.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \ $(LOCAL_PATH)/../../../cocos2d-x/external/websockets/include/android LOCAL_STATIC_LIBRARIES := cocos2d_js_static websockets_static include $(BUILD_SHARED_LIBRARY) $(call import-module, websockets/prebuilt/android) $(call import-module, scripting/js-bindings/proj.android) ... ``` -------------------------------- ### Implementing Click, Swipe, LongClick Functions - Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst These functions are essential for Poco's features to work. Note that input arguments (x, y coordinates) are percentages. If your API doesn't support percentage input, you must calculate the correct absolute coordinates (e.g., x = Left + Width * x, y = Top + Height * y). ```python def Click(self, x, y): # x = Left + Width * x # y = Top + Height * y YourAPI.Click(x, y) def Swipe(self, x1, y1, x2, y2, duration): YourAPI.Swipe(x1, y1, x2, y2, duration) def LongClick(self, x, y, duration): YourAPI.LongClick(x1, y1, x2, y2, duration) ``` -------------------------------- ### Initializing Airtest and Poco for Unity VR Automation (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/unity3d_vr.rst This snippet initializes the Airtest environment and sets up the Poco Unity3D driver for VR automation. It imports necessary modules, sets up the Airtest environment, and creates a `UnityPoco` instance, along with a `vr` object for VR-specific actions and a `uiproxy` for general UI interactions. ```Python import sys from airtest.core.api import * import time from poco.drivers.unity3d import UnityPoco import poco auto_setup(__file__) poco = UnityPoco() # note: use device=UnityEditorWindow() to test in unity vr = poco.vr uiproxy = poco() ``` -------------------------------- ### Initializing Poco for Unity3D Player on Windows Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/unity3d.rst This snippet demonstrates connecting to a Unity game running on Windows. It uses `airtest.core.api.connect_device` with a title regex to select the game window and initializes Poco with the specified device object and the Poco SDK's listening port. ```Python # import unity poco driver from this path from poco.drivers.unity3d import UnityPoco from airtest.core.api import connect_device # select the window object by title regex dev = connect_device('Windows:///?title_re=^your game title.*$') # make sure your poco-sdk in the game runtime listens on the following port. # default value will be 5001 # IP is not used for now addr = ('', 5001) # then initialize the poco instance in the following way # specifying the device object poco = UnityPoco(addr, device=dev) # now you can play with poco ui = poco('...') ui.click() ``` -------------------------------- ### Getting Available Node Attribute Names in Poco Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst This optional function allows extending the list of available attribute names for a UI node. It demonstrates how to append custom attribute names ('yourNewattr1', 'yourNewattr2') to the list returned by the superclass. ```python def getAvailableAttributeNames(self): return super(YourNode, self).getAvailableAttributeNames() + ('yourNewattr1', 'yourNewattr2') ``` -------------------------------- ### Handling PocoTargetRemovedException for Removed UI Elements Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/handling_exceptions.rst This example demonstrates PocoTargetRemovedException, which occurs when an operation is attempted on a UI element that was previously valid but has since been removed from the application. It also highlights the distinction between a 'tracked' removed node and a newly selected non-existent node, which would raise PocoNoSuchNodeException. ```python # coding=utf-8 from poco.exceptions import PocoTargetRemovedException, PocoNoSuchNodeException poco = Poco(...) start = poco('start') print(start.exists()) # => True. start.click() print(start.exists()) # => False try: start.click() except PocoTargetRemovedException: print('oops!') # IMPORTANT NOTE: # `start2` is different from `start` ! # `start` is tracking the UI at initial and it knows itself was removed but `start2` # does not know anything before. start2 = poco('start') try: start2.click() except PocoNoSuchNodeException: print('oops!') ``` -------------------------------- ### Clicking a UI Button with UnityPoco in Python Source: https://github.com/airtestproject/poco/blob/master/doc/poco-example/basic.rst This snippet initializes the UnityPoco driver and demonstrates how to select a UI object by its name ('btn_start') and perform a click action on it. It showcases the basic syntax for interacting with UI elements using the poco instance. ```python # coding=utf-8 from poco.drivers.unity3d import UnityPoco poco = UnityPoco() poco('btn_start').click() ``` -------------------------------- ### Getting Node Attributes in Poco Python Source: https://github.com/airtestproject/poco/blob/master/doc/implementation_guide.rst This function retrieves a property value of a UI node. It demonstrates how to return specific attributes like 'name', 'type', and 'pos' by calling corresponding methods on `self.Element`, falling back to the superclass for other attributes. It's crucial to return values in specified formats for 'anchor', 'pos', and 'size'. ```python def getAttr(self, attrName): if attrName == 'name': return self.Element.GetName() if attrName == 'type': return self.Element.GetType() if attrName == 'pos': return self.Element.GetPos() return super(YourNode, self).getAttr(attrName) ``` -------------------------------- ### Initializing WindowsPoco Instance by Window Properties (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/windows-app.rst This snippet demonstrates how to initialize a `WindowsPoco` instance to connect to a specific Windows application for automated testing. It shows three methods for identifying the target window: by exact title, by regular expression matching the title, or by window handle, and also illustrates connecting to a remote machine by specifying an IP address and port. Required dependencies include `pywin32` and `uiautomation`. ```Python from poco.drivers.windows import WindowsPoco poco = WindowsPoco({"title": "YourWindowTitle"}) # Find windows by title in local machine # poco = WindowsPoco({"title_re": "[a][b][c]"}, ("192.168.1.10", 15004)) # Find windows by regular expression remotely # poco = WindowsPoco({"handle": 123456}) # Find windows by handle ``` -------------------------------- ### Initializing OSXPoco Instance for MacOS Applications (Python) Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/osx-app.rst This code demonstrates how to initialize an `OSXPoco` instance to interact with a MacOS application. It shows various methods to identify the target application and window, including by app name, bundle ID, or regular expressions for both app and window titles. The second parameter allows specifying a remote machine address. ```python from poco.drivers.osx.osxui_poco import OSXPoco poco = OSXPoco({"appname": "Finder", "windowindex": 0}) # Find the first windows in 'Finder' application # poco = OSXPoco({"appname_re": "[a][b][c]", "windowtitle": "dirname"}, ("192.168.1.10", 15004)) # Find the window named 'dirname' by regular expression remotely # poco = OSXPoco({"bundleid": "com.apple.Finder", "windowtitle_re": "*.name"}) ``` -------------------------------- ### Defining SimpleRPC Sunshine Plugins (Python) Source: https://github.com/airtestproject/poco/blob/master/poco/utils/simplerpc/README.md This snippet shows how to define custom RPC plugins using the `Plugin` class, assign them a unique UUID, and register them with the `PluginRepo`. It also illustrates how a plugin can implement an `_on_rpc_ready` callback to interact with other plugins on the same agent and how to set up an `SSRpcServer` to host these plugins. ```Python ### 定义插件 from simplerpc.ssrpc.plugin import PluginRepo, Plugin, SSRpcServer, AgentManager class AAAPlugin(Plugin): UUID = "AAAAAAA" # UUID用于找到远端对应的插件 def _on_rpc_ready(self, agent): # print agent.get_plugin(self.UUID).add(3, 5).wait() agent.get_plugin(self.UUID).add(3, 5).on_result(pprint) def minus(self, a, b): return a - b class BBBPlugin(Plugin): UUID = "BBBBBBB" def echo(self, *args): return args PluginRepo.register(AAAPlugin()) PluginRepo.register(BBBPlugin()) AgentManager.ROLE = "SERVER" s = SSRpcServer(TcpServer()) s.run() ``` -------------------------------- ### Initializing Poco for Android Native Apps (Python) Source: https://github.com/airtestproject/poco/blob/master/README.rst This Python snippet demonstrates the initialization of Poco for automating Android native applications. It imports `AndroidUiautomationPoco`, creates an instance, wakes the device screen, and then performs a click action on a UI element identified by its text content, such as 'Clock'. ```Python from poco.drivers.android.uiautomation import AndroidUiautomationPoco poco = AndroidUiautomationPoco() poco.device.wake() poco(text='Clock').click() ``` -------------------------------- ### Selecting UI Elements with Basic Poco Selectors (Python) Source: https://github.com/airtestproject/poco/blob/master/README.rst Demonstrates how to select UI elements using the `poco(...)` function. It covers selection by node name and by combining node name with additional properties like `type`, `textMatches`, and `enable` to refine the query. The function traverses the render tree to find matching UI elements. ```Python # select by node name poco('bg_mission') # select by name and other properties poco('bg_mission', type='Button') poco(textMatches='^据点.*$', type='Button', enable=True) ``` -------------------------------- ### Initializing Poco for Multiple Mixed-Platform Devices Source: https://github.com/airtestproject/poco/blob/master/doc/drivers/unity3d.rst This snippet demonstrates how to control multiple devices across different platforms (UnityEditor, Android, Windows) within the same test case. It initializes separate device objects and Poco instances for each, allowing concurrent interaction with distinct game environments. ```Python # import unity poco driver from this path from poco.drivers.unity3d import UnityPoco from poco.drivers.unity3d.device import UnityEditorWindow # initialize different device object one by one dev1 = UnityEditorWindow() dev2 = connect_device('Android:///') dev3 = connect_device('Windows:///?title_re=^title xxx.*$') # use this default address. separate them if the devices do not listens on the same port. addr = ('', 5001) # initialize poco instance one by one by specifying different device object poco1 = UnityPoco(addr, device=dev1) poco2 = UnityPoco(addr, device=dev2) poco3 = UnityPoco(addr, device=dev3) # now you can play with poco ui1 = poco1('...') ui1.click() ui2 = poco2('...') ui2.swipe('up') ```