1# arkXtest User Guide 2 3 4## Overview 5 6arkXtest is an automated test framework that consists of JsUnit, UiTest, and PerfTest.<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>PerfTest is a white-box performance test framework based on code segments. It can collect performance data generated during the execution of a specified code segment or in a specified scenario.<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 three parts: unit test framework, UI test framework, and white-box performance 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.<br>The white-box performance test framework provides PerfTest APIs for you to call in code segment-based performance test scenarios. Its test scripts are developed based on the unit test framework. 11 12### Unit Test Framework 13 14 Figure 1 Main features 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 features of the UI test framework 25 26  27 28### White-Box Performance Test Framework 29 30 Figure 4 Main features of the white-box performance test framework 31 32 <img src="figures/perftest.PNG" alt="perftest" width="760"> 33 34## Compiling and Executing Tests Based on ArkTS 35 36### Setting Up the Environment 37 38[Download DevEco Studio](https://developer.huawei.com/consumer/en/download/) and set it up as instructed on the official website. 39 40### Creating and Compiling a Test Script 41 42#### Creating a Test Script 43 44<!--RP2--> 45Open DevEco Studio and create a project, in which the **ohos** directory is where the test script is located. 46 47Open 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). 48 49<!--RP2End--> 50 51#### Writing a Unit Test Script 52 53This 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 [JsUnit Features](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md#jsunit-features). 54 55The unit test script must contain the following basic elements: 56 571. Import of the dependencies so that the dependent test APIs can be used. 58 592. Test code, mainly about the related logic, such as API invoking. 60 613. Invoking of the assertion APIs and setting of checkpoints. If there is no checkpoint, the test script is considered as incomplete. 62 63The following sample code is used to start the test page to check whether the page displayed on the device is the expected page. 64 65```ts 66import { describe, it, expect, Level } from '@ohos/hypium'; 67import { abilityDelegatorRegistry } from '@kit.TestKit'; 68import { UIAbility, Want } from '@kit.AbilityKit'; 69 70const delegator = abilityDelegatorRegistry.getAbilityDelegator(); 71function sleep(time: number) { 72 return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); 73} 74export default function abilityTest() { 75 describe('ActsAbilityTest', () =>{ 76 it('testUiExample',Level.LEVEL3, async (done: Function) => { 77 console.info("uitest: TestUiExample begin"); 78 await sleep(1000); 79 const bundleName = abilityDelegatorRegistry.getArguments().bundleName; 80 //start tested ability 81 const want: Want = { 82 bundleName: bundleName, 83 abilityName: 'EntryAbility' 84 } 85 await delegator.startAbility(want); 86 await sleep(1000); 87 // Check the top display ability. 88 const ability: UIAbility = await delegator.getCurrentTopAbility(); 89 console.info("get top ability"); 90 expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); 91 done(); 92 }) 93 }) 94} 95``` 96 97#### Writing a UI Test Script 98 99 <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. 100 1011. Write the demo code in the **index.ets**file. 102 ```ts 103 @Entry 104 @Component 105 struct Index { 106 @State message: string = 'Hello World'; 107 108 build() { 109 Row() { 110 Column() { 111 Text(this.message) 112 .fontSize(50) 113 .fontWeight(FontWeight.Bold) 114 Text("Next") 115 .fontSize(50) 116 .margin({top:20}) 117 .fontWeight(FontWeight.Bold) 118 Text("after click") 119 .fontSize(50) 120 .margin({top:20}) 121 .fontWeight(FontWeight.Bold) 122 } 123 .width('100%') 124 } 125 .height('100%') 126 } 127 } 128 ``` 129 1302. Write test code in the .test.ets file under **ohosTest** > **ets** > **test**. 131 ```ts 132 import { describe, it, expect, Level } from '@ohos/hypium'; 133 // Import the test dependencies. 134 import { abilityDelegatorRegistry, Driver, ON } from '@kit.TestKit'; 135 import { UIAbility, Want } from '@kit.AbilityKit'; 136 137 const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator(); 138 function sleep(time: number) { 139 return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); 140 } 141 export default function abilityTest() { 142 describe('ActsAbilityTest', () => { 143 it('testUiExample',Level.LEVEL3, async (done: Function) => { 144 console.info("uitest: TestUiExample begin"); 145 await sleep(1000); 146 const bundleName = abilityDelegatorRegistry.getArguments().bundleName; 147 //start tested ability 148 const want: Want = { 149 bundleName: bundleName, 150 abilityName: 'EntryAbility' 151 } 152 await delegator.startAbility(want); 153 await sleep(1000); 154 // Check the top display ability. 155 const ability: UIAbility = await delegator.getCurrentTopAbility(); 156 console.info("get top ability"); 157 expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); 158 // UI test code 159 // Initialize the driver. 160 const driver = Driver.create(); 161 await driver.delayMs(1000); 162 // Find the button on text 'Next'. 163 const button = await driver.findComponent(ON.text('Next')); 164 // Click the button. 165 await button.click(); 166 await driver.delayMs(1000); 167 // Check text. 168 await driver.assertComponentExist(ON.text('after click')); 169 await driver.pressBack(); 170 done(); 171 }) 172 }) 173 } 174 ``` 175 176#### Writing a White-Box Performance Test Script 177 178 <br>The white-box performance test script, based on the unit test script, additionally calls the **PerfTest** API. <!--RP5-->For details, see [API reference](../reference/apis-test-kit/js-apis-perftest.md)<!--RP5End-->. During the performance test, you can use the UI test framework APIs to simulate operations on the UI and test the performance in a specified scenario.<br>The following sample code shows how to test the application performance during function execution and the frame rate during list scrolling in the application. 179 1801. Test the application performance during function execution. 181 182- Add the **PerfUtils.ets** file to **main** > **ets** > **utils** and compile custom functions in the file. 183 184 ```ts 185 export class PerfUtils { 186 public static CalculateTest() { 187 let num: number = 0 188 for (let index = 0; index < 10000; index++) { 189 num++; 190 } 191 } 192 } 193 ``` 194 195- Write test code in the .test.ets file under **ohosTest** > **ets** > **test**. 196 197 ```ts 198 import { describe, it, expect, Level } from '@ohos/hypium'; 199 import { PerfMetric, PerfTest, PerfTestStrategy, PerfMeasureResult } from '@kit.TestKit'; 200 import { PerfUtils } from '../../../main/ets/utils/PerfUtils'; 201 202 export default function PerfTestTest() { 203 describe('PerfTestTest', () => { 204 it('testExample0', Level.LEVEL3, async (done: Function) => { 205 let metrics: Array<PerfMetric> = [PerfMetric.DURATION, PerfMetric.CPU_USAGE] // Specify the metrics to be tested. 206 let actionCode = async (finish: Callback<boolean>) => { // Use uitest to scroll the list in the test code segment. 207 await PerfUtils.CalculateTest() 208 finish(true); 209 }; 210 let perfTestStrategy: PerfTestStrategy = { // Define a test strategy. 211 metrics: metrics, 212 actionCode: actionCode, 213 }; 214 try { 215 let perfTest: PerfTest = PerfTest.create(perfTestStrategy); // Create a test task object PerfTest. 216 await perfTest.run(); // Execute the test. Use await to wait for the completion of the asynchronous function. 217 let res1: PerfMeasureResult = perfTest.getMeasureResult(PerfMetric.DURATION); // Obtain the test result of the duration. 218 let res2: PerfMeasureResult = perfTest.getMeasureResult(PerfMetric.CPU_USAGE); // Obtain the test result of the CPU usage. 219 perfTest.destroy(); // Destroy the PerfTest object. 220 expect(res1.average).assertLessOrEqual(1000); // Assert the performance test result. 221 expect(res2.average).assertLessOrEqual(30); // Assert the performance test result. 222 } catch (error) { 223 console.error(`Failed to execute perftest. Cause:${JSON.stringify(error)}`); 224 expect(false).assertTrue() 225 } 226 done(); 227 }) 228 }) 229 } 230 ``` 231 2322. Test the frame rate during list scrolling in the application. 233 234- Write the demo code in the **index.ets** file. 235 236 ```ts 237 @Entry 238 @Component 239 struct ListPage { 240 scroller: Scroller = new Scroller() 241 private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 242 build() { 243 Row() { 244 Column() { 245 Scroll(this.scroller) { 246 Column() { 247 ForEach(this.arr, (item: number) => { 248 Text(item.toString()) 249 .width('90%') 250 .height('40%') 251 .fontSize(80) 252 .textAlign(TextAlign.Center) 253 .margin({ top: 10 }) 254 }, (item: string) => item) 255 } 256 } 257 .width('100%') 258 .height('100%') 259 .scrollable(ScrollDirection.Vertical) 260 .scrollBar(BarState.On) 261 .scrollBarColor(Color.Gray) 262 } 263 .width('100%') 264 } 265 .height('100%') 266 } 267 } 268 ``` 269 270- Write test code in the .test.ets file under **ohosTest** > **ets** > **test**. 271 272 ```ts 273 import { describe, it, expect, Level } from '@ohos/hypium'; 274 import { PerfMetric, PerfTest, PerfTestStrategy, PerfMeasureResult } from '@kit.TestKit'; 275 import { abilityDelegatorRegistry, Driver, ON } from '@kit.TestKit'; 276 import { Want } from '@kit.AbilityKit'; 277 278 const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator(); 279 export default function PerfTestTest() { 280 describe('PerfTestTest', () => { 281 it('testExample',Level.LEVEL3, async (done: Function) => { 282 let driver = Driver.create(); 283 await driver.delayMs(1000); 284 const bundleName = abilityDelegatorRegistry.getArguments().bundleName; 285 const want: Want = { 286 bundleName: bundleName, 287 abilityName: 'EntryAbility' 288 }; 289 await delegator.startAbility(want); // Open the test page. 290 await driver.delayMs(1000); 291 let scroll = await driver.findComponent(ON.type('Scroll')); 292 await driver.delayMs(1000); 293 let center = await scroll.getBoundsCenter(); // Obtain the coordinates of the Scroll component. 294 await driver.delayMs(1000); 295 let metrics: Array<PerfMetric> = [PerfMetric.LIST_SWIPE_FPS] // Specify the test metric to the frame rate during list scrolling. 296 let actionCode = async (finish: Callback<boolean>) => { // Use uitest to scroll the list in the test code segment. 297 await driver.fling({x: center.x, y: Math.floor(center.y * 3 / 2)}, {x: center.x, y: Math.floor(center.y / 2)}, 50, 20000); 298 await driver.delayMs(3000); 299 finish(true); 300 }; 301 let resetCode = async (finish: Callback<boolean>) => { // Scroll to the top of the list. 302 await scroll.scrollToTop(40000); 303 await driver.delayMs(1000); 304 finish(true); 305 }; 306 let perfTestStrategy: PerfTestStrategy = { // Define a test strategy. 307 metrics: metrics, 308 actionCode: actionCode, 309 resetCode: resetCode, 310 iterations: 5, // Specify the number of test iterations. 311 timeout: 50000, // Specify the timeout interval of actionCode and resetCode. 312 }; 313 try { 314 let perfTest: PerfTest = PerfTest.create(perfTestStrategy); // Create a test task object PerfTest. 315 await perfTest.run(); // Execute the test. Use await to wait for the completion of the asynchronous function. 316 let res: PerfMeasureResult = perfTest.getMeasureResult(PerfMetric.LIST_SWIPE_FPS); // Obtain the test result of the frame rate during list scrolling. 317 perfTest.destroy(); // Destroy the PerfTest object. 318 expect(res.average).assertLargerOrEqual(60); // Assert the performance test result. 319 } catch (error) { 320 console.error(`Failed to execute perftest. Cause:${JSON.stringify(error)}`); 321 } 322 done(); 323 }) 324 }) 325 } 326 ``` 327 328### Running the Test Script 329 330#### In DevEco Studio 331 332To 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: 333 3341. Test package level: All test cases in the test package are executed. 335 3362. Test suite level: All test cases defined in the **describe** method are executed. 337 3383. Test method level: The specified **it** method, that is, a single test case, is executed. 339 340 341 342**Viewing the Test Result** 343 344After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure. 345 346 347 348**Viewing the Test Case Coverage** 349 350After 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/en/doc/harmonyos-guides/ide-code-test). 351 352#### In the CMD 353 354To 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. 355 356> **NOTE** 357> 358> Before running commands in the CLI, make sure hdc-related environment variables have been configured. 359 360The table below lists the keywords in **aa** test commands. 361 362| Keyword | Abbreviation| Description | Example | 363| ------------- | ------------ | -------------------------------------- | ---------------------------------- | 364| --bundleName | -b | Application bundle name. | - b com.test.example | 365| --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry | 366| --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry | 367| NA | -s | \<key, value> pair.| - s unittest /ets/testrunner/OpenHarmonyTestRunner | 368 369The 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. 370 371| Name | Description | Value | Example | 372| ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- | 373| unittest | **OpenHarmonyTestRunner** object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner | 374| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt | 375| notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt | 376| itName | Test case to be executed. | {itName} | -s itName testAttributeIt | 377| 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 | 378| 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** or **false** (default value) | -s breakOnError true | 379| random | Whether to execute test cases in random sequence. | **true** or **false** (default value) | -s random true | 380| testType | Type of the test case to be executed. | **function**, **performance**, **power**, **reliability**, **security**, **global**, **compatibility**, **user**, **standard**, **safety**, **resilience**| -s testType function | 381| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | 382| size | Size of the test case to be executed. | small, medium, large | -s size small 383| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 | 384 385**Running Commands** 386 387> **NOTE** 388> 389>Parameter configuration and commands are based on the stage model. 390 391 392Example 1: Execute all test cases. 393 394```shell 395 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner 396``` 397 398Example 2: Execute cases in the specified test suites, separated by commas (,). 399 400```shell 401 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s class s1,s2 402``` 403 404Example 3: Execute specified cases in the specified test suites, separated by commas (,). 405 406```shell 407 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s class testStop#stop_1,testStop1#stop_0 408``` 409 410Example 4: Execute all test cases except the specified ones, separated by commas (,). 411 412```shell 413 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s notClass testStop 414``` 415 416Example 5: Execute specified test cases, separated by commas (,). 417 418```shell 419 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s itName stop_0 420``` 421 422Example 6: Set the timeout interval for executing a test case. 423 424```shell 425 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s timeout 15000 426``` 427 428Example 7: Enable break-on-error mode. 429 430```shell 431 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s breakOnError true 432``` 433 434Example 8: Execute test cases of the specified type. 435 436```shell 437 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s testType function 438``` 439 440Example 9: Execute test cases at the specified level. 441 442```shell 443 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s level 0 444``` 445 446Example 10: Execute test cases with the specified size. 447 448```shell 449 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s size small 450``` 451 452Example 11: Execute test cases for a specified number of times. 453 454```shell 455 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s stress 1000 456``` 457 458**Viewing the Test Result** 459 460- During test execution in the CLI, the log information similar to the following is displayed: 461 462 ``` 463 OHOS_REPORT_STATUS: class=testStop 464 OHOS_REPORT_STATUS: current=1 465 OHOS_REPORT_STATUS: id=JS 466 OHOS_REPORT_STATUS: numtests=447 467 OHOS_REPORT_STATUS: stream= 468 OHOS_REPORT_STATUS: test=stop_0 469 OHOS_REPORT_STATUS_CODE: 1 470 471 OHOS_REPORT_STATUS: class=testStop 472 OHOS_REPORT_STATUS: current=1 473 OHOS_REPORT_STATUS: id=JS 474 OHOS_REPORT_STATUS: numtests=447 475 OHOS_REPORT_STATUS: stream= 476 OHOS_REPORT_STATUS: test=stop_0 477 OHOS_REPORT_STATUS_CODE: 0 478 OHOS_REPORT_STATUS: consuming=4 479 ``` 480 481| Log Field | Description | 482| ------- | -------------------------| 483| OHOS_REPORT_SUM | Total number of test cases in the current test suite.| 484| OHOS_REPORT_STATUS: class | Name of the test suite that is being executed.| 485| OHOS_REPORT_STATUS: id | Case execution language. The default value is JS. | 486| OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.| 487| OHOS_REPORT_STATUS: stream | Error information of the current test case.| 488| OHOS_REPORT_STATUS: test| Name of the current test case.| 489| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. **0**: pass.<br>**1**: error.<br>**2**: fail.| 490| OHOS_REPORT_STATUS: consuming | Time spent in executing the current test case, in milliseconds.| 491 492- After the commands are executed, the following log information is displayed: 493 494 ``` 495 OHOS_REPORT_RESULT: stream=Tests run: 447, Failure: 0, Error: 1, Pass: 201, Ignore: 245 496 OHOS_REPORT_CODE: 0 497 498 OHOS_REPORT_RESULT: breakOnError model, Stopping whole test suite if one specific test case failed or error 499 OHOS_REPORT_STATUS: taskconsuming=16029 500 501 ``` 502 503| Log Field | Description | 504| ------------------| -------------------------| 505| run | Total number of test cases in the current test package.| 506| Failure | Number of failed test cases.| 507| Error | Number of test cases whose execution encounters errors. | 508| Pass | Number of passed test cases.| 509| Ignore | Number of test cases not yet executed.| 510| taskconsuming| Total time spent in executing the current test case, in milliseconds.| 511 512> **NOTE** 513> 514> When an error occurs in break-on-error mode, check the **Ignore** and interrupt information. 515 516## Executing Tests Based on Shell Commands 517 518During development, you can use shell commands to quickly perform operations such as screenshot capturing, screen recording, UI injection simulation, and component tree obtaining. 519 520> **NOTE** 521> 522> Before running commands in the CLI, make sure hdc-related environment variables have been configured. 523 524**Commands** 525| Command | Parameter |Description | 526|---------------|---------------------------------|---------------------------------| 527| help | help| Displays the commands supported by the uitest tool. | 528| 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**.| 529| 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.| 530| 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).| 531| 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). | 532| --version | --version|Obtains the version information about the current tool. | 533| start-daemon|start-daemon| Starts the uitest process.| 534 535### Example of Capturing Screenshots 536 537```bash 538# Specify the file name in the format of Timestamp + .png. 539hdc shell uitest screenCap 540# Save the file in /data/local/tmp/. 541hdc shell uitest screenCap -p /data/local/tmp/1.png 542``` 543 544### Example of Obtaining the Component Tree 545 546```bash 547hdc shell uitest dumpLayout -p /data/local/tmp/1.json 548``` 549 550### Recording User Operations 551>**NOTE** 552> 553> During the recording, you should perform the next operation after the recognition result of the current operation is displayed in the command line. 554 555**Commands** 556| Command | Parameter | Mandatory| Description | 557|-------|--------------|------|-----------------| 558| -W | \<true/false> | No | Whether to save the component information corresponding to the operation coordinates to the **/data/local/tmp/record.csv** file during recording. The value **true** means to save the component information, and **false** means to record only the coordinate information. The default value is **true**.| 559| -l | | No | The current layout information is saved after each operation. The file path is **/data/local/tmp/layout_Start timestamp of the recording_Operation ID.json**.| 560| -c | \<true/false> | No | Whether to print the recorded operation event information to the console. The value **true** means to print the information, and **false** means the opposite. The default value is **true**.| 561 562```bash 563# Record the operations on the current page to **/data/local/tmp/record.csv**. To stop the recording, press **Ctrl+C**. 564hdc shell uitest uiRecord record 565# During recording, only record the coordinates corresponding to the operation and do not match the target component. 566hdc shell uitest uiRecord record -W false 567# After each operation, the page layout is saved in /data/local/tmp/layout_Start timestamp of the recording _Operation ID.json. 568hdc shell uitest uiRecord record -l 569# Do not print the recorded operation event information to the console. 570hdc shell uitest uiRecord record -c false 571# Read and print record data. 572hdc shell uitest uiRecord read 573``` 574 575The following describes the fields in the recording data: 576 577 ``` 578 { 579 "ABILITY": "com.ohos.launcher.MainAbility", // Foreground application page. 580 "BUNDLE": "com.ohos.launcher", // Application. 581 "CENTER_X": "", // Reserved field. 582 "CENTER_Y": "", // Reserved field. 583 "EVENT_TYPE": "pointer", // 584 "LENGTH": "0", // Total length. 585 "OP_TYPE": "click", // Event type. Currently, click, double-click, long-press, drag, pinch, swipe, and fling types are supported. 586 "VELO": "0.000000", // Hands-off velocity. 587 "direction.X": "0.000000",// Movement along the x-axis. 588 "direction.Y": "0.000000", // Movement along the y-axis. 589 "duration": 33885000.0, // Gesture duration. 590 "fingerList": [{ 591 "LENGTH": "0", // Total length. 592 "MAX_VEL": "40000", // Maximum velocity. 593 "VELO": "0.000000", // Hands-off velocity. 594 "W1_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Starting component bounds. 595 "W1_HIER": "ROOT,3,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0", // Starting component hierarchy. 596 "W1_ID": "", // ID of the starting component. 597 "W1_Text": "", // Text of the starting component. 598 "W1_Type": "Image", // Type of the starting component. 599 "W2_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Ending component bounds. 600 "W2_HIER": "ROOT,3,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0", // Ending component hierarchy. 601 "W2_ID": "", // ID of the ending component. 602 "W2_Text": "", // Text of the ending component. 603 "W2_Type": "Image", // Type of the ending component. 604 "X2_POSI": "47", // X coordinate of the ending point. 605 "X_POSI": "47", // X coordinate of the starting point. 606 "Y2_POSI": "301", // Y coordinate of the ending point. 607 "Y_POSI": "301", // Y coordinate of the starting point. 608 "direction.X": "0.000000", // Movement along the x-axis. 609 "direction.Y": "0.000000" // Movement along the y-axis. 610 }], 611 "fingerNumber": "1" // Number of fingers. 612 } 613 ``` 614 615### Injecting Simulated UI Operations 616 617| Command | Mandatory| Description | 618|------|------|-----------------| 619| help | Yes | Displays help information about the uiInput commands.| 620| click | Yes | Simulates a click event. For details, see **Examples of Using uiInput click/doubleClick/longClick**. | 621| doubleClick | Yes | Simulates a double-click event. For details, see **Examples of Using uiInput click/doubleClick/longClick**. | 622| longClick | Yes | Simulates a long-click event. For details, see **Examples of Using uiInput click/doubleClick/longClick**. | 623| fling | Yes | Simulates a fling event. For details, see **Examples of Using uiInput fling**. | 624| swipe | Yes | Simulates a swipe event. For details, see **Examples of Using uiInput swipe/drag**. | 625| drag | Yes | Simulates a drag event. For details, see **Examples of Using uiInput swipe/drag**. | 626| dircFling | Yes | Simulates a directional fling event. For details, see **Examples of Using uiInput dircFling**. | 627| inputText | Yes | Simulates text input in a text box at specified coordinates. For details, see **Examples of Using uiInput inputText**. | 628| text | Yes | Simulates text input in a text box at the focused position without specifying coordinates. For details, see **Examples of Using uiInput text**. | 629| 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. For details, see **Examples of Using uiInput keyEvent**. | 630 631 632#### Example of Running the click/doubleClick/longClick Commands 633 634| Parameter | Mandatory| Description | 635|---------|------|-----------------| 636| point_x | Yes | The x-coordinate point to click.| 637| point_y | Yes | The y-coordinate point to click.| 638 639```shell 640# Execute the click event. 641hdc shell uitest uiInput click 100 100 642 643# Execute the double-click event. 644hdc shell uitest uiInput doubleClick 100 100 645 646# Execute a long-click event. 647hdc shell uitest uiInput longClick 100 100 648``` 649 650#### Example of Running the uiInput fling Command 651 652| Parameter | Mandatory | Description | 653|------|------------------|-----------------| 654| from_x | Yes | The x-coordinate of the start point.| 655| from_y | Yes | The y-coordinate of the start point.| 656| to_x | Yes | The x-coordinate of the stop point.| 657| to_y | Yes | The y-coordinate of the stop point.| 658| swipeVelocityPps_ | No | Swipe speed, in px/s. The value ranges from 200 to 40000.<br> The default value is **600**.| 659| stepLength_ | No| Step length. The default value is the swipe distance divided by 50.<br> To achieve better simulation effect, you are advised to use the default value. | 660 661 662```shell 663# Execute the fling event. The default value of stepLength_ is used. 664hdc shell uitest uiInput fling 10 10 200 200 500 665``` 666 667#### Example of Running the uiInput swipe/drag Command 668 669| Parameter | Mandatory | Description | 670|------|------------------|-----------------| 671| from_x | Yes | The x-coordinate of the start point.| 672| from_y | Yes | The y-coordinate of the start point.| 673| to_x | Yes | The x-coordinate of the stop point.| 674| to_y | Yes | The y-coordinate of the stop point.| 675| swipeVelocityPps_ | No | Swipe speed, in px/s. The value ranges from 200 to 40000.<br> The default value is **600**.| 676 677```shell 678# Execute the swipe event. 679hdc shell uitest uiInput swipe 10 10 200 200 500 680 681# Execute the drag event. 682hdc shell uitest uiInput drag 10 10 100 100 500 683``` 684 685#### Example of Running the uiInput dircFling Command 686 687| Parameter | Mandatory | Description| 688|-------------------|-------------|----------| 689| 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. | 690| swipeVelocityPps_ | No| Swipe speed, in px/s. The value ranges from 200 to 40000.<br> The default value is 600. | 691| stepLength | No | Step length.<br> The default value is the swipe distance divided by 50. To achieve better simulation effect, you are advised to use the default value.| 692 693```shell 694# Execute the leftward fling event. 695hdc shell uitest uiInput dircFling 0 500 696# Execute the rightward fling event. 697hdc shell uitest uiInput dircFling 1 600 698# Execute the upward fling event. 699hdc shell uitest uiInput dircFling 2 700# Execute the downward fling event. 701hdc shell uitest uiInput dircFling 3 702``` 703 704#### Example of Running the uiInput inputText Command 705 706| Parameter | Mandatory | Description| 707|------|------------------|----------| 708| point_x | Yes | The x-coordinate of the input box.| 709| point_y | Yes | The y-coordinate of the input box.| 710| text | Yes | Text in the input box. | 711 712```shell 713# Execute the input text event. 714hdc shell uitest uiInput inputText 100 100 hello 715``` 716 717#### Example of Running the uiInput text Command 718 719| Parameter | Mandatory | Description| 720|------|------------------|----------| 721| text | Yes | Text in the input box. | 722 723```shell 724# Execute the text input in the text box at the focused position. If the current focused position does not support text input, no effect is displayed. 725hdc shell uitest uiInput text hello 726``` 727 728#### Example of Running the uiInput keyEvent Command 729 730| Parameter | Mandatory | Description | 731|------|------|---------------------------------------------------------------------------------------------------------------------------------| 732| keyID1 | Yes | ID of a physical key, which can be **Back**, **Home**, **Power**, or [a keycode value](../reference/apis-input-kit/js-apis-keycode.md#keycode).<br>When the value is set to **Back**, **Home**, or **Power**, combination keys are not supported.<br>Currently, the Caps Lock key (**KeyCode**=**2074**) does not take effect. Use composition keys to input uppercase letters. For example, press **Shift+V** to input uppercase letter V.| 733| keyID2 | No | ID of a physical key. Value range: [KeyCode](../reference/apis-input-kit/js-apis-keycode.md#keycode). This parameter is left empty by default. | 734| keyID3 | No | ID of a physical key. Value range: [KeyCode](../reference/apis-input-kit/js-apis-keycode.md#keycode). This parameter is left empty by default. | 735 736```shell 737# Back to home page. 738hdc shell uitest uiInput keyEvent Home 739# Back to the last page. 740hdc shell uitest uiInput keyEvent Back 741# Perform a key combination to copy and paste text. 742hdc shell uitest uiInput keyEvent 2072 2038 743# Input the lowercase letter v. 744hdc shell uitest uiInput keyEvent 2038 745# Input the uppercase letter V. 746hdc shell uitest uiInput keyEvent 2047 2038 747``` 748 749### Obtaining the Version Information 750 751```bash 752hdc shell uitest --version 753``` 754### Starting the Uitest Process 755 756```shell 757hdc shell uitest start-daemon 758``` 759 760>**NOTE** 761> 762> You need to enable the developer mode for the device. 763> 764> Only the test HAP started by the **aa test** ability can call the ability of the UiTest. 765> 766> 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**. 767 768<!--Del--> 769## Examples 770 771### Unit Test Scripts 772 773#### Using Assertion APIs of the Unit Test 774For details about how to use the available APIs, see [Example of Using Assertion APIs](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/assertExampleTest/assertExample.test.ets). 775 776#### Defining Unit Test Suites 777For details about how to define and nest the unit test suite, see [Example of Defining Test Suites](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/coverExampleTest/coverExample.test.ets). 778 779#### Testing Custom Application Functions Using Unit Test 780For details about how to test the custom functions in an application, see [Example of Testing Custom Application Functions](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/customExampleTest/customExample.test.ets). 781 782#### Using Data-Driven Capability of the Unit Test 783For details about how to use the data-driven capability and configure repeat script execution, see [Example of Using Data-Driven Capability](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/paramExampleTest/paramExample.test.ets). 784 785### UI Test Scripts for Components 786 787#### Searching for Specified Components 788For 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://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/findCommentExampleTest/Component/findCommentExample.test.ets). 789 790#### Simulating Click Events 791For details about how to simulate a click event, a long-click event or a double-click event, see [Example of Simulating Click Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/clickEvent.test.ets). 792 793#### Simulating Mouse Events 794For 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://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/MouseEvent.test.ets). 795 796#### Simulating Input Events 797For details about how to simulate Chinese and English text input, see [Example of Simulating Text Input Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/InputEvent.test.ets). 798 799#### Simulating Screenshot Events 800For details about how to simulate capturing a screenshot (in a specified area), see [Example of Simulating Screenshot Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/ScreenCapEvent.test.ets). 801 802#### Simulating Fling Events 803For details about how to simulate a fling event (the finger leaves the screen after swiping), see [Example of Simulating Fling Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/FlingEvent.test.ets). 804 805#### Simulating Swipe Events 806For details about how to simulate a swipe event (the finger stays on the screen after swiping), see [Example of Simulating Swipe Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/SwipeEvent.test.ets). 807 808#### Simulating Pinch Events 809For details about how to simulate a zoom-in and zoom-out operation on pictures, see [Example of Simulating Pinch Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/PinchEvent.test.ets). 810 811#### Simulating Scroll Events 812For details about how to simulate components scrolling, see [Example of Simulating Scroll Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/ScrollerEvent.test.ets). 813 814### UI Test Scripts for Windows 815 816#### Searching for Specified Windows 817For details about how to search for an application window based on the bundle name of the application, see [Example of Searching for Specified Windows](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/findCommentExampleTest/window/findWindowExample.test.ets). 818 819#### Simulating Window Move Events 820For details about how to simulate moving a window to a specified position, see [Example of Simulating Window Move Events](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/window/MoveToEvent.test.ets). 821 822#### Simulating Window Size Adjustments 823For details about how to simulate a window size adjustment and direction specification, see [Example of Simulating Window Size Adjustments](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/window/ReSizeWindow.test.ets). 824 825### White-Box Performance Test Script 826 827For details about how to call the PerfTest API to implement the white-box performance test capability, see [Example of White-Box Performance Test](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/Project/Test/perftest/entry/src/ohosTest/ets/test/PerfTest.test.ets). 828 829<!--DelEnd--> 830 831## FAQs 832 833### FAQs About Unit Test Cases 834 835**1. What should I do if logs in the test case are printed after the test case result?** 836 837**Problem** 838 839The logs added to the test case are displayed after the test case execution, rather than during the test case execution. 840 841**Possible Causes** 842 843More 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. 844 845**Solutions** 846 847If more than one asynchronous API is called, you are advised to encapsulate the API invoking into the promise mode. 848 849**2. What should I do if the message "error: fail to start ability" is reported during test case execution?** 850 851**Problem** 852 853When a test case is executed, the console returns the error message "fail to start ability". 854 855**Possible Causes** 856 857An error occurs during the packaging of the test package, and the test framework dependency file is not included in the test package. 858 859**Solutions** 860 861Check 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. 862 863**3. What should I do if a timeout error is reported during case execution?** 864 865**Problem** 866 867After the test case execution is complete, the console displays the error message "execute time XXms", indicating that the case execution times out. 868 869**Possible Causes** 870 8711. The test case is executed through an asynchronous API, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. 872 8732. The time taken for API invocation is longer than the timeout interval set for test case execution. 874 8753. Test assertion fails, and a failure exception is thrown. As a result, the test case execution does not end until it times out. 876 877**Solutions** 878 8791. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails. 880 8812. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio. 882 8833. Check the code logic and assertion result of the test case and make sure that the assertion is passed. 884### FAQs About UI Test Cases 885 886**1. What should I do if the failure log contains "Get windows failed/GetRootByWindow failed"?** 887 888**Problem** 889 890The UI test case fails to be executed. The HiLog file contains the error message "Get windows failed/GetRootByWindow failed." 891 892**Possible Causes** 893 894The ArkUI feature is disabled. As a result, the component tree information is not generated on the test page. 895 896**Solutions** 897 898Run the following command, restart the device, and execute the test case again: 899 900```shell 901hdc shell param set persist.ace.testmode.enabled 1 902``` 903 904**2. What should I do if the failure log contains "uitest-api does not allow calling concurrently"?** 905 906**Problem** 907 908The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently". 909 910**Possible Causes** 911 9121. In the test case, the **await** operator is not added to the asynchronous API provided by the UI test framework. 913 9142. 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. 915 916**Solutions** 917 9181. Check the case implementation and add the **await** operator to the asynchronous API. 919 9202. Do not execute UI test cases in multiple processes. 921 922**3. What should I do if the failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object"?** 923 924**Problem** 925 926The 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." 927 928**Possible Causes** 929 930After 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. 931 932**Solutions** 933 934Run the UI test case again. 935