• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 { firstCharacterToUppercase } from '../common/commonUtils';
17
18/**
19 * save all mock function
20 */
21const indexArray: Array<IndexEntity> = [];
22
23export function addToIndexArray(indexEntity: IndexEntity): void {
24  indexArray.push(indexEntity);
25}
26
27export function getIndexArray(): Array<IndexEntity> {
28  return indexArray;
29}
30
31/**
32 * generate index
33 * @returns
34 */
35export function generateIndex(): string {
36  let indexBody = '';
37  let caseBody = '';
38  indexBody += 'import * as etsglobal from \'./@internal/ets/global\';\n';
39  const filterSet: Set<string> = new Set<string>();
40
41  indexArray.forEach(value => {
42    let functionName = value.mockFunctionName;
43    let isHasSameValue = false;
44    if (filterSet.has(value.mockFunctionName)) {
45      isHasSameValue = true;
46      const tmpArr = value.fileName.split('_');
47      let tmpName = tmpArr[0];
48      for (let i = 1; i < tmpArr.length; i++) {
49        tmpName += firstCharacterToUppercase(tmpArr[i]);
50      }
51      functionName = `${tmpName}`;
52    }
53    filterSet.add(functionName);
54    if (isHasSameValue) {
55      indexBody += `import { ${value.mockFunctionName} as ${functionName} } from './${value.fileName}';\n`;
56    } else {
57      indexBody += `import { ${functionName} } from './${value.fileName}';\n`;
58    }
59
60    if (value.fileName.startsWith('ohos_')) {
61      caseBody += `case '${value.fileName.split('ohos_')[1].replace(/_/g, '.')}':\n\treturn ${functionName}();\n`;
62    } else {
63      caseBody += `case '${value.fileName}':\n\treturn ${functionName}();\n`;
64    }
65  });
66
67  indexBody += `export function mockRequireNapiFun() {
68    global.requireNapi = function(...args) {
69      const globalNapi = global.requireNapiPreview(...args);
70      if (globalNapi !== undefined) {
71        return globalNapi;
72      }
73      switch (args[0]) {`;
74  indexBody += caseBody;
75  const endBody = `}
76      if (global.hosMockFunc !== undefined) {
77        return global.hosMockFunc(args[0]);
78      }
79          }
80        }`;
81  indexBody += endBody;
82  return indexBody;
83}
84
85interface IndexEntity {
86  fileName: string,
87  mockFunctionName: string
88}
89