1/*
2 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import type TestRunner from '@ohos.application.testRunner';
17import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
18import { Log } from '@ohos/common';
19
20const TAG: string = 'OpenHarmonyTestRunner';
21
22var abilityDelegator = undefined;
23var abilityDelegatorArguments = undefined;
24
25function translateParamsToString(parameters): string {
26  const keySet = new Set([
27    '-s class', '-s notClass', '-s suite', '-s it',
28    '-s level', '-s testType', '-s size', '-s timeout'
29  ]);
30  let targetParams: string = '';
31  for (const key in parameters) {
32    if (keySet.has(key)) {
33      targetParams = `${targetParams} ${key} ${parameters[key]}`;
34    }
35  }
36  return targetParams.trim();
37}
38
39async function onAbilityCreateCallback(): Promise<void> {
40  Log.info(TAG, 'onAbilityCreateCallback');
41}
42
43async function addAbilityMonitorCallback(err: any): Promise<void> {
44  Log.info(TAG, 'addAbilityMonitorCallback : ' + JSON.stringify(err));
45}
46
47export default class OpenHarmonyTestRunner implements TestRunner {
48  constructor() {
49  }
50
51  onPrepare(): void {
52    Log.info(TAG, 'OpenHarmonyTestRunner OnPrepare ');
53  }
54
55  async onRun(): Promise<void> {
56    Log.info(TAG, 'OpenHarmonyTestRunner onRun run');
57    abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments();
58    abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
59    let testAbilityName: string = abilityDelegatorArguments.bundleName + '.TestAbility';
60    let lMonitor = {
61      abilityName: testAbilityName,
62      onAbilityCreate: onAbilityCreateCallback,
63    };
64    abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback);
65    let cmd: string = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName;
66    cmd += ' ' + translateParamsToString(abilityDelegatorArguments.parameters);
67    Log.info(TAG, 'cmd : ' + cmd);
68    abilityDelegator.executeShellCommand(cmd,
69      (err, data) => {
70        Log.info(TAG, 'executeShellCommand : err : ' + JSON.stringify(err));
71        Log.info(TAG, 'executeShellCommand : data : ' + data.stdResult);
72        Log.info(TAG, 'executeShellCommand : data : ' + data.exitCode);
73      })
74    Log.info(TAG, 'OpenHarmonyTestRunner onRun end');
75  }
76};