1/*
2 * Copyright (c) 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/src/main/ets/default/utils/Log';
19
20let abilityDelegator = undefined;
21let abilityDelegatorArguments = undefined;
22
23function translateParamsToString(parameters): string {
24  const keySet = new Set([
25    '-s class', '-s notClass', '-s suite', '-s it',
26    '-s level', '-s testType', '-s size', '-s timeout'
27  ]);
28  let targetParams = '';
29  for (const key in parameters) {
30    if (keySet.has(key)) {
31      targetParams = `${targetParams} ${key} ${parameters[key]}`;
32    }
33  }
34  return targetParams.trim();
35}
36
37async function onAbilityCreateCallback() {
38  Log.log('onAbilityCreateCallback');
39}
40
41async function addAbilityMonitorCallback(err: any) {
42  Log.info('addAbilityMonitorCallback : ' + JSON.stringify(err));
43}
44
45export default class OpenHarmonyTestRunner implements TestRunner {
46  constructor() {
47  }
48
49  onPrepare(): void {
50    Log.info('OpenHarmonyTestRunner OnPrepare ');
51  }
52
53  async onRun() {
54    Log.log('OpenHarmonyTestRunner onRun run');
55    abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments();
56    abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
57    let testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility';
58    let lMonitor = {
59      abilityName: testAbilityName,
60      onAbilityCreate: onAbilityCreateCallback,
61    };
62    abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback);
63    let cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName;
64    cmd += ' ' + translateParamsToString(abilityDelegatorArguments.parameters);
65    Log.info('cmd : ' + cmd);
66    abilityDelegator.executeShellCommand(cmd,
67      (err: any, d: any) => {
68        Log.info('executeShellCommand : err : ' + JSON.stringify(err));
69        Log.info('executeShellCommand : data : ' + d.stdResult);
70        Log.info('executeShellCommand : data : ' + d.exitCode);
71      });
72    Log.info('OpenHarmonyTestRunner onRun end');
73  }
74};