1# arkXtest User Guide 2 3 4## Overview 5 6arkXtest is an automated test framework that consists of JsUnit and UiTest.<br>JsUnit is a unit test framework that provides basic APIs for compiling test cases and generating test reports for testing system and application APIs.<br>UiTest is a UI test framework that provides the UI component search and operation capabilities through simple and easy-to-use APIs, and allows you to develop automated test scripts based on GUI operations.<br>This document will help to familiarize you with arkXtest, describing its main functions, implementation principles, environment setup, and test script compilation and execution. In addition, the shell commands are provided for the following features: obtaining screenshots, component trees, recording user operations, and conveniently injecting UI simulation operations, which facilitates testing and verification. 7 8## Implementation 9 10arkXtest is divided into two parts: unit test framework and UI test framework.<br>As the backbone of arkXtest, the unit test framework offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results.<br>The UI test framework provides UiTest APIs for you to call in different test scenarios. Its test scripts are executed on top of the unit test framework. 11 12### Unit Test Framework 13 14 Figure 1 Main functions of the unit test framework 15 16  17 18 Figure 2 Basic script process 19 20  21 22### UI Test Framework 23 24 Figure 3 Main functions of the UI test framework 25 26  27 28## Compile and Execute Tests Based on ArkTS 29 30### Setting Up the Environment 31 32[Download DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download) and set it up as instructed on the official website. 33 34### Creating and Compiling a Test Script 35 36#### Creating a Test Script 37 38<!--RP2--> 391. Open DevEco Studio and create a project, in which the **ohos** directory is where the test script is located. 40 412. Open the .ets file of the module to be tested in the project directory. Move the cursor to any position in the code, and then right-click and choose **Show Context Actions** > **Create Ohos Test** or press **Alt+Enter** and choose **Create Ohos Test** to create a test class. For more details, see [DevEco Studio User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/harmonyos_jnit_jsunit-0000001092459608-V3?catalogVersion=V3#section13366184061415). 42 43<!--RP2End--> 44 45#### Writing a Unit Test Script 46 47This section describes how to use the unit test framework to write a unit test script. For details about the functionality of the unit test framework, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md). 48 49The unit test script must contain the following basic elements: 50 511. Import of the dependencies so that the dependent test APIs can be used. 52 532. Test code, mainly about the related logic, such as API invoking. 54 553. Invoking of the assertion APIs and setting of checkpoints. If there is no checkpoint, the test script is considered as incomplete. 56 57The following sample code is used to start the test page to check whether the page displayed on the device is the expected page. 58 59```ts 60import { describe, it, expect } from '@ohos/hypium'; 61import { abilityDelegatorRegistry } from '@kit.TestKit'; 62import { UIAbility, Want } from '@kit.AbilityKit'; 63 64const delegator = abilityDelegatorRegistry.getAbilityDelegator() 65const bundleName = abilityDelegatorRegistry.getArguments().bundleName; 66function sleep(time: number) { 67 return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); 68} 69export default function abilityTest() { 70 describe('ActsAbilityTest', () =>{ 71 it('testUiExample',0, async (done: Function) => { 72 console.info("uitest: TestUiExample begin"); 73 //start tested ability 74 const want: Want = { 75 bundleName: bundleName, 76 abilityName: 'EntryAbility' 77 } 78 await delegator.startAbility(want); 79 await sleep(1000); 80 // Check the top display ability. 81 const ability: UIAbility = await delegator.getCurrentTopAbility(); 82 console.info("get top ability"); 83 expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); 84 done(); 85 }) 86 }) 87} 88``` 89 90#### Writing a UI Test Script 91 92 <br>To write a UI test script to complete the corresponding test activities, simply add the invoking of the UiTest API to a unit test script. <!--RP1-->For details about the available APIs, see [@ohos.UiTest](..reference/apis-test-kit/js-apis-uitest.md).<!--RP1End--><br>In this example, the UI test script is written based on the preceding unit test script. It implements the click operation on the started application page and checks whether the page changes as expected. 93 941. Write the demo code in the **index.ets**file. 95 96 ```ts 97 @Entry 98 @Component 99 struct Index { 100 @State message: string = 'Hello World' 101 102 build() { 103 Row() { 104 Column() { 105 Text(this.message) 106 .fontSize(50) 107 .fontWeight(FontWeight.Bold) 108 Text("Next") 109 .fontSize(50) 110 .margin({top:20}) 111 .fontWeight(FontWeight.Bold) 112 Text("after click") 113 .fontSize(50) 114 .margin({top:20}) 115 .fontWeight(FontWeight.Bold) 116 } 117 .width('100%') 118 } 119 .height('100%') 120 } 121 } 122 ``` 123 1242. Write test code in the .test.ets file under **ohosTest** > **ets** > **test**. 125 126 ```ts 127 import { describe, it, expect } from '@ohos/hypium'; 128 // Import the test dependencies. 129 import { abilityDelegatorRegistry, Driver, ON } from '@kit.TestKit'; 130 import { UIAbility, Want } from '@kit.AbilityKit'; 131 132 const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() 133 const bundleName = abilityDelegatorRegistry.getArguments().bundleName; 134 function sleep(time: number) { 135 return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); 136 } 137 export default function abilityTest() { 138 describe('ActsAbilityTest', () => { 139 it('testUiExample',0, async (done: Function) => { 140 console.info("uitest: TestUiExample begin"); 141 //start tested ability 142 const want: Want = { 143 bundleName: bundleName, 144 abilityName: 'EntryAbility' 145 } 146 await delegator.startAbility(want); 147 await sleep(1000); 148 // Check the top display ability. 149 const ability: UIAbility = await delegator.getCurrentTopAbility(); 150 console.info("get top ability"); 151 expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); 152 // UI test code 153 // Initialize the driver. 154 const driver = Driver.create(); 155 await driver.delayMs(1000); 156 // Find the button on text 'Next'. 157 const button = await driver.findComponent(ON.text('Next')); 158 // Click the button. 159 await button.click(); 160 await driver.delayMs(1000); 161 // Check text. 162 await driver.assertComponentExist(ON.text('after click')); 163 await driver.pressBack(); 164 done(); 165 }) 166 }) 167 } 168 ``` 169 170### Running the Test Script 171 172#### In DevEco Studio 173 174To execute the script, you need to connect to a hardware device. You can run a test script in DevEco Studio in any of the following modes: 175 1761. Test package level: All test cases in the test package are executed. 177 1782. Test suite level: All test cases defined in the **describe** method are executed. 179 1803. Test method level: The specified **it** method, that is, a single test case, is executed. 181 182 183 184**Viewing the Test Result** 185 186After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure. 187 188 189 190**Viewing the Test Case Coverage** 191 192After the test is complete, you can view the test coverage. For details, see the coverage statistics modes in [Code Test](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/ide-code-test-V5). 193 194#### In the CMD 195 196To run the script, you need to connect to a hardware device, install the application test package on the test device, and run the **aa** command in the cmd window. 197 198> **NOTE** 199> 200> Before running commands in the CLI, make sure hdc-related environment variables have been configured. 201 202The table below lists the keywords in **aa** test commands. 203 204| Keyword | Abbreviation| Description | Example | 205| ------------- | ------------ | -------------------------------------- | ---------------------------------- | 206| --bundleName | -b | Application bundle name. | - b com.test.example | 207| --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry | 208| --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry | 209| NA | -s | \<key, value> pair.| - s unittest /ets/testrunner/OpenHarmonyTestRunner | 210 211The framework supports multiple test case execution modes, which are triggered by the key-value pair following the **-s** keyword. The table below lists the available keys and values. 212 213| Name | Description | Value | Example | 214| ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- | 215| unittest | **OpenHarmonyTestRunner** object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner | 216| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt | 217| notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt | 218| itName | Test case to be executed. | {itName} | -s itName testAttributeIt | 219| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value **5000** is used. | -s timeout 15000 | 220| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion failure or error occurs.| **true**/**false** (default value) | -s breakOnError true | 221| random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true | 222| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function | 223| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | 224| size | Size of the test case to be executed. | small, medium, large | -s size small 225| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 | 226 227**Running Commands** 228 229> **NOTE** 230> 231>Parameter configuration and commands are based on the stage model. 232 233 234Example 1: Execute all test cases. 235 236```shell 237 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner 238``` 239 240Example 2: Execute cases in the specified test suites, separated by commas (,). 241 242```shell 243 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s class s1,s2 244``` 245 246Example 3: Execute specified cases in the specified test suites, separated by commas (,). 247 248```shell 249 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s class testStop#stop_1,testStop1#stop_0 250``` 251 252Example 4: Execute all test cases except the specified ones, separated by commas (,). 253 254```shell 255 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s notClass testStop 256``` 257 258Example 5: Execute specified test cases, separated by commas (,). 259 260```shell 261 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s itName stop_0 262``` 263 264Example 6: Set the timeout interval for executing a test case. 265 266```shell 267 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s timeout 15000 268``` 269 270Example 7: Enable break-on-error mode. 271 272```shell 273 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s breakOnError true 274``` 275 276Example 8: Execute test cases of the specified type. 277 278```shell 279 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s testType function 280``` 281 282Example 9: Execute test cases at the specified level. 283 284```shell 285 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s level 0 286``` 287 288Example 10: Execute test cases with the specified size. 289 290```shell 291 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s size small 292``` 293 294Example 11: Execute test cases for a specified number of times. 295 296```shell 297 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s stress 1000 298``` 299 300**Viewing the Test Result** 301 302- During test execution in the CLI, the log information similar to the following is displayed: 303 304 ``` 305 OHOS_REPORT_STATUS: class=testStop 306 OHOS_REPORT_STATUS: current=1 307 OHOS_REPORT_STATUS: id=JS 308 OHOS_REPORT_STATUS: numtests=447 309 OHOS_REPORT_STATUS: stream= 310 OHOS_REPORT_STATUS: test=stop_0 311 OHOS_REPORT_STATUS_CODE: 1 312 313 OHOS_REPORT_STATUS: class=testStop 314 OHOS_REPORT_STATUS: current=1 315 OHOS_REPORT_STATUS: id=JS 316 OHOS_REPORT_STATUS: numtests=447 317 OHOS_REPORT_STATUS: stream= 318 OHOS_REPORT_STATUS: test=stop_0 319 OHOS_REPORT_STATUS_CODE: 0 320 OHOS_REPORT_STATUS: consuming=4 321 ``` 322 323| Log Field | Description | 324| ------- | -------------------------| 325| OHOS_REPORT_SUM | Total number of test cases in the current test suite.| 326| OHOS_REPORT_STATUS: class | Name of the test suite that is being executed.| 327| OHOS_REPORT_STATUS: id | Case execution language. The default value is JS. | 328| OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.| 329| OHOS_REPORT_STATUS: stream | Error information of the current test case.| 330| OHOS_REPORT_STATUS: test| Name of the current test case.| 331| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. **0**: pass.<br>**1**: error.<br>**2**: fail.| 332| OHOS_REPORT_STATUS: consuming | Time spent in executing the current test case, in milliseconds.| 333 334- After the commands are executed, the following log information is displayed: 335 336 ``` 337 OHOS_REPORT_RESULT: stream=Tests run: 447, Failure: 0, Error: 1, Pass: 201, Ignore: 245 338 OHOS_REPORT_CODE: 0 339 340 OHOS_REPORT_RESULT: breakOnError model, Stopping whole test suite if one specific test case failed or error 341 OHOS_REPORT_STATUS: taskconsuming=16029 342 343 ``` 344 345| Log Field | Description | 346| ------------------| -------------------------| 347| run | Total number of test cases in the current test package.| 348| Failure | Number of failed test cases.| 349| Error | Number of test cases whose execution encounters errors. | 350| Pass | Number of passed test cases.| 351| Ignore | Number of test cases not yet executed.| 352| taskconsuming| Total time spent in executing the current test case, in milliseconds.| 353 354> **NOTE** 355> 356> When an error occurs in break-on-error mode, check the **Ignore** and interrupt information. 357 358## Executing Tests Based on Shell Commands 359 360During development, you can use shell commands to quickly perform operations such as screenshot capturing, screen recording, UI injection simulation, and component tree obtaining. 361 362> **NOTE** 363> 364> Before running commands in the CLI, make sure hdc-related environment variables have been configured. 365 366**Commands** 367| Command | Parameter |Description | 368|---------------|---------------------------------|---------------------------------| 369| help | help| Displays the commands supported by the uitest tool. | 370| screenCap |[-p] | Captures the current screen. This parameter is optional.<br>The file can be stored only in **/data/local/tmp/** by default.<br>The file name is in the format of **Timestamp + .png**.| 371| dumpLayout |[-p] \<-i \| -a>|Obtains the component tree when the daemon is running.<br> **-p**: specifies the path and name of the file, which can be stored only in **/data/local/tmp/** by default. The file name is in the format of **Timestamp + .json**.<br> **-i**: disables filtering of invisible components and window merging.<br> **-a**: stores the data of the **BackgroundColor**, **Content**, **FontColor**, **FontSize** and **extraAttrs** attributes.<br> The preceding attribute data is not saved by default.<br> The **-a** and **-i** parameters cannot be used at the same time.| 372| uiRecord | uiRecord \<record \| read>|Records UI operations.<br> **record**: starts recording the operations on the current page to **/data/local/tmp/record.csv**. To stop recording, press **Ctrl+C**.<br> **read**: Reads and prints recorded data.<br>For details about the parameters, see [Recording User Operations](#recording-user-operations).| 373| uiInput | \<help \| click \| doubleClick \| longClick \| fling \| swipe \| drag \| dircFling \| inputText \| keyEvent>| Injects simulated UI operations.<br>For details about the parameters, see [Injecting Simulated UI Operations](#injecting-simulated-ui-operations). | 374| --version | --version|Obtains the version information about the current tool. | 375| start-daemon|start-daemon| Starts the uitest process.| 376 377### Example of Capturing Screenshots 378 379```bash 380# Specify the file name in the format of Timestamp + .png. 381hdc shell uitest screenCap 382# Save the file in /data/local/tmp/. 383hdc shell uitest screenCap -p /data/local/tmp/1.png 384``` 385 386### Example of Obtaining the Component Tree 387 388```bash 389hdc shell uitest dumpLayout -p /data/local/tmp/1.json 390``` 391 392### Recording User Operations 393>**NOTE** 394> 395> During the recording, you should perform the next operation after the recognition result of the current operation is displayed in the command line. 396 397```bash 398# Record the operations on the current page to **/data/local/tmp/record.csv**. To stop the recording, press **Ctrl+C**. 399hdc shell uitest uiRecord record 400# Read and print record data. 401hdc shell uitest uiRecord read 402``` 403 404The following describes the fields in the recording data: 405 406 ``` 407 { 408 "ABILITY": "com.ohos.launcher.MainAbility", // Foreground application page. 409 "BUNDLE": "com.ohos.launcher", // Application. 410 "CENTER_X": "", // Reserved field. 411 "CENTER_Y": "", // Reserved field. 412 "EVENT_TYPE": "pointer", // 413 "LENGTH": "0", // Total length. 414 "OP_TYPE": "click", // Event type. Currently, click, double-click, long-press, drag, pinch, swipe, and fling types are supported. 415 "VELO": "0.000000", // Hands-off velocity. 416 "direction.X": "0.000000",// Movement along the x-axis. 417 "direction.Y": "0.000000", // Movement along the y-axis. 418 "duration": 33885000.0, // Gesture duration. 419 "fingerList": [{ 420 "LENGTH": "0", // Total length. 421 "MAX_VEL": "40000", // Maximum velocity. 422 "VELO": "0.000000", // Hands-off velocity. 423 "W1_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Starting component bounds. 424 "W1_HIER": "ROOT,3,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0", // Starting component hierarchy. 425 "W1_ID": "", // ID of the starting component. 426 "W1_Text": "", // Text of the starting component. 427 "W1_Type": "Image", // Type of the starting component. 428 "W2_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Ending component bounds. 429 "W2_HIER": "ROOT,3,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0", // Ending component hierarchy. 430 "W2_ID": "", // ID of the ending component. 431 "W2_Text": "", // Text of the ending component. 432 "W2_Type": "Image", // Type of the ending component. 433 "X2_POSI": "47", // X coordinate of the ending point. 434 "X_POSI": "47", // X coordinate of the starting point. 435 "Y2_POSI": "301", // Y coordinate of the ending point. 436 "Y_POSI": "301", // Y coordinate of the starting point. 437 "direction.X": "0.000000", // Movement along the x-axis. 438 "direction.Y": "0.000000" // Movement along the y-axis. 439 }], 440 "fingerNumber": "1" // Number of fingers. 441 } 442 ``` 443 444### Injecting Simulated UI Operations 445 446| Command | Mandatory| Description | 447|------|------|-----------------| 448| help | Yes | Displays help information about the uiInput commands.| 449| click | Yes | Simulates a click event. | 450| doubleClick | Yes | Simulates a double-click event. | 451| longClick | Yes | Simulates a long-click event. | 452| fling | Yes | Simulates a fling event. | 453| swipe | Yes | Simulates a swipe event. | 454| drag | Yes | Simulates a drag event. | 455| dircFling | Yes | Simulates a directional fling event. | 456| inputText | Yes | Simulates a text input event. | 457| keyEvent | Yes | Simulates a physical key event (such as pressing a keyboard key, pressing the power key, returning to the previous page, or returning to the home screen) or a key combination. | 458 459 460#### Example of Running the click/doubleClick/longClick Commands 461 462| Parameter | Mandatory| Description | 463|---------|------|-----------------| 464| point_x | Yes | The x-coordinate point to click.| 465| point_y | Yes | The y-coordinate point to click.| 466 467```shell 468# Execute the click event. 469hdc shell uitest uiInput click 100 100 470 471# Execute the double-click event. 472hdc shell uitest uiInput doubleClick 100 100 473 474# Execute a long-click event. 475hdc shell uitest uiInput longClick 100 100 476``` 477 478#### Example of Running the uiInput fling Command 479 480| Parameter | Mandatory | Description | 481|------|------------------|-----------------| 482| from_x | Yes | The x-coordinate of the start point.| 483| from_y | Yes | The y-coordinate of the start point.| 484| to_x | Yes | The x-coordinate of the stop point.| 485| to_y | Yes | The y-coordinate of the stop point.| 486| swipeVelocityPps_ | No | Swipe speed, in px/s. Value range: 200 to 40000.<br> The default value is 600.| 487| stepLength_ | No| The step length. The default value is the sliding distance divided by 50.<br> To achieve better simulation effect, you are advised to use the default values. | 488 489 490```shell 491# Execute the fling event. The default value of stepLength_ is used. 492hdc shell uitest uiInput fling 10 10 200 200 500 493``` 494 495#### Example of Running the uiInput swipe/drag Command 496 497| Parameter | Mandatory | Description | 498|------|------------------|-----------------| 499| from_x | Yes | The x-coordinate of the start point.| 500| from_y | Yes | The y-coordinate of the start point.| 501| to_x | Yes | The x-coordinate of the stop point.| 502| to_y | Yes | The y-coordinate of the stop point.| 503| swipeVelocityPps_ | No | Swipe speed, in px/s. Value range: 200 to 40000.<br> The default value is 600.| 504 505```shell 506# Execute the swipe event. 507hdc shell uitest uiInput swipe 10 10 200 200 500 508 509# Execute the drag event. 510hdc shell uitest uiInput drag 10 10 100 100 500 511``` 512 513#### Example of Running the uiInput dircFling Command 514 515| Parameter | Mandatory | Description| 516|-------------------|-------------|----------| 517| direction | No| Fling direction, which can be **0**, **1**, **2**, or **3**. The default value is **0**.<br> The value **0** indicates leftward fling, **1** indicates rightward fling, **2** indicates upward fling, and **3** indicates downward fling. | 518| swipeVelocityPps_ | No| Swipe speed, in px/s. Value range: 200 to 40000.<br> The default value is 600. | 519| stepLength | No | The step length.<br> The default value is the sliding distance divided by 50. To achieve better simulation effect, you are advised to use the default values.| 520 521```shell 522# Execute the leftward fling event. 523hdc shell uitest uiInput dircFling 0 500 524# Execute the rightward fling event. 525hdc shell uitest uiInput dircFling 1 600 526# Execute the upward fling event. 527hdc shell uitest uiInput dircFling 2 528# Execute the downward fling event. 529hdc shell uitest uiInput dircFling 3 530``` 531 532#### Example of Running the uiInput inputText Command 533 534| Parameter | Mandatory | Description| 535|------|------------------|----------| 536| point_x | Yes | The x-coordinate of the input box.| 537| point_y | Yes | The y-coordinate of the input box.| 538| text | Yes | Text in the input box. | 539 540```shell 541# Execute the input text event. 542hdc shell uitest uiInput inputText 100 100 hello 543``` 544 545#### Example of Running the uiInput keyEvent Command 546 547| Parameter | Mandatory | Description| 548|------|------|----------| 549| keyID1 | Yes | ID of a physical key, which can be **KeyCode**, **Back**, **Home**, or **Power**.<br>When the value is set to **Back**, **Home**, or **Power**, the combination keys are not supported.| 550| keyID2 | No | ID of a physical key.| 551| keyID3 | No | ID of a physical key.| 552 553>**NOTE** 554> 555> A maximum of three key values can be passed. <!--RP3-->For details about the key values, see [KeyCode](../reference/apis-input-kit/js-apis-keycode.md)<!--RP3End-->. 556 557```shell 558# Back to home page. 559hdc shell uitest uiInput keyEvent Home 560# Back to the last page. 561hdc shell uitest uiInput keyEvent Back 562# Perform a key combination to copy and paste text. 563hdc shell uitest uiInput keyEvent 2072 2038 564``` 565 566### Obtaining the Version Information 567 568```bash 569hdc shell uitest --version 570``` 571### Starting the Uitest Process 572 573```shell 574hdc shell uitest start-daemon 575``` 576 577>**NOTE** 578> 579> You need to enable the developer mode for the device. 580> 581> Only the test HAP started by the **aa test** ability can call the ability of the UiTest. 582> 583> <!--RP4-->The <!--RP4End-->[Ability Privilege Level (APL)](../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism) of the <!--RP4End-->test HAP must be **system_basic** or **normal**. 584 585<!--Del--> 586## Examples 587 588### Unit Test Scripts 589 590#### Using Assertion APIs of the Unit Test 591For details about how to use the available APIs, see [Example of Using Assertion APIs](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/assertExampleTest/assertExample.test.ets). 592 593#### Defining Unit Test Suites 594For details about how to define and nest the unit test suite, see [Example of Defining Test Suites](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/coverExampleTest/coverExample.test.ets). 595 596#### Testing Custom Application Functions Using Unit Test 597For details about how to test the custom functions in an application, see [Example of Testing Custom Application Functions](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/customExampleTest/customExample.test.ets). 598 599#### Using Data-Driven Capability of the Unit Test 600For details about how to use the data-driven capability and configure repeat script execution, see [Example of Using Data-Driven Capability](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/paramExampleTest/paramExample.test.ets). 601 602### UI Test Scripts for Components 603 604#### Searching for Specified Components 605For details about how to search for a component in an application UI by specifying the attributes of the component, see [Example of Searching for Specified Components](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/findCommentExampleTest/Component/findCommentExample.test.ets). 606 607#### Simulating Click Events 608For details about how to simulate a click event, a long-click event or a double-click event, see [Example of Simulating Click Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/clickEvent.test.ets). 609 610#### Simulating Mouse Events 611For details about how to simulate a mouse left-click event, a mouse right-click event, or a mouse scroll wheel event, see [Example of Simulating Mouse Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/MouseEvent.test.ets). 612 613#### Simulating Input Events 614For details about how to simulate the input of Chinese and English text, see [Example of Simulating Input Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/InputEvent.test.ets). 615 616#### Simulating Screenshot Events 617For details about how to simulate capturing a screenshot (in a specified area), see [Example of Simulating Screenshot Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/ScreenCapEvent.test.ets). 618 619#### Simulating Fling Events 620For details about how to simulate a fling event (the finger leaves the screen after sliding), see [Example of Simulating Fling Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/FlingEvent.test.ets). 621 622#### Simulating Swipe Events 623For details about how to simulate a swipe event (the finger stays on the screen after sliding), see [Example of Simulating Swipe Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/SwipeEvent.test.ets). 624 625#### Simulating Pinch Events 626For details about how to simulate a zoom-in and zoom-out operation on pictures, see [Example of Simulating Pinch Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/PinchEvent.test.ets). 627 628#### Simulating Scroll Events 629For details about how to simulate components scrolling, see [Example of Simulating Scroll Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/ScrollerEvent.test.ets). 630 631### UI Test Scripts for Windows 632 633#### Searching for Specified Windows 634For details about how to search for an application window by using the bundle name of the application, see [Example of Searching for Specified Windows](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/findCommentExampleTest/window/findWindowExample.test.ets). 635 636#### Simulating Window Move Events 637For details about how to simulate moving a window to a specified position, see [Example of Simulating Window Move Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/window/MoveToEvent.test.ets). 638 639#### Simulating Window Size Adjustments 640For details about how to simulate a window size adjustment and direction specification, see [Example of Simulating Window Size Adjustments](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/window/ReSizeWindow.test.ets). 641 642<!--DelEnd--> 643 644## FAQs 645 646### FAQs About Unit Test Cases 647 6481. The logs in the test case are printed after the test case result 649 650**Problem** 651 652The logs added to the test case are displayed after the test case execution, rather than during the test case execution. 653 654**Possible Causes** 655 656More than one asynchronous API is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete. 657 658**Solutions** 659 660If more than one asynchronous API is called, you are advised to encapsulate the API invoking into the promise mode. 661 662**Error "fail to start ability" is reported during test case execution** 663 664**Problem** 665 666When a test case is executed, the console returns the error message "fail to start ability". 667 668**Possible Causes** 669 670An error occurs during the packaging of the test package, and the test framework dependency file is not included in the test package. 671 672**Solutions** 673 674Check whether the test package contains the **OpenHarmonyTestRunner.abc** file. If the file does not exist, rebuild and pack the file and perform the test again. 675 676Test case execution timeout 677 678**Problem** 679 680After the test case execution is complete, the console displays the error message "execute time XXms", indicating that the case execution times out. 681 682**Possible Causes** 683 6841. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. 685 6862. The time taken for API invocation is longer than the timeout interval set for test case execution. 687 6883. Test assertion fails, and a failure exception is thrown. As a result, the test case execution does not end until it times out. 689 690**Solutions** 691 6921. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails. 693 6942. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio. 695 6963. Check the code logic and assertion result of the test case and make sure that the assertion is passed. 697### FAQs About UI Test Cases 698 699**The failure log contains "Get windows failed/GetRootByWindow failed"** 700 701**Problem** 702 703The UI test case fails to be executed. The HiLog file contains the error message "Get windows failed/GetRootByWindow failed." 704 705**Possible Causes** 706 707The ArkUI feature is disabled. As a result, the component tree information is not generated on the test page. 708 709**Solutions** 710 711Run the following command, restart the device, and execute the test case again: 712 713```shell 714hdc shell param set persist.ace.testmode.enabled 1 715``` 716 717**The failure log contains "uitest-api does not allow calling concurrently"** 718 719**Problem** 720 721The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently." 722 723**Possible Causes** 724 7251. In the test case, the **await** operator is not added to the asynchronous API provided by the UI test framework. 726 7272. The UI test case is executed in multiple processes. As a result, multiple UI test processes are started. The framework does not support multi-process invoking. 728 729**Solutions** 730 7311. Check the case implementation and add the **await** operator to the asynchronous API. 732 7332. Do not execute UI test cases in multiple processes. 734 735The failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object". 736 737**Problem** 738 739The UI test case fails to be executed. The HiLog file contains the error message "does not exist on current UI! Check if the UI has changed after you got the widget object." 740 741**Possible Causes** 742 743After the target component is found in the code of the test case, the device UI changes, resulting in loss of the found component and inability to perform emulation. 744 745**Solutions** 746 747Run the UI test case again. 748