### UI Test Setup API Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md API for initializing the UI test library. ```APIDOC ## POST /setup ### Description Initializes the ui_test library. This method must be called within the `onRun` method of a `TestRunner`. ### Method POST ### Endpoint /setup ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (String) - Indicates the status of the UI test library initialization. #### Response Example ```json { "status": "initialized" } ``` ``` -------------------------------- ### Example: Setting up UI Test in Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Demonstrates how to set up the UI test library by calling `UITest.setup()` within the `onRun()` method of a custom `TestRunner`. It also shows how to register the custom runner. ```cangjie //unittest_enginge.cj import ohos.base.* import kit.TestKit.* import ohos.test_runner.* class MyTestRunner <: TestRunner { public func onRun() { UITest.setup() } public func onPrepare() { Hilog.info(0, "AppLogCj", "CJTestRunner onPrepare") } } let _ = TestRunner.registerCreator("MyTestRunner") {MyTestRunner()} ``` -------------------------------- ### Start Ability (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Launches the specified UIAbility. This function requires SystemCapability.Ability.AbilityRuntime.Core and takes a Want object containing launch parameters. It returns a Future and may encounter parameter errors. ```cangjie public func startAbility(want: Want): Future ``` -------------------------------- ### Initialize UI Test Library in Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Initializes the ui_test library. The `setup()` static method must be called within the `onRun()` method of a `TestRunner`. This is a prerequisite for using UI testing functionalities. ```cangjie public static func setup(): Unit ``` -------------------------------- ### Example Test Results XML Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-arkxtest-guidelines.md This is an example of the XML output generated after a test execution completes. It provides details about the test suite, individual test cases, execution time, and any failures or errors. ```xml ``` -------------------------------- ### Simulate Mouse Drag Gesture (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Simulates a mouse drag action from a starting point to an ending point while holding the left mouse button. Accepts start and end coordinates, and an optional speed parameter. Throws BusinessException on parameter errors. ```cangjie public func mouseDrag(from: Point, to: Point, speed!: Int32 = 600): Unit // Example: import kit.TestKit.* import ohos.ui_test.Point as PT let driver: Driver = Driver.create() driver.mouseDrag(PT(100, 100), PT(200, 200)) ``` -------------------------------- ### Write Unit Test Script in Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-arkxtest-guidelines.md Example of a unit test script in Cangjie for launching an ability and verifying the current top displayed ability. It imports necessary kits and uses assertion interfaces to check conditions. ```cangjie //example_test.cj import kit.TestKit.* import kit.AbilityKit.* import std.unittest.* import std.unittest.common.* import std.unittest.testmacro.* @Test class TestExample00 { @TestCase func testUiExample(): Unit { let delegator = AbilityDelegatorRegistry.getAbilityDelegator() let bundleName = AbilityDelegatorRegistry .getArguments() .bundleName AppLog.info("uitest: TestUiExample begin") //start tested ability let want = Want(bundleName: bundleName, abilityName: 'EntryAbility') delegator .startAbility(want) .get() sleep(Duration.second * 5) //check top display ability let ability = delegator.getCurrentTopAbility() AppLog.info("get top ability") @Expect(ability.context.abilityInfo.name, 'EntryAbility') } } ``` -------------------------------- ### Monitor UI Events with UIEventObserver Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt This example shows how to use UIEventObserver to monitor and react to UI events such as Toast and Dialog appearances. It sets up listeners for specific event types and logs information about the event when it occurs. This is useful for verifying UI feedback during automated tests. ```cantml import kit.TestKit.* let driver = Driver.create() // Create event observer let observer = driver.createUiEventObserver() // Listen for Toast appearance observer.once(OnceType.ToastShow) { info: UiElementInfo => AppLog.info("Toast appeared: ${info.text}") AppLog.info("Bundle: ${info.bundleName}") AppLog.info("Type: ${info.componentType}") } // Listen for Dialog appearance observer.once(OnceType.DialogShow) { info: UiElementInfo => AppLog.info("Dialog appeared: ${info.text}") } ``` -------------------------------- ### Cangjie UI Test: Login Flow Example Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Demonstrates a unit test structure for UI testing in OpenHarmony using the Cangjie API. It covers launching an ability, initializing a UI driver, interacting with input fields, clicking buttons, and verifying screen transitions. Dependencies include kit.TestKit, kit.AbilityKit, and std.unittest. ```cangjie import kit.TestKit.* import kit.AbilityKit.* import std.unittest.* import std.unittest.testmacro.* @Test class LoginUITest { @TestCase func testLoginFlow(): Unit { // Setup let delegator = AbilityDelegatorRegistry.getAbilityDelegator() let bundleName = AbilityDelegatorRegistry.getArguments().bundleName // Launch the app let want = Want(bundleName: bundleName, abilityName: "EntryAbility") delegator.startAbility(want).get() sleep(Duration.second * 3) // Verify app launched let ability = delegator.getCurrentTopAbility() @Expect(ability.context.abilityInfo.name, "EntryAbility") // Initialize UI driver let driver = Driver.create() driver.delayMs(1000) // Verify login screen displayed driver.assertComponentExist(On().text("Login")) // Enter credentials if (let Some(username) <- driver.findComponent(On().id("username_input"))) { username.inputText("testuser") } if (let Some(password) <- driver.findComponent(On().id("password_input"))) { password.inputText("password123") } // Click login button let loginBtn = driver.findComponent(On().text("Login").onType("Button")) loginBtn?.click() // Wait for and verify success driver.delayMs(2000) driver.assertComponentExist(On().text("Welcome")) // Cleanup driver.pressBack() } } ``` -------------------------------- ### Move Mouse with Track and Speed (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Simulates mouse movement from a starting point to a destination point with a configurable speed. This function requires 'TestKit' and 'Point' modules. It takes two Point objects for start and end coordinates, and an optional Int32 for speed. ```cangjie import kit.TestKit.* import ohos.ui_test.Point as PT let driver: Driver = Driver.create() driver.mouseMoveWithTrack(PT(100, 100), PT(200, 200)) ``` -------------------------------- ### Create Custom Test Runners with TestRunner Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt This example shows how to create a custom test runner by extending the TestRunner class. It allows defining custom logic for test preparation (onPrepare) and execution (onRun). A custom runner can be registered with the framework to be used for specialized testing scenarios. ```cangjie import kit.TestKit.* import ohos.test_runner.* // Define custom test runner class MyTestRunner <: TestRunner { public func onPrepare(): Unit { AppLog.info("Test preparation started") // Setup test environment } public func onRun(): Unit { // Initialize UI testing library (required for UiTest) UITest.setup() AppLog.info("Test execution started") // Execute tests } } // Register the custom test runner let _ = TestRunner.registerCreator("MyTestRunner") { MyTestRunner() } ``` -------------------------------- ### Driver Drag API Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Executes a drag operation from start coordinates to target coordinates. ```APIDOC ## POST /driver/drag ### Description Executes a drag operation from the start coordinates to the target coordinates for the Driver object. ### Method POST ### Endpoint /driver/drag ### Parameters #### Query Parameters - **startx** (Int32) - Required - The horizontal coordinate of the start point. - **starty** (Int32) - Required - The vertical coordinate of the start point. - **endx** (Int32) - Required - The horizontal coordinate of the end point. - **endy** (Int32) - Required - The vertical coordinate of the end point. - **speed** (Int32) - Optional - The swipe speed, range: 200-15000. Defaults to 600. Unit: pixels/second. ### Request Example ```cangjie // index.cj import ohos.base.* import kit.TestKit.* let driver: Driver = Driver.create() driver.drag(100, 100, 200, 200, speed: 600) ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` #### Error Handling - **BusinessException** - **401**: Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. ``` -------------------------------- ### Get Display Size - Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the screen size of the current device. Requires the TestKit and Base modules. Returns a Point object representing the screen dimensions. ```cangjie import ohos.base.* import kit.TestKit.* let driver: Driver = Driver.create() let size = driver.getDisplaySize() ``` -------------------------------- ### POST /api/swipe Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Performs a swipe operation from starting coordinates to destination coordinates with a specified speed. ```APIDOC ## POST /api/swipe ### Description Performs a swipe operation from the starting coordinates to the destination coordinates. ### Method POST ### Endpoint /api/swipe ### Parameters #### Query Parameters - **startx** (Int32) - Required - The x-coordinate of the starting point. - **starty** (Int32) - Required - The y-coordinate of the starting point. - **endx** (Int32) - Required - The x-coordinate of the destination point. - **endy** (Int32) - Required - The y-coordinate of the destination point. - **speed** (Int32) - Optional - Swipe speed, range: 200-15000. Defaults to 600. ### Request Example ```json { "startx": 100, "starty": 100, "endx": 200, "endy": 200, "speed": 600 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` #### Error Response (400) - **error** (string) - Description of the error. #### Error Example ```json { "error": "Parameter error. Mandatory parameters are left unspecified." } ``` ``` -------------------------------- ### Execute All Test Cases via CMD Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-arkxtest-guidelines.md This command executes all test cases for a given application bundle and module. It requires the 'hdc' tool to be configured and the HarmonyOS test framework environment variables to be set. ```shell hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner ``` -------------------------------- ### Get Window Mode - Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Obtains the window mode information of the window. This function requires the SystemCapability.Test.UiTest capability and returns the window's mode. It may throw a BusinessException if the window is invisible or destroyed. ```cangjie public func getWindowMode(): WindowMode ``` ```cangjie // index.cj import ohos.base.* import kit.TestKit.* let driver: Driver = Driver.create() let window: Option = driver.findWindow(WindowFilter(active: true)) let mode = window?.getWindowMode() ``` -------------------------------- ### Coordinate-Based Screen Interactions (Cangjie Driver) Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Performs touch operations directly on the screen at specified coordinates using the Driver class. Supports clicks, double clicks, long presses, swipe gestures with start and end points and speed, and drag operations. It also includes fling gestures in various directions and at specific coordinates, as well as inputting text at a given point. ```cangjie import kit.TestKit.* let driver = Driver.create() // Click at specific coordinates driver.click(100, 200) // Click at (100, 200) driver.doubleClick(300, 400) // Double click driver.longClick(500, 600) // Long press // Swipe gestures driver.swipe( startx: 100, // Start X starty: 500, // Start Y endx: 100, // End X endy: 100, // End Y speed: 800 // Speed in pixels/second (200-40000) ) // Drag operation driver.drag( startx: 200, starty: 300, endx: 600, endy: 300, speed: 600 ) // Fling gesture with direction driver.fling(UiDirection.Down, 10000) // Fling down at high speed driver.fling(UiDirection.Up, 5000) // Fling up // Fling with specific coordinates driver.fling( from: Point(200, 800), to: Point(200, 200), stepLen: 50, speed: 8000 ) // Input text at coordinates let textPoint = Point(300, 400) driver.inputText(textPoint, "Hello World") ``` -------------------------------- ### Get Control Description (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the description information (String) of a control object. This function is part of the SystemCapability.Test.UiTest and requires API version 21 or later. It may throw a BusinessException if the window or component is invisible or destroyed. ```cangjie public func getDescription(): String ``` -------------------------------- ### startAbility Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Launches the specified UIAbility. ```APIDOC ## POST /startAbility ### Description Launches the specified UIAbility. ### Method POST ### Endpoint /startAbility ### Parameters #### Query Parameters None #### Request Body - **want** (Want) - Required - Parameters for launching UIAbility. ### Request Example ```json { "want": { "abilityName": "MyAbility", "bundleName": "com.example.myapp" } } ``` ### Response #### Success Response (200) - **future** (Future) - A future object representing the asynchronous operation of starting the ability. #### Response Example ```json { "future": "{FutureObjectReference}" } ``` ### Exceptions - **401**: Parameter error. Possible causes: 1. Mandatory parameters are unspecified. 2. Incorrect parameter types. ``` -------------------------------- ### Get AbilityDelegator Object (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Retrieves the AbilityDelegator object, which is essential for dispatching test framework functionalities within an application. This function is available starting from API version 21. ```cangjie public static func getAbilityDelegator(): AbilityDelegator ``` -------------------------------- ### Cangjie UI Test Script for Application Interaction Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-arkxtest-guidelines.md Implements a UI test case using Cangjie API to interact with a HarmonyOS application. It starts the ability, simulates a click on a 'Next' button, and asserts the presence of text indicating a successful interaction. This script requires the `TestKit`, `AbilityKit`, and `unittest` libraries. ```cangjie import kit.TestKit.* import kit.AbilityKit.* import std.unittest.* import std.unittest.common.* import std.unittest.testmacro.* @Test class TestExample00 { @TestCase func testUiExample(): Unit { let delegator = AbilityDelegatorRegistry.getAbilityDelegator() let bundleName = AbilityDelegatorRegistry .getArguments() .bundleName AppLog.info("uitest: TestUiExample begin") //start tested ability let want = Want(bundleName: bundleName, abilityName: 'EntryAbility') delegator .startAbility(want) .get() sleep(Duration.second * 5) //check top display ability let ability = delegator.getCurrentTopAbility() AppLog.info("get top ability") @Expect(ability.context.abilityInfo.name, 'EntryAbility') // ui test code // init driver let driver = Driver.create() driver.delayMs(1000) let button = driver.findComponent(On().text('Next')) //click button button.click() driver.delayMs(1000) //check text driver.assertComponentExist(On().text('after click')) driver.pressBack() } } ``` -------------------------------- ### Press Home Key API Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Returns the device to the home screen. ```APIDOC ## POST /api/pressHome ### Description Returns the device to the home screen. ### Method POST ### Endpoint /api/pressHome ### Parameters No parameters required. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (String) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Point Class Initialization (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md The `init` method for the `Point` class allows for the creation of a `Point` instance by providing the x and y coordinates, and an optional display ID. This constructor is essential for defining specific points for UI interactions. ```cangjie public init(x: Int32, y: Int32, displayId!: ?Int32 = None) ``` -------------------------------- ### String Utility Functions Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Provides functions for string manipulation, including checking if a string contains, ends with, equals, or starts with a specific value. ```APIDOC ## String Utility Functions ### Contains **Function:** Contains the given value. **System Capability:** SystemCapability.Test.UiTest **Since:** 21 ### EndsWith **Function:** Ends with the given value. **System Capability:** SystemCapability.Test.UiTest **Since:** 21 ### Equals **Function:** Equals the given value. **System Capability:** SystemCapability.Test.UiTest **Since:** 21 ### StartsWith **Function:** Starts with the given value. **System Capability:** SystemCapability.Test.UiTest **Since:** 21 ``` -------------------------------- ### POST /api/triggerCombineKeys Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Simulates pressing a combination of keys. ```APIDOC ## POST /api/triggerCombineKeys ### Description Simulates pressing a combination of keys based on the provided key values. ### Method POST ### Endpoint /api/triggerCombineKeys ### Parameters #### Query Parameters - **key0** (Int32) - Required - The first specified key value. - **key1** (Int32) - Required - The second specified key value. - **key2** (Int32) - Optional - The third specified key value. Defaults to 0. ### Request Example ```json { "key0": 2072, "key1": 2047, "key2": 2035 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` #### Error Response (400) - **error** (string) - Description of the error. #### Error Example ```json { "error": "Parameter error. Incorrect parameter types." } ``` ``` -------------------------------- ### Get Display Density API Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the screen resolution (density) of the current device. This information is crucial for tests that depend on screen dimensions. ```APIDOC ## GET /super3001/harmonyos_testfwk_cangjie_api/getDisplayDensity ### Description Retrieves the screen resolution of the current device. ### Method GET ### Endpoint /super3001/harmonyos_testfwk_cangjie_api/getDisplayDensity ### Response #### Success Response (200) - **displayDensity** (Point) - Returns the screen resolution of the current device. #### Response Example ```json { "displayDensity": { "x": 1080, "y": 1920 } } ``` ``` -------------------------------- ### Create PointerMatrix Object (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md The static `create` function constructs a `PointerMatrix` object. It takes the number of fingers and the number of steps for each finger operation as parameters, returning the initialized `PointerMatrix`. ```cangjie public static func create(fingers: Int32, steps: Int32): PointerMatrix ``` ```cangjie // index.cj import ohos.base.* import kit.TestKit.* let pointerMatrix: PointerMatrix = PointerMatrix.create(2, 3) ``` -------------------------------- ### Get Display Rotation API Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the current screen orientation (rotation) of the device. This is important for tests that need to adapt to different device orientations. ```APIDOC ## GET /super3001/harmonyos_testfwk_cangjie_api/getDisplayRotation ### Description Retrieves the screen orientation of the current device. ### Method GET ### Endpoint /super3001/harmonyos_testfwk_cangjie_api/getDisplayRotation ### Response #### Success Response (200) - **displayRotation** (DisplayRotation) - Returns the screen orientation of the current device. #### Response Example ```json { "displayRotation": "Rotation0" } ``` ``` -------------------------------- ### Driver.create() - Create Driver Instance Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Creates a Driver object, the main entry point for UI test operations, including component finding, screen interactions, and device management. ```APIDOC ## Driver.create() - Create Driver Instance ### Description Creates a Driver object which serves as the main entry point for all UI test operations including component finding, screen interactions, and device management. ### Method `Driver.create()` ### Parameters None ### Request Example ```cangjie import kit.TestKit.* // Create the main driver instance for UI testing let driver: Driver = Driver.create() ``` ### Response - **driver** (Driver) - An instance of the Driver class. ### Response Example ```cangjie // Driver instance is implicitly returned and assigned to the 'driver' variable. let driver: Driver = Driver.create() driver.delayMs(1000) let displaySize = driver.getDisplaySize() ``` ``` -------------------------------- ### Get Control Type (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the control type (String) of a control object. This function is part of the SystemCapability.Test.UiTest and requires API version 21 or later. ```cangjie public func getType(): String ``` -------------------------------- ### Interact with UI Components: Click, Input, Query (Cangjie) Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Provides methods for interacting with and querying UI components using the Component class. Supports basic clicks, double clicks, long presses, text input, clearing text, and retrieving component properties like ID, text, type, and state. It also allows for drag-and-drop and pinch gestures. ```cangjie import kit.TestKit.* let driver = Driver.create() // Find and click a button if (let Some(button) <- driver.findComponent(On().text("Login"))) { // Basic click operations button.click() // Single click button.doubleClick() // Double click button.longClick() // Long press // Query component properties let id = button.getId() let text = button.getText() let type = button.getType() let description = button.getDescription() // Query component states let isClickable = button.isClickable() let isEnabled = button.isEnabled() let isFocused = button.isFocused() let isSelected = button.isSelected() let isChecked = button.isChecked() let isScrollable = button.isScrollable() // Get component bounds let bounds = button.getBounds() // Rect with left, top, right, bottom let center = button.getBoundsCenter() // Point with x, y } // Text input operations if (let Some(textInput) <- driver.findComponent(On().onType("TextInput"))) { textInput.inputText("user@example.com") // Enter text textInput.clearText() // Clear existing text textInput.inputText("newuser@example.com") } // Drag component to another component if (let Some(source) <- driver.findComponent(On().text("Drag me"))) { if (let Some(target) <- driver.findComponent(On().text("Drop here"))) { source.dragTo(target) } } // Pinch gestures for zoom if (let Some(image) <- driver.findComponent(On().onType("Image"))) { image.pinchOut(2.0) // Zoom in by 2x image.pinchIn(0.5) // Zoom out to 50% } ``` -------------------------------- ### Get Control Text (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the text information (String) of a control object. This function is part of the SystemCapability.Test.UiTest and requires API version 21 or later. ```cangjie public func getText(): String ``` -------------------------------- ### POST /api/triggerKey Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Simulates pressing a single key. ```APIDOC ## POST /api/triggerKey ### Description Simulates pressing a key by passing in its key code. ### Method POST ### Endpoint /api/triggerKey ### Parameters #### Query Parameters - **keyCode** (Int32) - Required - The key code to be triggered. ### Request Example ```json { "keyCode": 18 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` #### Error Response (400) - **error** (string) - Description of the error. #### Error Example ```json { "error": "Parameter error. Parameter verification failed." } ``` ``` -------------------------------- ### Get Control ID (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the ID value (String) of a control object. This function is part of the SystemCapability.Test.UiTest and requires API version 21 or later. ```cangjie public func getId(): String ``` -------------------------------- ### On - Component Locator Builder Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt The On class provides a fluent API for building component locators using various attributes like text, ID, type, and state properties. Supports chaining multiple conditions and relative positioning. ```APIDOC ## On - Component Locator Builder ### Description The On class provides a fluent API for building component locators using various attributes like text, ID, type, and state properties. Supports chaining multiple conditions and relative positioning. ### Method `On()` ### Parameters None (Methods are chained to build the locator) ### Query Parameters - **text** (string, optional) - Matches components by their text content. Can use `MatchPattern` for Contains, StartsWith, etc. - **id** (string, optional) - Matches components by their unique ID. - **onType** (string, optional) - Matches components by their class type (e.g., "Button", "TextInput"). - **clickable** (boolean, optional) - Matches components that are clickable. - **enabled** (boolean, optional) - Matches components that are enabled. - **checkable** (boolean, optional) - Matches components that are checkable. - **checked** (boolean, optional) - Matches components that are currently checked. - **focused** (boolean, optional) - Matches components that currently have focus. - **selected** (boolean, optional) - Matches components that are currently selected. - **isAfter** (On, optional) - Matches a component that appears after another component defined by the provided `On` locator. - **isBefore** (On, optional) - Matches a component that appears before another component defined by the provided `On` locator. - **within** (On, optional) - Matches a component that is a descendant of a parent component defined by the provided `On` locator. - **inWindow** (string, optional) - Matches a component within a specific application window identified by its package name. ### Request Example ```cangjie import kit.TestKit.* // Find by exact text let byText = On().text("Submit") // Find by text with pattern matching let byTextContains = On().text("Hello", pattern: MatchPattern.Contains) let byTextStartsWith = On().text("Welcome", pattern: MatchPattern.StartsWith) // Find by component ID let byId = On().id("login_button") // Find by component type let byType = On().onType("Button") // Combine multiple attributes let combined = On() .text("Login") .onType("Button") .clickable() .enabled() // Find by state attributes let byState = On() .checkable(b: true) .checked(b: false) .focused(b: true) .selected(b: false) // Relative positioning - find component before/after another let anchor = On().text("Username") let afterAnchor = On().onType("TextInput").isAfter(anchor) let beforeAnchor = On().onType("Button").isBefore(anchor) // Find within a parent container let parent = On().onType("Scroll") let childInParent = On().text("Item").within(parent) // Find within specific application window let inApp = On().text("Settings").inWindow("com.example.app") ``` ### Response - **On** - An instance of the On class configured with the specified locator criteria. ``` -------------------------------- ### Get AbilityDelegatorArgs Object (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Obtains the AbilityDelegatorArgs object, used for accessing unit test parameters. This function is available from API version 21 onwards. ```cangjie public static func getArguments(): AbilityDelegatorArgs ``` -------------------------------- ### Implement Test Runner Lifecycle Methods in Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Provides methods for test case execution and environment preparation. `onPrepare()` is intended for executing test cases, while `onRun()` is for preparing the unit test environment. Both are crucial for the test runner's lifecycle. ```cangjie public open func onPrepare(): Unit ``` ```cangjie public open func onRun(): Unit ``` -------------------------------- ### Add Ability Monitor to Delegator Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Adds an AbilityMonitor instance to the AbilityDelegator. This function is used to start monitoring the lifecycle state changes of a specified UIAbility. It is not designed for concurrent thread access. ```cangjie public func addAbilityMonitor(monitor: AbilityMonitor): Unit ``` -------------------------------- ### Create and Execute Multi-Touch Gestures with PointerMatrix Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt This snippet demonstrates how to create and inject multi-finger touch gestures using the PointerMatrix API. It defines the paths for multiple fingers across several steps to simulate complex interactions like pinch-zoom. The gesture is then executed using the driver's injectMultiPointerAction method. ```cangjie import kit.TestKit.* import ohos.ui_test.Point as PT let driver = Driver.create() // Create a 2-finger, 3-step gesture let pointers = PointerMatrix.create(2, 3) // fingers, steps // Define finger 1 path (pinch out - moving outward) pointers.setPoint(0, 0, PT(300, 400)) // Start position pointers.setPoint(0, 1, PT(250, 350)) // Middle position pointers.setPoint(0, 2, PT(200, 300)) // End position // Define finger 2 path (moving opposite direction) pointers.setPoint(1, 0, PT(400, 500)) pointers.setPoint(1, 1, PT(450, 550)) pointers.setPoint(1, 2, PT(500, 600)) // Execute the multi-pointer gesture let success = driver.injectMultiPointerAction(pointers, speed: 600) ``` -------------------------------- ### Get Display Rotation - Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the screen orientation of the current device. The `getDisplayRotation` function returns a `DisplayRotation` enum value, indicating the current orientation. This function is part of SystemCapability.Test.UiTest. ```cangjie public func getDisplayRotation(): DisplayRotation // index.cj import ohos.base.* import kit.TestKit.* let driver: Driver = Driver.create() let rotation: DisplayRotation = driver.getDisplayRotation() ``` -------------------------------- ### Shell Commands: Running OpenHarmony Tests Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Provides essential hdc shell commands for executing OpenHarmony tests. This includes enabling test mode, disabling background app freeze, rebooting the device, and running all tests, specific test classes, or multiple test classes within a module. ```shell # Enable test mode (run once after flashing device) hdc shell param set persist.ace.testmode.enabled 1 # Disable background app freeze for testing hdc shell param set persist.sys.suspend_manager_enabled 0 # Reboot device to apply settings hdc shell reboot # Run all tests in a module hdc shell aa test -b com.example.myapplication -m entry -s unittest CJTestRunner # Run specific test class hdc shell aa test -b com.example.myapplication -m entry -s unittest CJTestRunner -s class LoginUITest # Run multiple test classes hdc shell aa test -b com.example.myapplication -m entry -s unittest CJTestRunner -s class LoginUITest,SettingsUITest ``` -------------------------------- ### On Class Initialization Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Initializes an instance of the On class, used for control matching in UiTest. ```APIDOC ## POST /api/On/init ### Description Initializes an instance of the `On` class, which provides APIs for filtering and locating target controls in the UiTest framework. ### Method POST ### Endpoint /api/On/init ### Parameters This endpoint does not require any parameters. ### Request Example ```json { "init": true } ``` ### Response #### Success Response (200) - **instanceId** (string) - A unique identifier for the created `On` instance. #### Response Example ```json { "instanceId": "on_instance_12345" } ``` #### Error Response (500) - **error** (string) - Description of the error. #### Error Example ```json { "error": "Failed to initialize On instance." } ``` ``` -------------------------------- ### Get String Representation of AbilityLifecycleState (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Retrieves the string representation of the current AbilityLifecycleState enumeration value. This function does not take any parameters and returns a String. It is useful for debugging and logging purposes. ```cangjie public func toString(): String ``` -------------------------------- ### print Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Prints log information to the unit test terminal console. ```APIDOC ## POST /print ### Description Prints log information to the unit test terminal console. ### Method POST ### Endpoint /print ### Parameters #### Query Parameters None #### Request Body - **msg** (String) - Required - The log message string. ### Request Example ```json { "msg": "This is a log message." } ``` ### Response #### Success Response (200) - **status** (String) - Indicates the success or failure of the operation. #### Response Example ```json { "status": "success" } ``` ### Exceptions - **401**: Parameter error. Possible causes: 1. Mandatory parameters are unspecified. 2. Incorrect parameter types. ``` -------------------------------- ### HarmonyOS Cangjie AbilityMonitor Initialization Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Constructs an AbilityMonitor object in HarmonyOS using Cangjie. This constructor allows for the initialization of an AbilityMonitor with various callback functions for ability and window stage lifecycles. Default values are provided for optional parameters. ```cangjie public init( abilityName: String, moduleName!: String = "", onAbilityCreate!: ?(UIAbility) -> Unit = None, onAbilityForeground!: ?(UIAbility) -> Unit = None, onAbilityBackground!: ?(UIAbility) -> Unit = None, onAbilityDestroy!: ?(UIAbility) -> Unit = None, onWindowStageCreate!: ?(UIAbility) -> Unit = None, onWindowStageRestore!: ?(UIAbility) -> Unit = None, onWindowStageDestroy!: ?(UIAbility) -> Unit = None ) ``` -------------------------------- ### Manage UIAbility Lifecycle with AbilityDelegator Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt This snippet illustrates how to manage the lifecycle of a UIAbility using the AbilityDelegator API. It covers obtaining the delegator instance, accessing test arguments, launching abilities, checking ability states, moving abilities between foreground and background, executing shell commands, and concluding tests. ```cangjie import kit.TestKit.* import kit.AbilityKit.* // Get the delegator instance let delegator = AbilityDelegatorRegistry.getAbilityDelegator() // Get test arguments let args = AbilityDelegatorRegistry.getArguments() let bundleName = args.bundleName let testCases = args.testCaseNames // Get application context let appContext = delegator.getAppContext() // Launch an ability let want = Want(bundleName: "com.example.app", abilityName: "EntryAbility") delegator.startAbility(want).get() // Get current top ability let topAbility = delegator.getCurrentTopAbility() let abilityState = delegator.getAbilityState(topAbility) // Move ability between foreground/background delegator.doAbilityForeground(topAbility) delegator.doAbilityBackground(topAbility) // Execute shell command let result = delegator.executeShellCommand("ls -la", timeoutSecs: 5) let exitCode = result.exitCode let output = result.stdResult // Print to test console delegator.print("Test output message") // End test with result delegator.finishTest("All tests passed", 0) ``` -------------------------------- ### Get Display Density - Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the screen resolution (density) of the current device. The `getDisplayDensity` function returns a `Point` object representing the screen's resolution. This function is available under SystemCapability.Test.UiTest. ```cangjie public func getDisplayDensity(): Point // index.cj import ohos.base.* import kit.TestKit.* let driver: Driver = Driver.create() let density = driver.getDisplayDensity() ``` -------------------------------- ### Rect Class Constructor Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Initializes a Rect instance with the coordinates of the control's border and an optional display ID. The constructor requires left, top, right, and bottom coordinates, and accepts an optional displayId. ```cangjie public init(left: Int32, top: Int32, right: Int32, bottom: Int32, displayId!: ?Int32 = None) ``` -------------------------------- ### Driver Display Management in Cangjie Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Manages device display settings, including retrieving display size, rotation, and density. It allows setting screen rotation to different orientations and enabling/disabling auto-rotation. The `wakeUpDisplay` method can turn on the screen, and `waitForIdle` checks for UI responsiveness. ```cangjie import kit.TestKit.* let driver = Driver.create() // Get display information let size = driver.getDisplaySize() // Returns Point with width/height let rotation = driver.getDisplayRotation() let density = driver.getDisplayDensity() // Set display rotation driver.setDisplayRotation(DisplayRotation.Rotation0) // Portrait driver.setDisplayRotation(DisplayRotation.Rotation90) // Landscape driver.setDisplayRotation(DisplayRotation.Rotation180) // Portrait inverted driver.setDisplayRotation(DisplayRotation.Rotation270) // Landscape inverted // Enable/disable auto-rotation driver.setDisplayRotationEnabled(false) // Lock rotation driver.setDisplayRotationEnabled(true) // Enable auto-rotation // Wake up display driver.wakeUpDisplay() // Wait for UI to become idle let isIdle = driver.waitForIdle( idleTime: 500, // Idle threshold in ms timeout: 5000 // Max wait time in ms ) ``` -------------------------------- ### Importing the Module Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Import the TestKit module to access all UI testing functionality provided by the framework. ```APIDOC ## Importing the Module ### Description Import the TestKit module to access all UI testing functionality. ### Code Example ```cangjie import kit.TestKit.* ``` ``` -------------------------------- ### Get UIAbility State (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Retrieves the current lifecycle state of a specified UIAbility. The getAbilityState() function takes a UIAbility object and returns an AbilityLifecycleState. It is part of SystemCapability.Ability.AbilityRuntime.Core and available since version 21. ```cangjie public func getAbilityState(ability: UIAbility): AbilityLifecycleState ``` -------------------------------- ### Fling Gesture API (Point-based) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Simulates a fling gesture (rapid swipe followed by release) with specified start and end points, step length, and speed. This allows for precise control over swipe gestures in tests. ```APIDOC ## POST /super3001/harmonyos_testfwk_cangjie_api/fling ### Description Simulates a fling gesture (rapid swipe followed by release) with specified direction and speed. ### Method POST ### Endpoint /super3001/harmonyos_testfwk_cangjie_api/fling ### Parameters #### Request Body - **from** (Point) - Required - Starting coordinates where the finger touches the screen. - **to** (Point) - Required - Ending coordinates where the finger leaves the screen. - **stepLen** (Int32) - Required - Step length, in pixels. - **speed** (Int32) - Required - Swipe speed, range: 200-40000. If out of range, defaults to 600. Unit: pixels/second. ### Request Example ```json { "from": {"x": 100, "y": 100}, "to": {"x": 500, "y": 500}, "stepLen": 10, "speed": 10000 } ``` ### Response #### Success Response (200) - **status** (String) - Indicates the operation was successful. #### Response Example ```json { "status": "success" } ``` #### Error Response (401) - **errorCode** (String) - Parameter error. Possible causes: 1. Mandatory parameters are missing; 2. Incorrect parameter types; 3. Parameter validation failed. - **errorMessage** (String) - Detailed error message. ``` -------------------------------- ### Get Window Title using Cangjie API Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Obtains the title information (String) of the specified window. This function requires the window to be visible and not destroyed. It returns the window title or throws a BusinessException if the window is invalid. ```cangjie import ohos.base.* import kit.TestKit.* let driver: Driver = Driver.create() let window: Option = driver.findWindow(WindowFilter(active: true)) let title: Option = window?.getTitle() ``` -------------------------------- ### Create Driver Instance in Cangjie Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md The Driver class is the primary entry point for the uitest framework, offering functionalities like component matching, searching, key injection, and screenshot capture. The static create() method constructs and returns a Driver object. This method is part of SystemCapability.Test.UiTest. ```cangjie public static func create(): Driver ``` ```cangjie // index.cj import ohos.base.* import kit.TestKit.* let driver: Driver = Driver.create() ``` -------------------------------- ### Create Driver Instance in Cangjie Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt Creates a Driver object, the primary entry point for UI testing operations in the OpenHarmony Cangjie UI Test Framework. It allows for component finding, screen interactions, and device management. Requires the TestKit module to be imported. ```cangjie import kit.TestKit.* // Create the main driver instance for UI testing let driver: Driver = Driver.create() // Use the driver to interact with the device driver.delayMs(1000) // Wait 1 second // Get device display information let displaySize = driver.getDisplaySize() let rotation = driver.getDisplayRotation() let density = driver.getDisplayDensity() ``` -------------------------------- ### Get Control Bounds (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ui_test.md Retrieves the border information (Rect) of a control object. This function is part of the SystemCapability.Test.UiTest and requires API version 21 or later. It may throw a BusinessException if the window or component is invisible or destroyed. ```cangjie public func getBounds(): Rect ``` -------------------------------- ### Monitor UIAbility Lifecycle Callbacks with AbilityMonitor Source: https://context7.com/super3001/harmonyos_testfwk_cangjie_api/llms.txt This code demonstrates how to monitor UIAbility lifecycle transitions using AbilityMonitor. It allows defining callbacks for various lifecycle events such as creation, foreground, background, destruction, and window stage creation. The monitor is added to the delegator and can be waited upon for specific lifecycle states. ```cangjie import kit.TestKit.* import kit.AbilityKit.* let delegator = AbilityDelegatorRegistry.getAbilityDelegator() // Create monitor with lifecycle callbacks let monitor = AbilityMonitor( abilityName: "EntryAbility", moduleName: "entry", onAbilityCreate: { ability: UIAbility => AppLog.info("Ability created: ${ability.context.abilityInfo.name}") }, onAbilityForeground: { ability: UIAbility => AppLog.info("Ability moved to foreground") }, onAbilityBackground: { ability: UIAbility => AppLog.info("Ability moved to background") }, onAbilityDestroy: { ability: UIAbility => AppLog.info("Ability being destroyed") }, onWindowStageCreate: { ability: UIAbility => AppLog.info("Window stage created") } ) // Add monitor to delegator delegator.addAbilityMonitor(monitor) // Wait for ability to reach onCreate let ability = delegator.waitAbilityMonitor(monitor, timeout: 10000) // Remove monitor when done delegator.removeAbilityMonitor(monitor) ``` -------------------------------- ### Get Application Context (Cangjie) Source: https://github.com/super3001/harmonyos_testfwk_cangjie_api/blob/main/docs/en/cj-apis-ability_delegator_registry.md Retrieves the application's context object. The getAppContext() function returns a Context object, providing access to application-level resources and information. It is part of SystemCapability.Ability.AbilityRuntime.Core and available since version 21. ```cangjie public func getAppContext(): Context ```