• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024 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 fs from 'fs';
17import path from 'path';
18import {describe, expect, test} from '@jest/globals';
19import { createSourceFile, ScriptTarget } from 'typescript';
20import {
21  checkIsGenericSymbol,
22  generateGenericTypeToMockValue,
23  generateSymbolIterator,
24  getBaseReturnValue,
25  getCallbackStatement,
26  getOverloadedFunctionCallbackStatement,
27  getReturnData,
28  getReturnStatement,
29  getTheRealReferenceFromImport,
30  getWarnConsole,
31  hasExportDefaultKeyword,
32  propertyTypeWhiteList
33} from '../generate/generateCommonUtil';
34
35describe('generateCommonUtil.ts file test', (): void => {
36  test('Test the getWarnConsole function', (): void => {
37    const interfaceNameOrClassName = 'setInterval';
38    const functionNameOrPropertyName = 'setInterval';
39    const result = getWarnConsole(interfaceNameOrClassName, functionNameOrPropertyName);
40    const expectedResult = `console.warn('The setInterval.setInterval interface in the Previewer is a mocked implementation and may behave differently than on a real device.');
41`;
42    expect(result).toBe(expectedResult);
43  });
44
45  test('Test the getReturnStatement function', (): void => {
46    const filePath = path.join(__dirname, './api/global.d.ts');
47    const code = fs.readFileSync(filePath);
48    const sourceFile = createSourceFile(filePath, code.toString(), ScriptTarget.Latest);
49    const returnType = {
50      returnKind: 144,
51      returnKindName: 'number'
52    };
53    const result = getReturnStatement(returnType, sourceFile);
54    expect(result).toBe('return 0;');
55  });
56
57  test('Test the propertyTypeWhiteList function', (): void => {
58    const propertyTypeName = 'formBindingData.FormBindingData';
59    const result = propertyTypeWhiteList(propertyTypeName);
60    expect(result).toBe('formBindingData.FormBindingData');
61  });
62
63  test('Test the getBaseReturnValue function', (): void => {
64    const value = 'rpc.RemoteObject';
65    const result = getBaseReturnValue(value);
66    expect(result).toBe('rpc.RemoteObject');
67  });
68
69  test('Test the getTheRealReferenceFromImport function', (): void => {
70    const filePath = path.join(__dirname, './api/lifecycle.d.ts');
71    const code = fs.readFileSync(filePath);
72    const sourceFile = createSourceFile(filePath, code.toString(), ScriptTarget.Latest);
73    const typeName = 'formBindingData.FormBindingData';
74    const result = getTheRealReferenceFromImport(sourceFile, typeName);
75    expect(result).toBe('mockFormBindingData().FormBindingData');
76  });
77
78  test('Test the checkIsGenericSymbol function', (): void => {
79    const type = 'formBindingData.FormBindingData';
80    const result = checkIsGenericSymbol(type);
81    expect(result).toBe(false);
82  });
83
84  test('Test the generateGenericTypeToMockValue function', (): void => {
85    const kindName = 'Array<AccessibilityAbilityInfo>';
86    const result = generateGenericTypeToMockValue(kindName);
87    expect(result).toBe('');
88  });
89
90  test('Test the getCallbackStatement function', (): void => {
91    const mockApi = 'import { mockWant } from \'../../ohos_app_ability_Want\''
92      + 'import { ResultSet } from \'../../data/rdb/resultSet\''
93      + 'import { AbilityInfo } from \'../../bundle/abilityInfo\''
94      + 'import { DataAbilityResult } from \'../../ability/dataAbilityResult\''
95      + 'import { DataAbilityOperation } from \'../../ability/dataAbilityOperation\''
96      + 'import { mockDataAbility } from \'../../ohos_data_dataAbility\''
97      + 'import { mockFormBindingData } from \'../../ohos_application_formBindingData\''
98      + 'import { mockFormInfo } from \'../../ohos_app_form_formInfo\''
99      + 'import { mockRdb } from \'../../ohos_data_rdb\''
100      + 'import { mockRpc } from \'../../ohos_rpc\''
101      + 'import { mockResourceManager } from \'../../ohos_resourceManager\''
102      + 'import { PacMap } from \'../../ability/dataAbilityHelper\''
103      + 'import { AsyncCallback } from \'../../ohos_base\'';
104    const paramTypeString = 'AsyncCallback<number>';
105    const result = getCallbackStatement(mockApi, paramTypeString);
106    const expectedResult = `if (args && typeof args[args.length - 1] === 'function') {
107    args[args.length - 1].call(this, {'code': '','data': '','name': '','message': '','stack': ''}, 0);
108}`;
109    expect(result).toBe(expectedResult);
110  });
111
112  test('Test the getOverloadedFunctionCallbackStatement function', (): void => {
113    const filePath = path.join(__dirname, './api/@ohos.account.appAccount.d.ts');
114    const code = fs.readFileSync(filePath);
115    const sourceFile = createSourceFile(filePath, code.toString(), ScriptTarget.Latest);
116    const mockApi = 'import { AsyncCallback, Callback } from \'./ohos_base\''
117      + 'import { mockWant } from \'./ohos_app_ability_Want\''
118      + 'import { mockRpc } from \'./ohos_rpc\'';
119    const entityArray = [
120      {
121        returnType: {
122          returnKind: 113,
123          returnKindName: 'void'
124        },
125        args: [
126          {
127            paramName: 'type',
128            paramTypeKind: 191,
129            paramTypeString: '\'change\''
130          },
131          {
132            paramName: 'owners',
133            paramTypeKind: 173,
134            paramTypeString: 'Array<string>'
135          },
136          {
137            paramName: 'callback',
138            paramTypeKind: 173,
139            paramTypeString: 'Callback<Array<AppAccountInfo>>'
140          }
141        ],
142        functionName: 'on'
143      },
144      {
145        functionName: 'on',
146        args: [
147          {
148            paramName: 'type',
149            paramTypeKind: 191,
150            paramTypeString: '\'accountChange\''
151          },
152          {
153            paramName: 'callback',
154            paramTypeKind: 173,
155            paramTypeString: 'Callback<Array<AppAccountInfo>>'
156          },
157          {
158            paramName: 'owners',
159            paramTypeKind: 173,
160            paramTypeString: 'Array<string>'
161          }
162        ],
163        returnType: {
164          returnKind: 113,
165          returnKindName: 'void'
166        }
167      }
168    ];
169    const result = getOverloadedFunctionCallbackStatement(entityArray, sourceFile, mockApi);
170    const expectedResult = `if (args && ['change'].includes(args[0])) {
171if (args && typeof args[args.length - 1] === 'function') {
172    args[args.length - 1].call(this, []);
173}
174}if (args && ['accountChange'].includes(args[0])) {
175if (args && typeof args[args.length - 1] === 'function') {
176    args[args.length - 1].call(this, []);
177}
178}
179`;
180    expect(result).toBe(expectedResult);
181  });
182
183  test('Test the generateSymbolIterator function', (): void => {
184    const methodEntity = {
185      args: [],
186      functionName: {
187        name: 'Symbol.iterator',
188        kind: 158,
189        expressionKind: 201
190      },
191      modifiers: [],
192      returnType: {
193        returnKindName: 'IterableIterator<[string, string]>',
194        returnKind: 173
195      }
196    };
197    const result = generateSymbolIterator(methodEntity);
198    const expectedResult = `let index = 0;
199    const IteratorMock = {
200      next: () => {
201        if (index < 1) {
202          const returnValue = ['[PC Previwe] unknown iterableiterator_k', '[PC Previwe] unknown iterableiterator_v'];
203          index++;
204          return {
205            value: returnValue,
206            done: false
207          };
208        } else {
209          return {
210            done: true
211          };
212        }
213      }
214    };
215    return IteratorMock;`;
216    expect(result).toBe(expectedResult);
217  });
218
219  test('Test the getReturnData function', (): void => {
220    const filePath = path.join(__dirname, './api/@ohos.account.appAccount.d.ts');
221    const code = fs.readFileSync(filePath);
222    const sourceFile = createSourceFile(filePath, code.toString(), ScriptTarget.Latest);
223    const returnType = {
224      returnKind: 113,
225      returnKindName: 'void'
226    };
227    const mockApi = 'import { AsyncCallback, Callback } from \'./ohos_base\''
228      + 'import { mockWant } from \'./ohos_app_ability_Want\''
229      + 'import { mockRpc } from \'./ohos_rpc\'';
230    const result = getReturnData(true, false, returnType, sourceFile, mockApi);
231    expect(result).toBe(`return '[PC Preview] unknown type'`);
232  });
233
234  test('Test the hasExportDefaultKeyword function', (): void => {
235    const filePath = path.join(__dirname, './api/@ohos.ability.errorCode.d.ts');
236    const code = fs.readFileSync(filePath);
237    const sourceFile = createSourceFile(filePath, code.toString(), ScriptTarget.Latest);
238    const mockName = 'errorCode';
239    const result = hasExportDefaultKeyword(mockName, sourceFile);
240    expect(result).toBe(true);
241  });
242});
243