提交 f527fee6 编写于 作者: E ester.zhou

Update docs (14175)

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 74931a3c
......@@ -42,13 +42,13 @@ arkXtest is divided into two parts: unit test framework and UI test framework.
- The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md).
## Environment preparations
## Preparing the Environment
### Environment Requirements
Software for writing test scripts: DevEco Studio 3.0 or later
Hardware for running test scripts: PC connected to a OpenHarmony device, such as the RK3568 development board
Hardware for running test scripts: PC connected to an OpenHarmony device, such as the RK3568 development board
### Setting Up the Environment
......@@ -63,8 +63,8 @@ Hardware for running test scripts: PC connected to a OpenHarmony device, such as
## Writing a Unit Test Script
```TS
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
const delegator = abilityDelegatorRegistry.getAbilityDelegator()
export default function abilityTest() {
......@@ -72,7 +72,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
......@@ -81,7 +81,7 @@ export default function abilityTest() {
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
done();
})
......@@ -119,7 +119,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
......@@ -128,7 +128,7 @@ export default function abilityTest() {
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
//ui test code
//init uidriver
......@@ -154,20 +154,180 @@ export default function abilityTest() {
## Running the Test Script
### In DevEco Studio
You can run a test script in DevEco Studio in any of the following modes:
- Test package level: All test cases in the test package are executed.
- Test suite level: All test cases defined in the **describe** method are executed.
- Test method level: The specified **it** method, that is, a single test case, is executed.
1. Test package level: All test cases in the test package are executed.
2. Test suite level: All test cases defined in the **describe** method are executed.
3. Test method level: The specified **it** method, that is, a single test case, is executed.
![](figures/Execute.PNG)
## Viewing the Test Result
**Viewing the Test Result**
After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure.
![](figures/TestResult.PNG)
### In the CLI
To run a test script in the CLI, execute **aa** commands with different execution control keywords.
Parameters in aa test commands
| Keyword | Abbreviation| Description | Example |
| ------------- | ------------ | -------------------------------------- | ---------------------------------- |
| --bundleName | -b | Application bundle name. | - b com.test.example |
| --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry |
| --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry |
| NA | -s | \<key, value> pair.| - s unittest OpenHarmonyTestRunner |
The 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.
| Key | Description | Value | Parameter |
| ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- |
| unittest | OpenHarmonyTestRunner object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner |
| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt |
| notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt |
| itName | Test case to be executed. | {itName} | -s itName testAttributeIt |
| 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 |
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
| size | Size of the test case to be executed. | small, medium, large | -s size small |
| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 |
**Running Commands**
> Configure hdc-related environment variables, and then perform the following:
- Open the CLI.
- Run the **aa test** commands.
Example 1: Execute all test cases.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner
```
Example 2: Execute cases in the specified test suites, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class s1,s2
```
Example 3: Execute specified cases in the specified test suites, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class testStop#stop_1,testStop1#stop_0
```
Example 4: Execute all test cases except the specified ones, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s notClass testStop
```
Example 5: Execute specified test cases, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s itName stop_0
```
Example 6: Set the timeout interval for executing a test case.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s timeout 15000
```
Example 7: Enable break-on-error mode.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s breakOnError true
```
Example 8: Execute test cases of the specified type.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s testType function
```
Example 9: Execute test cases at the specified level.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s level 0
```
Example 10: Execute test cases with the specified size.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s size small
```
Example 11: Execute test cases for a specified number of times.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s stress 1000
```
**Viewing the Test Result**
- During test execution in the CLI, the log information similar to the following is displayed:
```
OHOS_REPORT_STATUS: class=testStop
OHOS_REPORT_STATUS: current=1
OHOS_REPORT_STATUS: id=JS
OHOS_REPORT_STATUS: numtests=447
OHOS_REPORT_STATUS: stream=
OHOS_REPORT_STATUS: test=stop_0
OHOS_REPORT_STATUS_CODE: 1
OHOS_REPORT_STATUS: class=testStop
OHOS_REPORT_STATUS: current=1
OHOS_REPORT_STATUS: id=JS
OHOS_REPORT_STATUS: numtests=447
OHOS_REPORT_STATUS: stream=
OHOS_REPORT_STATUS: test=stop_0
OHOS_REPORT_STATUS_CODE: 0
OHOS_REPORT_STATUS: consuming=4
```
| Log Field | Description |
| ------- | -------------------------|
| OHOS_REPORT_SUM | Total number of test cases in the current test suite.|
| OHOS_REPORT_STATUS: class | Name of the test suite that is being executed.|
| OHOS_REPORT_STATUS: id | Case execution language. The default value is JS. |
| OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.|
| OHOS_REPORT_STATUS: stream | Error information of the current test case.|
| OHOS_REPORT_STATUS: test| Name of the current test case.|
| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. The options are as follows:<br>**0**: pass<br>**1**: error<br>**2**: fail|
| OHOS_REPORT_STATUS: consuming | Execution duration of the current test case.|
- After the commands are executed, the log information similar to the following is displayed:
```
OHOS_REPORT_RESULT: stream=Tests run: 447, Failure: 0, Error: 1, Pass: 201, Ignore: 245
OHOS_REPORT_CODE: 0
OHOS_REPORT_RESULT: breakOnError model, Stopping whole test suite if one specific test case failed or error
OHOS_REPORT_STATUS: taskconsuming=16029
```
| Log Field | Description |
| ------------------| -------------------------|
| run | Total number of test cases in the current test package.|
| Failure | Number of failed test cases.|
| Error | Number of test cases whose execution encounters errors. |
| Pass | Number of passed test cases.|
| Ignore | Number of test cases not executed.|
| taskconsuming| Total time spent in executing the current test case.|
> When an error occurs in break-on-error mode, check the **Ignore** and interrupt information.
## FAQs
### FAQs About Unit Test Cases
......@@ -182,7 +342,7 @@ The logs added to the test case are displayed after the test case execution, rat
More than one asynchronous interface is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete.
**Solution**
**Solution**
If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode
......@@ -209,14 +369,18 @@ After the test case execution is complete, the console displays the error messag
**Possible Causes**
1. 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.
2. The time taken for API invocation is longer than the timeout interval set for test case execution.
2. The time taken for API invocation is longer than the timeout interval set for test case execution.
3. Test assertion fails, and a failure exception is thrown. As a result, the test case execution does not end until the timeout expires.
**Solution**
1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails.
2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio.
2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio.
3. Check the code logic and assertion result of the test case and make sure that the assertion is passed.
### FAQs About UI Test Cases
#### The failure log contains "Get windows failed/GetRootByWindow failed"
......@@ -237,11 +401,11 @@ Run the following command, restart the device, and execute the test case again:
hdc shell param set persist.ace.testmode.enabled 1
```
#### The failure log contains "uitest-api dose not allow calling concurrently"
#### The failure log contains "uitest-api does not allow calling concurrently"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "uitest-api dose not allow calling concurrently".
The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently".
**Possible Causes**
......@@ -255,11 +419,11 @@ The UI test case fails to be executed. The HiLog file contains the error message
2. Do not execute UI test cases in multiple processes.
#### The failure log contains "dose not exist on current UI! Check if the UI has changed after you got the widget object"
#### The failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "dose not exist on current UI! Check if the UI has changed after you got the widget object".
The 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".
**Possible Causes**
......
......@@ -305,6 +305,7 @@ struct WebComponent {
Button('loadUrl')
.onClick(() => {
try {
// The URL to be loaded is of the string type.
this.controller.loadUrl('www.example.com');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
......@@ -316,6 +317,69 @@ struct WebComponent {
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// The headers parameter is carried.
this.controller.loadUrl('www.example.com', [{headerKey: "headerKey", headerValue: "headerValue"}]);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.webDebuggingAccess(true)
}
}
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// The URL to be loaded is of the Resource type.
this.controller.loadUrl($rawfile('xxx.html'));
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
```html
<!-- xxx.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
### loadData
loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void
......@@ -987,7 +1051,7 @@ Executes a JavaScript script. This API uses a promise to return the script execu
| Type | Description |
| --------------- | --------------------------------------------------- |
| Promise\<string> | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed|
| Promise\<string> | Promise used to return the result. Returns **null** if the JavaScript script fails to be executed|
**Error codes**
......@@ -4101,7 +4165,7 @@ Checks whether any saved HTTP authentication credentials exist. This API returns
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.|
| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise. |
**Example**
......
......@@ -21,6 +21,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController})
> **NOTE**
>
> Transition animation is not supported.
> Different **\<Web>** components on the same page must be bound to different **WebController**s.
**Parameters**
......@@ -526,7 +527,7 @@ Sets whether to enable the multi-window permission.
horizontalScrollBarAccess(horizontalScrollBar: boolean)
Sets whether to display the horizontal scrollbar, including the system default scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed.
Sets whether to display the horizontal scrollbar, including the default system scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed.
**Parameters**
......@@ -577,7 +578,7 @@ Sets whether to display the horizontal scrollbar, including the system default s
verticalScrollBarAccess(verticalScrollBar: boolean)
Sets whether to display the vertical scrollbar, including the system default scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed.
Sets whether to display the vertical scrollbar, including the default system scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed.
**Parameters**
......@@ -1539,7 +1540,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp
onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void)
Called when an error occurs during web page loading. For better results, simplify the implementation logic in the callback.
Called when an error occurs during web page loading. For better results, simplify the implementation logic in the callback. This API is called when there is no network connection.
**Parameters**
......@@ -1764,7 +1765,7 @@ Called when the document title of the web page is changed.
onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void)
Called when loading of the web page is complete. This API is used by an application to update the historical link it accessed..
Called when loading of the web page is complete. This API is used by an application to update the historical link it accessed.
**Parameters**
......@@ -1950,7 +1951,7 @@ Called when the display ratio of this page changes.
onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean)
Called when the **\<Web>** component is about to access a URL. This API is used to determine whether to block the access.
Called when the **\<Web>** component is about to access a URL. This API is used to determine whether to block the access, which is allowed by default.
**Parameters**
......@@ -2326,8 +2327,8 @@ Called when the scrollbar of the page scrolls.
| Name | Type | Description |
| ------- | ------ | ------------ |
| xOffset | number | Position of the scrollbar on the x-axis.|
| yOffset | number | Position of the scrollbar on the y-axis.|
| xOffset | number | Position of the scrollbar on the x-axis relative to the leftmost of the web page.|
| yOffset | number | Position of the scrollbar on the y-axis relative to the top of the web page.|
**Example**
......@@ -2668,7 +2669,7 @@ Called when the old page is not displayed and the new page is about to be visibl
onInterceptKeyEvent(callback: (event: KeyEvent) => boolean)
Called when the key event is intercepted, before being consumed by the Webview.
Called when the key event is intercepted and before it is consumed by the Webview.
**Parameters**
......
......@@ -8,10 +8,12 @@ Create a **\<Web>** component in the .ets file under **main/ets/MainAbility/page
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'https://www.example.com', controller: this.controller })
......@@ -26,11 +28,13 @@ When using the **\<Web>** component, you must specify the styles and attributes.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
fileAccess: boolean = true;
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Text('Hello world!')
......@@ -54,13 +58,15 @@ Add the **onProgressChange** event for the **\<Web>** component, which is trigge
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State progress: number = 0;
@State hideProgress: boolean = true;
fileAccess: boolean = true;
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Text('Hello world!')
......@@ -93,14 +99,17 @@ Add the **runJavaScript** method to the **onPageEnd** event. The **onPageEnd** e
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State progress: number = 0;
@State hideProgress: boolean = true;
@State webResult: string = ''
fileAccess: boolean = true;
// Define the controller for the \<Web> component.
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Text('Hello world!')
......@@ -124,8 +133,23 @@ struct WebComponent {
})
.onPageEnd(e => {
// test() is defined in index.html.
this.controller.runJavaScript({ script: 'test()' });
console.info('url: ', e.url);
try {
this.controller.runJavaScript(
'test()',
(error, result) => {
if (error) {
console.info(`run JavaScript error: ` + JSON.stringify(error))
return;
}
if (result) {
this.webResult = result
console.info(`The test() return value is: ${result}`)
}
});
console.info('url: ', e.url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Text('End')
.fontSize(20)
......@@ -160,10 +184,12 @@ The configuration procedure is as follows:
1. Set the **webDebuggingAccess** attribute of the **\<Web>** component to **true**.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
......@@ -189,20 +215,30 @@ In this example, you'll implement a **\<Web>** component where videos can be pla
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Row() {
Button('onActive').onClick(() => {
console.info("Web Component onActive");
this.controller.onActive();
try {
this.controller.onActive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Button('onInactive').onClick(() => {
console.info("Web Component onInactive");
this.controller.onInactive();
try {
this.controller.onInactive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
}
Web({ src: $rawfile('index.html'), controller: this.controller })
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册