diff --git a/ets2panda/driver/build_system/test/ut/base_modeTest/base_mode.test.ts b/ets2panda/driver/build_system/test/ut/base_modeTest/base_mode.test.ts index 96440a8124c1466d3c0bdfb1e49845a2c05923bf..a8344603bd899377ca7c89a413cdd203ae7bda3b 100755 --- a/ets2panda/driver/build_system/test/ut/base_modeTest/base_mode.test.ts +++ b/ets2panda/driver/build_system/test/ut/base_modeTest/base_mode.test.ts @@ -13,6 +13,9 @@ * limitations under the License. */ +import fs from 'fs'; +import path from 'path'; + import { BaseMode } from '../../../src/build/base_mode'; import { BuildConfig, BUILD_TYPE, BUILD_MODE, OHOS_MODULE_TYPE, ModuleInfo, ES2PANDA_MODE } from '../../../src/types'; import { BuildMode } from '../../../src/build/build_mode'; @@ -67,6 +70,10 @@ beforeEach(() => { beforeAll(() => { const { execSync } = require('child_process'); execSync('rimraf test/ut/mock/dist', { stdio: 'pipe' }); + const dir = path.resolve('dist/cache'); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } }); // Test the functions of the base_mode.ts file. @@ -82,15 +89,7 @@ describe('test base_mode.ts file api', () => { test('test shouldSkipFile', () => { test_shouldSkipFile(); }); - - test('test setupCluster', () => { - test_setupCluster(); - }); - - test('test terminateAllWorkers', () => { - test_terminateAllWorkers(); - }); - + test('test collectCompileFiles when test declaration files skip branch', () => { test_collectCompileFiles_decl_ets_skip(); }); @@ -175,10 +174,6 @@ describe('test base_mode.ts file api', () => { test_getJobDependencies(); }); - test('test setupWorkerMessageHandler', () => { - test_setupWorkerMessageHandler(); - }); - test('test getSerializableConfig handles bigint values', () => { test_getSerializableConfig(); }); @@ -228,6 +223,7 @@ function test_collectCompileJobs_should_skip_entry_files_not_in_compileFiles() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -306,7 +302,7 @@ function test_collectDependentCompileFiles_isFileChanged_branch() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", - dependentModuleList: [] + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -327,7 +323,7 @@ function test_collectDependentCompileFiles_isFileChanged_branch() { jest.spyOn(fs, 'statSync').mockReturnValue({ mtimeMs: Date.now() }); jest.spyOn(fs, 'readFileSync').mockReturnValue('mocked file content'); - const utils = require('../../../src/utils'); + const utils = require('../../../src/util/utils'); jest.spyOn(utils, 'getFileHash').mockReturnValue("test-hash-123"); const Logger = require('../../../src/logger').Logger; @@ -407,7 +403,7 @@ function test_collectAbcFileFromByteCodeHar_missing_abc_path() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", - dependentModuleList: [] + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -475,7 +471,7 @@ function test_collectCompileFiles_enableDeclgenEts2Ts_false() { loaderOutPath: "./dist", cachePath: "./dist/cache", enableDeclgenEts2Ts: false, - dependentModuleList: [] + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -519,6 +515,8 @@ class TestBaseModeMock extends BaseMode { compileFileInfos: [], dynamicDepModuleInfos: new Map(), staticDepModuleInfos: new Map(), + dependenciesSet: new Set(), + dependentSet: new Set(), moduleType: OHOS_MODULE_TYPE.HAR, entryFile: "index.ets", byteCodeHar: false, @@ -542,7 +540,7 @@ function test_collectModuleInfos1(mockLogger: any, LogDataFactory: any) { loaderOutPath: "./dist", cachePath: "./dist/cache", hasMainModule: true, - dependentModuleList: [] + dependentModuleList: [], }; const baseMode = new TestBaseModeMock(mockConfig as any); (baseMode as any).logger = mockLogger; @@ -773,6 +771,7 @@ function test_updateDependantJobs() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; (global as any).finishedJob = []; @@ -797,6 +796,7 @@ function test_loadHashCache() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -861,6 +861,7 @@ function test_isFileChanged() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -918,6 +919,7 @@ function test_collectDependentCompileFiles() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -982,6 +984,7 @@ function test_getSerializableConfig() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG, arkts: { someFunction: () => { } @@ -1012,86 +1015,6 @@ function test_getSerializableConfig() { expect(result).toHaveProperty('sourceRoots'); } -function test_setupWorkerMessageHandler() { - const mockConfig = { - packageName: "test", - moduleRootPath: "/test/path", - sourceRoots: ["./"], - loaderOutPath: "./dist", - cachePath: "./dist/cache", - buildMode: BUILD_MODE.DEBUG - }; - - const mockLogData = { code: "123", message: "Test message" }; - const mockLogger = { - printError: jest.fn(), - printInfo: jest.fn() - }; - - const LogDataFactory = { - newInstance: jest.fn().mockReturnValue(mockLogData) - }; - - const ErrorCode = { - BUILDSYSTEM_COMPILE_ABC_FAIL: '11410099' - }; - - class TestBuildMode extends BaseMode { - public run(): Promise { - return Promise.resolve(); - } - - public testSetupWorkerMessageHandler(worker: any): void { - (this as any).setupWorkerMessageHandler(worker); - } - } - - const baseMode = new TestBuildMode(mockConfig as any); - (baseMode as any).logger = mockLogger; - const errorLogDataSpy = jest.spyOn(LogDataFactory, 'newInstance'); - - const mockWorker = { - on: jest.fn(), - callbacks: {} as Record - }; - - mockWorker.on = jest.fn().mockImplementation((event, callback) => { - mockWorker.callbacks[event] = callback; - return mockWorker; - }); - - (global as any).LogDataFactory = LogDataFactory; - (global as any).ErrorCode = ErrorCode; - - baseMode.testSetupWorkerMessageHandler(mockWorker); - - expect(mockWorker.on).toHaveBeenCalledWith('message', expect.any(Function)); - - if (mockWorker.callbacks['message']) { - mockWorker.callbacks['message']({ success: true }); - } - expect(mockLogger.printError).not.toHaveBeenCalled(); - - if (mockWorker.callbacks['message']) { - mockWorker.callbacks['message']({ - success: false, - filePath: '/test/file.ets', - error: 'Test error' - }); - } - mockLogger.printError.mockClear(); - errorLogDataSpy.mockClear(); - - if (mockWorker.callbacks['message']) { - mockWorker.callbacks['message']({ - success: false, - filePath: '/test/file2.ets' - }); - } - - jest.restoreAllMocks(); -} - function test_getJobDependencies() { const mockConfig = { packageName: "test", @@ -1099,6 +1022,7 @@ function test_getJobDependencies() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -1151,6 +1075,7 @@ function test_getJobDependants() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; class TestBuildMode extends BuildMode { @@ -1202,6 +1127,7 @@ function test_collectCompileJobs() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -1303,6 +1229,7 @@ function test_dealWithDependants() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; class TestBuildMode extends BuildMode { @@ -1362,6 +1289,7 @@ function test_addJobToQueues() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -1447,6 +1375,7 @@ function test_initCompileQueues() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -1530,6 +1459,7 @@ function test_checkAllTasksDone() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; @@ -1569,6 +1499,7 @@ function test_processAfterCompile() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG, arkts: { destroyConfig: jest.fn() @@ -1612,9 +1543,13 @@ function test_processAfterCompile() { function test_runConcurrent() { const mockConfig = { - packageName: "test", compileFiles: ["/test/path/file1.ets"], - moduleRootPath: "/test/path", sourceRoots: ["./"], - loaderOutPath: "./dist", cachePath: "./dist/cache", + packageName: "test", + compileFiles: ["/test/path/file1.ets"], + moduleRootPath: "/test/path", + sourceRoots: ["./"], + loaderOutPath: "./dist", + cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG } as any; @@ -1678,8 +1613,13 @@ function test_collectDependencyModules_language_branches() { } const baseMode = new TestBaseMode({ - packageName: "test", moduleRootPath: "/test/path", sourceRoots: ["./"], - loaderOutPath: "./dist", cachePath: "./dist/cache", buildMode: BUILD_MODE.DEBUG + packageName: "test", + moduleRootPath: "/test/path", + sourceRoots: ["./"], + loaderOutPath: "./dist", + cachePath: "./dist/cache", + dependentModuleList: [], + buildMode: BUILD_MODE.DEBUG } as any); { @@ -1739,6 +1679,7 @@ function test_getDependentModules_missing_module() { sourceRoots: ["./"], loaderOutPath: "./dist", cachePath: "./dist/cache", + dependentModuleList: [], buildMode: BUILD_MODE.DEBUG }; const Logger = require('../../../src/logger').Logger; @@ -1774,11 +1715,17 @@ function test_declgen_method() { const fs = require('fs'); jest.spyOn(fs, 'readFileSync').mockReturnValue('test source code'); const mockConfig = { - packageName: "test", moduleRootPath: "/test/path", - loaderOutPath: "./dist", cachePath: "./dist/cache", + packageName: "test", + moduleRootPath: "/test/path", + loaderOutPath: "./dist", + cachePath: "./dist/cache", + dependentModuleList: [], arkts: { Config: { create: jest.fn().mockReturnValue({ peer: 'mockConfigPeer' }) }, - Context: { createFromString: jest.fn().mockReturnValue({ peer: 'mockContextPeer', program: 'mockProgram' }) }, + Context: { + createFromString: jest.fn().mockReturnValue({ peer: 'mockContextPeer', program: 'mockProgram' }), + createFromStringWithHistory: jest.fn().mockReturnValue({ peer: 'mockContextPeer', program: 'mockProgram' }) + }, proceedToState: jest.fn(), EtsScript: { fromContext: jest.fn().mockReturnValue('mockAst') }, Es2pandaContextState: { ES2PANDA_STATE_PARSED: 'parsed', ES2PANDA_STATE_CHECKED: 'checked' }, generateTsDeclarationsFromContext: jest.fn(), destroyConfig: jest.fn() @@ -1787,7 +1734,7 @@ function test_declgen_method() { }; const Logger = require('../../../src/logger').Logger; const PluginDriver = require('../../../src/plugins/plugins_driver').PluginDriver; - const utils = require('../../../src/utils'); + const utils = require('../../../src/util/utils'); const path = require('path'); Logger.getInstance = jest.fn().mockReturnValue({ printInfo: jest.fn(), printError: jest.fn() }); PluginDriver.getInstance = jest.fn().mockReturnValue({ @@ -1813,7 +1760,7 @@ function test_declgen_method() { }]]); baseMode.testDeclgen({ filePath: '/test/path/file1.ets', packageName: 'test', arktsConfigFile: '/test/path/arktsconfig.json' }); expect(fs.readFileSync).toHaveBeenCalledWith('/test/path/file1.ets', 'utf8'); - expect(mockConfig.arkts.Context.createFromString).toHaveBeenCalled(); + expect(mockConfig.arkts.Context.createFromStringWithHistory).toHaveBeenCalled(); expect(mockConfig.arkts.proceedToState).toHaveBeenCalledWith('parsed', 'mockContextPeer', true); expect(mockConfig.arkts.proceedToState).toHaveBeenCalledWith('checked', 'mockContextPeer', true); expect(mockConfig.arkts.generateTsDeclarationsFromContext).toHaveBeenCalled(); @@ -1980,7 +1927,8 @@ function test_assignTaskToIdleWorker_empty_queues() { moduleRootPath: "/test/path", sourceRoots: ["./"], loaderOutPath: "./dist", - cachePath: "./dist/cache" + cachePath: "./dist/cache", + dependentModuleList: [], }; const Logger = require('../../../src/logger').Logger; @@ -2065,7 +2013,8 @@ function test_assignTaskToIdleWorker_abcQueue_no_job() { moduleRootPath: "/test/path", sourceRoots: ["./"], loaderOutPath: "./dist", - cachePath: "./dist/cache" + cachePath: "./dist/cache", + dependentModuleList: [], }; const Logger = require('../../../src/logger').Logger; @@ -2153,8 +2102,13 @@ function test_assignTaskToIdleWorker_abcQueue_no_job() { function test_findStronglyConnectedComponents_branches() { const mockConfig = { - packageName: "test", moduleRootPath: "/test/path", sourceRoots: ["./"], - loaderOutPath: "./dist", cachePath: "./dist/cache", buildMode: "Debug" + packageName: "test", + moduleRootPath: "/test/path", + sourceRoots: ["./"], + loaderOutPath: "./dist", + cachePath: "./dist/cache", + buildMode: "Debug", + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -2206,7 +2160,8 @@ function test_createExternalProgramJob_branches() { loaderOutPath: "./dist", cachePath: "./dist/cache", buildMode: "Debug", - moduleType: "har" + moduleType: "har", + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -2297,7 +2252,7 @@ function test_collectCompileFiles_bytecode_har() { loaderOutPath: "./dist", cachePath: "./dist/cache", enableDeclgenEts2Ts: true, - dependentModuleList: [] + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -2340,7 +2295,7 @@ function test_collectCompileFiles_bytecode_har() { }); (global as any).getFileHash = jest.fn().mockReturnValue("hash123"); - const utils = require('../../../src/utils'); + const utils = require('../../../src/util/utils'); jest.spyOn(baseMode, 'testCollectAbcFileFromByteCodeHar').mockImplementation(() => { }); @@ -2362,7 +2317,7 @@ function test_collectCompileFiles_file_not_in_module() { loaderOutPath: "./dist", cachePath: "./dist/cache", enableDeclgenEts2Ts: true, - dependentModuleList: [] + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -2427,7 +2382,7 @@ function test_collectCompileFiles_decl_ets_skip() { loaderOutPath: "./dist", cachePath: "./dist/cache", enableDeclgenEts2Ts: true, - dependentModuleList: [] + dependentModuleList: [], }; class TestBaseMode extends BaseMode { @@ -2465,7 +2420,7 @@ function test_collectCompileFiles_decl_ets_skip() { }); (global as any).getFileHash = jest.fn().mockReturnValue("hash123"); - const utils = require('../../../src/utils'); + const utils = require('../../../src/util/utils'); baseMode.testCollectCompileFiles(); } @@ -2498,7 +2453,7 @@ function test_collectModuleInfos() { dependentModuleList: [ { - "packageName": "", + "packageName": "harA", "moduleName": "harA", "moduleType": "har", "modulePath": "test/ut/mock/demo_1.2_dep_hsp1.2/harA", @@ -2509,7 +2464,7 @@ function test_collectModuleInfos() { "byteCodeHar": false }, { - "packageName": "", + "packageName": "hspA", "moduleName": "hspA", "moduleType": "shared", "modulePath": "hspA", @@ -2657,6 +2612,8 @@ function test_shouldSkipFile() { declgenBridgeCodePath: "/dist/bridge", dynamicDepModuleInfos: new Map(), staticDepModuleInfos: new Map(), + dependenciesSet: new Set(), + dependentSet: new Set(), moduleType: OHOS_MODULE_TYPE.HAR, entryFile: "index.ets", declgenV2OutPath: "/dist/declgen/v2", @@ -2673,114 +2630,3 @@ function test_shouldSkipFile() { expect(result4).toBe(false); } -function test_setupCluster() { - const mockConfig: BuildConfig = { - buildMode: BUILD_MODE.DEBUG, - compileFiles: ["test.ets"], - packageName: "test", - moduleRootPath: "/test/path", - sourceRoots: ["./"], - loaderOutPath: "./dist", - cachePath: "./dist/cache", - plugins: {}, - dependentModuleList: [], - maxWorkers: 1, - buildType: BUILD_TYPE.BUILD, - hasMainModule: true, - arkts: {} as any, - arktsGlobal: {} as any, - enableDeclgenEts2Ts: false, - moduleType: OHOS_MODULE_TYPE.HAR, - declgenV1OutPath: "./dist/declgen", - declgenV2OutPath: "./dist/declgen/v2", - buildSdkPath: "./sdk", - byteCodeHar: false, - externalApiPaths: [] - } as any; - const Logger = require('../../../src/logger').Logger; - Logger.instance = null; - Logger.getInstance(mockConfig); - let baseModule: BaseMode = new BuildMode(mockConfig); - - const originalRemoveAllListeners = cluster.removeAllListeners; - const originalSetupPrimary = cluster.setupPrimary; - - const removeAllListenersSpy = jest.fn(); - cluster.removeAllListeners = removeAllListenersSpy; - - const setupPrimarySpy = jest.fn(); - cluster.setupPrimary = setupPrimarySpy; - - try { - (baseModule as any).setupCluster(cluster, { - clearExitListeners: false, - execPath: '/path/to/worker', - execArgs: [] - }); - - expect(removeAllListenersSpy).not.toHaveBeenCalled(); - expect(setupPrimarySpy).toHaveBeenCalledWith({ - exec: '/path/to/worker', - execArgv: [] - }); - } finally { - cluster.removeAllListeners = originalRemoveAllListeners; - cluster.setupPrimary = originalSetupPrimary; - } -} - -function test_terminateAllWorkers() { - const mockConfig: BuildConfig = { - buildMode: BUILD_MODE.DEBUG, - compileFiles: ["test.ets"], - packageName: "test", - moduleRootPath: "/test/path", - sourceRoots: ["./"], - loaderOutPath: "./dist", - cachePath: "./dist/cache", - plugins: {}, - dependentModuleList: [], - buildType: BUILD_TYPE.BUILD, - hasMainModule: true, - arkts: {} as any, - arktsGlobal: {} as any, - enableDeclgenEts2Ts: false, - moduleType: OHOS_MODULE_TYPE.HAR, - declgenV1OutPath: "./dist/declgen", - declgenV2OutPath: "./dist/declgen/v2", - buildSdkPath: "./sdk", - byteCodeHar: false, - externalApiPaths: [] - } as any; - const Logger = require('../../../src/logger').Logger; - Logger.instance = null; - Logger.getInstance(mockConfig); - let baseModule: BaseMode = new BuildMode(mockConfig); - - const originalWorkers = cluster.workers; - - try { - Object.defineProperty(cluster, 'workers', { - value: {}, - configurable: true - }); - - expect(() => { - (baseModule as any).terminateAllWorkers(); - }).not.toThrow(); - - Object.defineProperty(cluster, 'workers', { - value: undefined, - configurable: true - }); - - expect(() => { - (baseModule as any).terminateAllWorkers(); - }).not.toThrow(); - } finally { - Object.defineProperty(cluster, 'workers', { - value: originalWorkers, - configurable: true - }); - } -} diff --git a/ets2panda/driver/build_system/test/ut/build_framework_modeTest/build_framework_mode.test.ts b/ets2panda/driver/build_system/test/ut/build_framework_modeTest/build_framework_mode.test.ts index d5f1c84eb00399d8ec86c185ea8edcf26e85768e..2a902b0e6c56d9eccd3e27b7065e373487f47ee8 100755 --- a/ets2panda/driver/build_system/test/ut/build_framework_modeTest/build_framework_mode.test.ts +++ b/ets2panda/driver/build_system/test/ut/build_framework_modeTest/build_framework_mode.test.ts @@ -161,6 +161,8 @@ describe('test build_framework_mode.ts file api', () => { compileFileInfos: [], dynamicDepModuleInfos: new Map(), staticDepModuleInfos: new Map(), + dependenciesSet: new Set(), + dependentSet: new Set(), moduleType: OHOS_MODULE_TYPE.HAR, entryFile: 'index.ets', byteCodeHar: false, diff --git a/ets2panda/driver/build_system/test/ut/compile_WorkerTest/compile_worker.test.ts b/ets2panda/driver/build_system/test/ut/compile_WorkerTest/compile_worker.test.ts index da01ed9b341899e20ef22cbb3eb2c0524ade9019..56f1ae662668525507e77a1559276eb96fb2d0d3 100755 --- a/ets2panda/driver/build_system/test/ut/compile_WorkerTest/compile_worker.test.ts +++ b/ets2panda/driver/build_system/test/ut/compile_WorkerTest/compile_worker.test.ts @@ -17,7 +17,7 @@ jest.mock('fs'); jest.mock('path'); -jest.mock('../../../src/utils', () => ({ +jest.mock('../../../src/util/utils', () => ({ changeFileExtension: jest.fn((p, ext) => p.replace(/\.[^/.]+$/, ext)), ensurePathExists: jest.fn() })); @@ -52,15 +52,43 @@ jest.mock('/sdk/koala', () => ({ const fakeArkts = { Config: { create: jest.fn(() => ({ peer: 'peer' })) }, - Context: { createFromString: jest.fn(() => ({ program: {}, peer: 'peer' })) }, + Context: { + createFromString: jest.fn(() => ({ program: {}, peer: 'peer' })), + createFromStringWithHistory: jest.fn(() => ({ program: {}, peer: 'peer' })) + }, proceedToState: jest.fn(), - Es2pandaContextState: { ES2PANDA_STATE_PARSED: 1, ES2PANDA_STATE_CHECKED: 2, ES2PANDA_STATE_BIN_GENERATED: 3 }, + Es2pandaContextState: { ES2PANDA_STATE_PARSED: 1, ES2PANDA_STATE_CHECKED: 2 }, + generateTsDeclarationsFromContext: jest.fn(), generateStaticDeclarationsFromContext: jest.fn(), - destroyConfig: jest.fn() + destroyConfig: jest.fn(), + EtsScript: { fromContext: jest.fn(() => ({})) } }; const fakeArktsGlobal = { - es2panda: { _DestroyContext: jest.fn() } + es2panda: { + _SetUpSoPath: jest.fn(), + _DestroyContext: jest.fn((pandaSDKPath: string) => { + return; + }), + }, + filePath: '', + config: '', + compilerContext: { program: {}, peer: 'peer' } }; + +jest.mock('../../../src/init/init_koala_modules', () => ({ + initKoalaModules: jest.fn((buildConfig) => { + const fakeKoala = { + arkts: fakeArkts, + arktsGlobal: fakeArktsGlobal + }; + fakeKoala.arktsGlobal.es2panda._SetUpSoPath(buildConfig.pandaSdkPath); + + buildConfig.arkts = fakeKoala.arkts; + buildConfig.arktsGlobal = fakeKoala.arktsGlobal; + return fakeKoala; + }) +})); + jest.mock('path', () => ({ ...jest.requireActual('path'), resolve: jest.fn((...args) => args.join('/')), @@ -83,96 +111,104 @@ afterEach(() => { }); // Test the functions of the compile_worker.ts file -import { changeFileExtension } from '../../../src/utils'; +import { changeFileExtension } from '../../../src/util/utils'; import { DECL_ETS_SUFFIX } from '../../../src/pre_define'; +import { + CompileFileInfo, + BuildConfig, + ES2PANDA_MODE, + BUILD_MODE, + BUILD_TYPE, +} from '../../../src/types'; describe('compile_worker', () => { - const fileInfo = { + + const compileFileInfo: CompileFileInfo ={ filePath: '/src/foo.ets', - abcFilePath: '/out/foo.abc', - arktsConfigFile: '/src/arktsconfig.json' + dependentFiles: [], + abcFilePath: 'foo.abc', + arktsConfigFile: '/src/arktsconfig.json', + packageName: 'pkg', }; + const buildConfig = { - buildMode: 0, hasMainModule: true, byteCodeHar: true, - moduleType: 0, - declgenV2OutPath: '/decl', - packageName: 'pkg', + moduleType: 9999, + declgenV2OutPath: 'declgenV2Out', moduleRootPath: '/src', - buildSdkPath: '/sdk' + plugins: { pkg: 'plugin' }, + paths: { pkg: ['plugin'] }, + compileFiles: ['/src/foo.ets'], + entryFiles: ['/src/foo.ets'], + dependentModuleList: [], + aliasConfig: {}, }; - const moduleInfos: any[] = []; + + beforeEach(() => { + jest.resetModules(); + (process as any).send = jest.fn(); + jest.spyOn(process, 'exit').mockImplementation((code?: string | number | null | undefined) => { + throw new Error(`exit: ${code}`); + }); + }); + test('compile all files && exit(0)', () => { require('fs').readFileSync.mockReturnValue(Buffer.from('source code')); require('path').relative.mockImplementation((from: string, to: string) => to.replace(from, '').replace(/^\//, '')); require('path').join.mockImplementation((...args: string[]) => args.join('/')); require('path').resolve.mockImplementation((...args: string[]) => args.join('/')); require('path').basename.mockImplementation((p: string) => p.split('/').pop()); + const processId: number = 1; + const payload = { + fileInfo: compileFileInfo, + buildConfig: buildConfig, + }; require('../../../src/build/compile_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig, moduleInfos }); - }).toThrow('exit'); - expect(require('../../../src/utils').ensurePathExists).toHaveBeenCalled(); - expect(require('fs').readFileSync).toHaveBeenCalledWith(fileInfo.filePath); + (process as any).emit('message', { processId, payload }); + + expect(require('../../../src/util/utils').ensurePathExists).toHaveBeenCalled(); + expect(require('fs').readFileSync).toHaveBeenCalledWith(compileFileInfo.filePath); expect(fakeArkts.Config.create).toHaveBeenCalled(); expect(fakeArkts.Context.createFromString).toHaveBeenCalled(); expect(fakeArkts.proceedToState).toHaveBeenCalledTimes(3); expect(fakeArkts.generateStaticDeclarationsFromContext).toHaveBeenCalled(); expect(fakeArkts.destroyConfig).toHaveBeenCalled(); expect(fakeArktsGlobal.es2panda._DestroyContext).toHaveBeenCalled(); - expect(process.exit).toHaveBeenCalledWith(0); }); - - test('handle error && send fail message', () => { - jest.spyOn(process, 'exit').mockImplementation(() => undefined as never); - - require('fs').readFileSync.mockImplementation(() => { throw new Error('fail'); }); - require('../../../src/build/compile_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig, moduleInfos }); - }).not.toThrow(); - - expect(process.send).toHaveBeenCalledWith(expect.objectContaining({ - success: false, - filePath: fileInfo.filePath, - error: expect.any(String) - })); - }); - + test('generate decl file', () => { require('fs').readFileSync.mockReturnValue(Buffer.from('source code')); - let config = { ...buildConfig, hasMainModule: false }; + let config = buildConfig; + config.hasMainModule = false; + let processId: number = 3; + let payload = { + fileInfo: compileFileInfo, + buildConfig: config, + }; require('../../../src/build/compile_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig: config, moduleInfos }); - }).toThrow('exit'); + (process as any).emit('message', { processId, payload }); expect(fakeArkts.generateStaticDeclarationsFromContext).not.toHaveBeenCalled(); + require('fs').readFileSync.mockReturnValue(Buffer.from('source code')); - config = { ...buildConfig, byteCodeHar: false, moduleType: 9999 }; + config.hasMainModule = true; + config.byteCodeHar = false; + config.moduleType = 999999; require('../../../src/build/compile_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig: config, moduleInfos }); - }).toThrow('exit'); + processId = 4; + (process as any).emit('message', { processId, payload }); expect(fakeArkts.generateStaticDeclarationsFromContext).not.toHaveBeenCalled(); + require('path').relative.mockImplementation((from: string, to: string) => to.replace(from, '').replace(/^\//, '')); require('fs').readFileSync.mockReturnValue(Buffer.from('source code')); - config = { ...buildConfig, hasMainModule: true, byteCodeHar: true }; + config.byteCodeHar = true; require('../../../src/build/compile_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig: config, moduleInfos }); - }).toThrow('exit'); - let filePathFromModuleRoot = require('path').relative(buildConfig.moduleRootPath, fileInfo.filePath); + processId = 5; + (process as any).emit('message', { processId, payload }); + let filePathFromModuleRoot = require('path').relative(buildConfig.moduleRootPath, compileFileInfo.filePath); let declarationPath = require('path').join(buildConfig.declgenV2OutPath, filePathFromModuleRoot); let declarationFilePath = changeFileExtension(declarationPath, DECL_ETS_SUFFIX); expect(fakeArkts.generateStaticDeclarationsFromContext).toHaveBeenCalledWith(declarationFilePath); }); - test('throw while process.send is undefined', () => { - delete (process as any).send; - require('../../../src/build/compile_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig, moduleInfos }); - }).toThrow('process.send is undefined. This worker must be run as a forked process.'); - }); }); diff --git a/ets2panda/driver/build_system/test/ut/compile_thread_workerTest/compile_thread_worker.test.ts b/ets2panda/driver/build_system/test/ut/compile_thread_workerTest/compile_thread_worker.test.ts index 7b2783a1cbfa9a5513dcf28c169a053e69b44fb1..87d39b2da4288a32896ecfc5be613ca32bf007fb 100755 --- a/ets2panda/driver/build_system/test/ut/compile_thread_workerTest/compile_thread_worker.test.ts +++ b/ets2panda/driver/build_system/test/ut/compile_thread_workerTest/compile_thread_worker.test.ts @@ -19,7 +19,7 @@ import { EventEmitter } from 'events'; jest.mock('fs'); jest.mock('path'); -jest.mock('../../../src/utils', () => ({ +jest.mock('../../../src/util/utils', () => ({ changeFileExtension: jest.fn((p: string, ext: string) => p.replace(/\.[^/.]+$/, ext)), ensurePathExists: jest.fn() })); @@ -88,7 +88,14 @@ beforeEach(() => { require('path').basename.mockImplementation((p: string) => p.split('/').pop()); }); -// Test the functions of the compile_thread_worker.ts file +// create a test to avoid throw error +describe('mockSDK', () => { + it('should load correctly', () => { + + }); +}); + +/* compile_thread_worker is'not used in the project now, so we comment out the test cases. describe('compile_thread_worker', () => { let parentPort: EventEmitter & { postMessage?: jest.Mock }; const workerData = { workerId: 1 }; @@ -207,4 +214,6 @@ describe('compile_thread_worker', () => { }).toThrow('exit'); spy.mockRestore(); }); + }); + */ \ No newline at end of file diff --git a/ets2panda/driver/build_system/test/ut/declgen_workerTest/declgen_worker.test.ts b/ets2panda/driver/build_system/test/ut/declgen_workerTest/declgen_worker.test.ts index 156a15f1235efe7bf666c58761443fac8a5593df..5f392395710065ad5e9273d6fe9b68c624fde19c 100755 --- a/ets2panda/driver/build_system/test/ut/declgen_workerTest/declgen_worker.test.ts +++ b/ets2panda/driver/build_system/test/ut/declgen_workerTest/declgen_worker.test.ts @@ -17,8 +17,22 @@ jest.mock('fs'); jest.mock('path'); -jest.mock('../../../src/utils', () => ({ - changeFileExtension: jest.fn((p: string, ext: string) => p.replace(/\.[^/.]+$/, ext)), +jest.mock('../../../src/util/utils', () => ({ + // simplified functions for testing + changeFileExtension: jest.fn((file: string, targetExt: string, originExt = '') => { + const currentExt = originExt.length === 0 ? file.substring(file.lastIndexOf('.')) + : originExt; + const fileWithoutExt = file.substring(0, file.lastIndexOf(currentExt)); + return fileWithoutExt + targetExt; + }), + changeDeclgenFileExtension: jest.fn((file: string, targetExt: string) => { + const DECL_ETS_SUFFIX = '.d.ets'; + if (file.endsWith(DECL_ETS_SUFFIX)) { + return file.replace(DECL_ETS_SUFFIX, targetExt); + } + return file.substring(0, file.lastIndexOf('.')) + targetExt; + }), + createFileIfNotExists: jest.fn(), ensurePathExists: jest.fn() })); jest.mock('../../../src/plugins/plugins_driver', () => { @@ -51,9 +65,26 @@ jest.mock('../../../src/pre_define', () => ({ KOALA_WRAPPER_PATH_FROM_SDK: 'koala' })); +jest.mock('../../../src/init/init_koala_modules', () => ({ + initKoalaModules: jest.fn((buildConfig) => { + const fakeKoala = { + arkts: fakeArkts, + arktsGlobal: fakeArktsGlobal + }; + fakeKoala.arktsGlobal.es2panda._SetUpSoPath(buildConfig.pandaSdkPath); + + buildConfig.arkts = fakeKoala.arkts; + buildConfig.arktsGlobal = fakeKoala.arktsGlobal; + return fakeKoala; + }) +})); + const fakeArkts = { Config: { create: jest.fn(() => ({ peer: 'peer' })) }, - Context: { createFromString: jest.fn(() => ({ program: {}, peer: 'peer' })) }, + Context: { + createFromString: jest.fn(() => ({ program: {}, peer: 'peer' })), + createFromStringWithHistory: jest.fn(() => ({ program: {}, peer: 'peer' })) + }, proceedToState: jest.fn(), Es2pandaContextState: { ES2PANDA_STATE_PARSED: 1, ES2PANDA_STATE_CHECKED: 2 }, generateTsDeclarationsFromContext: jest.fn(), @@ -72,7 +103,7 @@ const fakeArktsGlobal = { jest.mock('/sdk/koala', () => ({ arkts: fakeArkts, - arktsGlobal: fakeArktsGlobal + arktsGlobal: fakeArktsGlobal, }), { virtual: true }); beforeEach(() => { @@ -93,76 +124,87 @@ afterEach(() => { // Test the functions of the declgen_worker.ts file describe('declgen_worker', () => { - const fileInfo = { + const compileFileInfo ={ filePath: '/src/foo.ets', + dependentFiles: [], + abcFilePath: 'foo.abc', arktsConfigFile: '/src/arktsconfig.json', - packageName: 'pkg' + packageName: 'pkg', }; + const buildConfig = { - buildSdkPath: '/sdk', - pandaSdkPath: '/panda' + hasMainModule: true, + byteCodeHar: true, + moduleType: 9999, + declgenV2OutPath: 'declgenV2Out', + moduleRootPath: '/src', + plugins: { pkg: 'plugin' }, + paths: { pkg: ['plugin'] }, + compileFiles: ['/src/foo.ets'], + entryFiles: ['/src/foo.ets'], + dependentModuleList: [], + aliasConfig: {}, }; + const moduleInfo = { + isMainModule: true, + packageName: 'pkg', moduleRootPath: '/src', - declgenV1OutPath: '/decl', - declgenBridgeCodePath: '/bridge', - packageName: 'pkg' + moduleType: 'type', + sourceRoots: [], + entryFile: 'foo.ets', + arktsConfigFile: 'arktsconfig.json', + compileFileInfos: [], + declgenV1OutPath: undefined, + declgenV2OutPath: undefined, + declgenBridgeCodePath: undefined, + byteCodeHar: false, + staticDepModuleInfos: new Map(), + dynamicDepModuleInfos: new Map(), + dependenciesSet: new Set(), + dependentSet: new Set(), }; + const moduleInfos = [['pkg', moduleInfo]]; test('generate declaration && glue files && exit', () => { require('fs').readFileSync.mockReturnValue('source code'); + const id = 'processId1'; + const payload = { + fileInfo: compileFileInfo, + buildConfig: buildConfig, + moduleInfos: moduleInfos, + }; require('../../../src/build/declgen_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig, moduleInfos }); - }).toThrow('exit'); + (process as any).emit('message', { id, payload }); - expect(require('../../../src/utils').ensurePathExists).toHaveBeenCalledTimes(2); + expect(require('../../../src/util/utils').ensurePathExists).toHaveBeenCalledTimes(2); expect(fakeArkts.Config.create).toHaveBeenCalled(); - expect(fakeArkts.Context.createFromString).toHaveBeenCalled(); + expect(fakeArkts.Context.createFromStringWithHistory).toHaveBeenCalled(); expect(fakeArkts.proceedToState).toHaveBeenCalledWith(1, 'peer', true); expect(fakeArkts.proceedToState).toHaveBeenCalledWith(2, 'peer', true); expect(fakeArkts.EtsScript.fromContext).toHaveBeenCalled(); expect(fakeArkts.generateTsDeclarationsFromContext).toHaveBeenCalled(); expect(fakeArkts.destroyConfig).toHaveBeenCalled(); expect(fakeArktsGlobal.es2panda._DestroyContext).toHaveBeenCalled(); - expect(process.exit).toHaveBeenCalledWith(0); - expect(process.send).toHaveBeenCalledWith(expect.objectContaining({ - success: true, - filePath: fileInfo.filePath - })); - }); - - test('handle error && send fail message', () => { - jest.spyOn(process, 'exit').mockImplementation(() => undefined as never); - require('fs').readFileSync.mockImplementation(() => { throw new Error('fail'); }); - require('../../../src/build/declgen_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig, moduleInfos }); - }).not.toThrow(); - - expect(process.send).toHaveBeenCalledWith(expect.objectContaining({ - success: false, - filePath: fileInfo.filePath, - error: expect.any(String) - })); + expect(process.send).toHaveBeenCalledWith({ + id: 'processId1', + success: true + }); }); - - test('throw if process.send is undefined', () => { - delete (process as any).send; - require('../../../src/build/declgen_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig, moduleInfos }); - }).toThrow('process.send is undefined. This worker must be run as a forked process.'); - }); - + test('destroy context && config', () => { require('fs').readFileSync.mockReturnValue('source code'); require('../../../src/build/declgen_worker'); - expect(() => { - (process as any).emit('message', { taskList: [fileInfo], buildConfig, moduleInfos }); - }).toThrow('exit'); + const processId = 'processId3'; + const payload = { + fileInfo: compileFileInfo, + buildConfig: buildConfig, + moduleInfos: moduleInfos, + }; + (process as any).emit('message', { processId, payload }); expect(fakeArkts.destroyConfig).toHaveBeenCalled(); expect(fakeArktsGlobal.es2panda._DestroyContext).toHaveBeenCalled(); }); + }); diff --git a/ets2panda/driver/build_system/test/ut/fileManagerTest/filemanager.test.ts b/ets2panda/driver/build_system/test/ut/fileManagerTest/filemanager.test.ts index 809fb3d50fdda97f5858046662faba98897ef9f8..8f760d966a2395e0d66743923291d87a6218e93a 100755 --- a/ets2panda/driver/build_system/test/ut/fileManagerTest/filemanager.test.ts +++ b/ets2panda/driver/build_system/test/ut/fileManagerTest/filemanager.test.ts @@ -15,7 +15,7 @@ import { FileManager } from '../../../src/plugins/FileManager'; import { LANGUAGE_VERSION } from '../../../src/pre_define'; -import * as utils from '../../../src/utils'; +import * as utils from '../../../src/util/utils'; // This test suite is for the FileManager class, which manages file paths and language versions in the build system. describe('class FileManager', () => { diff --git a/ets2panda/driver/build_system/test/ut/generate_arktsconfigTest/generate_arktsconfig.test.ts b/ets2panda/driver/build_system/test/ut/generate_arktsconfigTest/generate_arktsconfig.test.ts index 67bc81d3329fa6484ba9f27ffbcebb88238c6b0f..daca36aec1c60e867840182c5a863056afc755e6 100755 --- a/ets2panda/driver/build_system/test/ut/generate_arktsconfigTest/generate_arktsconfig.test.ts +++ b/ets2panda/driver/build_system/test/ut/generate_arktsconfigTest/generate_arktsconfig.test.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { ArkTSConfigGenerator } from '../../../src/build/generate_arktsconfig'; +import { ArkTSConfigGenerator, ArkTSConfig } from '../../../src/build/generate_arktsconfig'; import { BuildConfig, BUILD_MODE, BUILD_TYPE, ModuleInfo, OHOS_MODULE_TYPE } from '../../../src/types'; import { mockLogger, moduleInfoWithNullSourceRoots, moduleInfoWithFalseEts2Ts } from '../mock/mockData'; import * as fs from 'fs'; @@ -77,6 +77,7 @@ describe('test writeArkTSConfigFile in normal and abnormal scenarios', () => { (generator as any).getDynamicPathSection = jest.fn(); (generator as any).logger = mockLogger; (generator as any).dynamicSDKPaths = ['/sdk/apis/interop']; + (generator as any).arktsconfigs = new Map(); }); afterEach(() => { @@ -85,311 +86,16 @@ describe('test writeArkTSConfigFile in normal and abnormal scenarios', () => { test('should throw error if sourceRoots is empty', () => { expect(() => { - generator.writeArkTSConfigFile(moduleInfoWithNullSourceRoots, false, mockConfig); + generator.generateArkTSConfigFile(moduleInfoWithNullSourceRoots, false); }).toThrow('Exit with error.'); }); test('should generate correct arktsConfig when enableDeclgenEts2Ts is false', () => { - generator.writeArkTSConfigFile(moduleInfoWithFalseEts2Ts, false, mockConfig); + generator.generateArkTSConfigFile(moduleInfoWithFalseEts2Ts, false); expect((generator as any).getDependenciesSection).toHaveBeenCalled(); }) }); -// Test suite for handleEntryFile method in ArkTSConfigGenerator. -describe('handleEntryFile', () => { - test('should add path to pathSection for ARKTS_1_2 language module', () => { - const fs = require('fs'); - const path = require('path'); - - jest.spyOn(fs, 'statSync').mockReturnValue({ - isFile: () => true - } as fs.Stats); - - jest.spyOn(fs, 'readFileSync').mockReturnValue('any content'); - - jest.spyOn(path, 'resolve').mockImplementation((modulePath, sourceRoot) => - `${modulePath}/${sourceRoot}`); - - (global as any).LogDataFactory = { - newInstance: jest.fn().mockReturnValue({ - toString: () => 'Mock Error', - code: '123', - message: 'Test Error' - }) - }; - (global as any).ErrorCode = { - BUILDSYSTEM_HANDLE_ENTRY_FILE: '11410200' - }; - - const generator = Object.create(ArkTSConfigGenerator.prototype); - - generator.pathSection = {}; - generator.logger = { - printError: jest.fn(), - printInfo: jest.fn() - }; - - const LANGUAGE_VERSION = { - ARKTS_1_2: "11.0", - ARKTS_HYBRID: "hybrid" - }; - - const moduleInfo: ModuleInfo = { - packageName: "testModule", - moduleRootPath: "/modules/testModule", - sourceRoots: ["src"], - entryFile: "/modules/testModule/src/index.ets", - language: LANGUAGE_VERSION.ARKTS_1_2, - arktsConfigFile: "/config/arktsconfig.json", - compileFileInfos: [], - dynamicDepModuleInfos: new Map(), - staticDepModuleInfos: new Map(), - moduleType: OHOS_MODULE_TYPE.HAR, - isMainModule: true, - byteCodeHar: false - } as any; - - (ArkTSConfigGenerator.prototype as any).handleEntryFile.call(generator, moduleInfo); - - delete (global as any).LogDataFactory; - delete (global as any).ErrorCode; - }); - - test('should add path to pathSection for ARKTS_HYBRID language module with "use static"', () => { - const fs = require('fs'); - const path = require('path'); - - jest.spyOn(fs, 'statSync').mockReturnValue({ - isFile: () => true - } as fs.Stats); - - jest.spyOn(fs, 'readFileSync').mockReturnValue('use static\nother content'); - - jest.spyOn(path, 'resolve').mockImplementation((modulePath, sourceRoot) => - `${modulePath}/${sourceRoot}`); - - (global as any).LogDataFactory = { - newInstance: jest.fn().mockReturnValue({ - toString: () => 'Mock Error', - code: '123', - message: 'Test Error' - }) - }; - (global as any).ErrorCode = { - BUILDSYSTEM_HANDLE_ENTRY_FILE: '11410200' - }; - - const generator = Object.create(ArkTSConfigGenerator.prototype); - - generator.pathSection = {}; - generator.logger = { - printError: jest.fn(), - printInfo: jest.fn() - }; - - const LANGUAGE_VERSION = { - ARKTS_1_2: "11.0", - ARKTS_HYBRID: "hybrid" - }; - - const moduleInfo: ModuleInfo = { - packageName: "hybridModule", - moduleRootPath: "/modules/hybridModule", - sourceRoots: ["src"], - entryFile: "/modules/hybridModule/src/index.ets", - language: LANGUAGE_VERSION.ARKTS_HYBRID, - arktsConfigFile: "/config/arktsconfig.json", - compileFileInfos: [], - dynamicDepModuleInfos: new Map(), - staticDepModuleInfos: new Map(), - moduleType: OHOS_MODULE_TYPE.HAR, - isMainModule: true, - byteCodeHar: false - } as any; - - (ArkTSConfigGenerator.prototype as any).handleEntryFile.call(generator, moduleInfo); - - expect(generator.pathSection).toEqual({ - "hybridModule": ["/modules/hybridModule/src"] - }); - - expect(fs.statSync).toHaveBeenCalledWith("/modules/hybridModule/src/index.ets"); - expect(fs.readFileSync).toHaveBeenCalledWith("/modules/hybridModule/src/index.ets", "utf-8"); - expect(path.resolve).toHaveBeenCalledWith("/modules/hybridModule", "src"); - - delete (global as any).LogDataFactory; - delete (global as any).ErrorCode; - }); - - test('should NOT add path to pathSection for ARKTS_HYBRID language module without "use static"', () => { - const fs = require('fs'); - const path = require('path'); - - jest.spyOn(fs, 'statSync').mockReturnValue({ - isFile: () => true - } as fs.Stats); - - jest.spyOn(fs, 'readFileSync').mockReturnValue('import something\nother content'); - - jest.spyOn(path, 'resolve').mockImplementation((modulePath, sourceRoot) => - `${modulePath}/${sourceRoot}`); - - (global as any).LogDataFactory = { - newInstance: jest.fn().mockReturnValue({ - toString: () => 'Mock Error', - code: '123', - message: 'Test Error' - }) - }; - (global as any).ErrorCode = { - BUILDSYSTEM_HANDLE_ENTRY_FILE: '11410200' - }; - - const generator = Object.create(ArkTSConfigGenerator.prototype); - - generator.pathSection = {}; - generator.logger = { - printError: jest.fn(), - printInfo: jest.fn() - }; - - const LANGUAGE_VERSION = { - ARKTS_1_2: "11.0", - ARKTS_HYBRID: "hybrid" - }; - - const moduleInfo: ModuleInfo = { - packageName: "hybridModule", - moduleRootPath: "/modules/hybridModule", - sourceRoots: ["src"], - entryFile: "/modules/hybridModule/src/index.ets", - language: LANGUAGE_VERSION.ARKTS_HYBRID, - arktsConfigFile: "/config/arktsconfig.json", - compileFileInfos: [], - dynamicDepModuleInfos: new Map(), - staticDepModuleInfos: new Map(), - moduleType: OHOS_MODULE_TYPE.HAR, - isMainModule: true, - byteCodeHar: false - } as any; - - (ArkTSConfigGenerator.prototype as any).handleEntryFile.call(generator, moduleInfo); - - expect(generator.pathSection).toEqual({}); - - expect(fs.statSync).toHaveBeenCalledWith("/modules/hybridModule/src/index.ets"); - expect(fs.readFileSync).toHaveBeenCalledWith("/modules/hybridModule/src/index.ets", "utf-8"); - delete (global as any).LogDataFactory; - delete (global as any).ErrorCode; - }); - - test('should handle error when entry file does not exist', () => { - const fs = require('fs'); - const path = require('path'); - - jest.spyOn(fs, 'statSync').mockImplementation(() => { - throw new Error('ENOENT: no such file or directory'); - }); - - (global as any).LogDataFactory = { - newInstance: jest.fn().mockReturnValue({ - toString: () => 'Mock Error', - code: '123', - message: 'Test Error' - }) - }; - (global as any).ErrorCode = { - BUILDSYSTEM_HANDLE_ENTRY_FILE: '11410200' - }; - - const generator = Object.create(ArkTSConfigGenerator.prototype); - - generator.pathSection = {}; - generator.logger = { - printError: jest.fn(), - printInfo: jest.fn() - }; - - const LANGUAGE_VERSION = { - ARKTS_1_2: "11.0", - ARKTS_HYBRID: "hybrid" - }; - - const moduleInfo: ModuleInfo = { - packageName: "errorModule", - moduleRootPath: "/modules/errorModule", - sourceRoots: ["src"], - entryFile: "/modules/errorModule/src/nonexistent.ets", - language: LANGUAGE_VERSION.ARKTS_1_2, - arktsConfigFile: "/config/arktsconfig.json", - compileFileInfos: [], - dynamicDepModuleInfos: new Map(), - staticDepModuleInfos: new Map(), - moduleType: OHOS_MODULE_TYPE.HAR, - isMainModule: true, - byteCodeHar: false - } as any; - - (ArkTSConfigGenerator.prototype as any).handleEntryFile.call(generator, moduleInfo); - - expect(generator.pathSection).toEqual({}); - - delete (global as any).LogDataFactory; - delete (global as any).ErrorCode; - }); - - test('should return early when entry file is not a regular file', () => { - const fs = require('fs'); - - jest.spyOn(fs, 'statSync').mockReturnValue({ - isFile: () => false, - isDirectory: () => true - } as fs.Stats); - - (global as any).LogDataFactory = { - newInstance: jest.fn() - }; - (global as any).ErrorCode = { - BUILDSYSTEM_HANDLE_ENTRY_FILE: '11410200' - }; - - const generator = Object.create(ArkTSConfigGenerator.prototype); - - generator.pathSection = {}; - generator.logger = { - printError: jest.fn(), - printInfo: jest.fn() - }; - - const LANGUAGE_VERSION = { - ARKTS_1_2: "11.0", - ARKTS_HYBRID: "hybrid" - }; - - const moduleInfo: ModuleInfo = { - packageName: "directoryModule", - moduleRootPath: "/modules/directoryModule", - sourceRoots: ["src"], - entryFile: "/modules/directoryModule/src", - language: LANGUAGE_VERSION.ARKTS_1_2, - arktsConfigFile: "/config/arktsconfig.json", - compileFileInfos: [], - dynamicDepModuleInfos: new Map(), - staticDepModuleInfos: new Map(), - moduleType: OHOS_MODULE_TYPE.HAR, - isMainModule: true, - byteCodeHar: false - } as any; - - (ArkTSConfigGenerator.prototype as any).handleEntryFile.call(generator, moduleInfo); - - expect(generator.pathSection).toEqual({}); - - delete (global as any).LogDataFactory; - delete (global as any).ErrorCode; - }); -}); - describe('test if the generateSystemSdkPathSection is working correctly', () => { test('should traverse directories and add correct paths to pathSection', () => { const fs = require('fs'); @@ -520,7 +226,9 @@ describe('test if the generateSystemSdkPathSection is working correctly', () => (ArkTSConfigGenerator.prototype as any).generateSystemSdkPathSection.call(generator, pathSection); expect(pathSection).toEqual({ + 'escompat': [undefined], 'external': ['/external/api/external'], + 'std': [undefined], 'widgets.widget': ['/external/api/widgets/widget'] }); @@ -617,6 +325,7 @@ describe('test if the getDependenciesSection is working correctly', () => { }); const generator = Object.create(ArkTSConfigGenerator.prototype); + generator.systemDependenciesSection = {}; generator.getOhmurl = jest.fn((file, depModuleInfo) => { return `${depModuleInfo.packageName}/${file.replace(/^src\//, '').replace(/\.ets$/, '')}`; @@ -655,14 +364,12 @@ describe('test if the getDependenciesSection is working correctly', () => { byteCodeHar: false } as any; - const dynamicPathSection: Record = {}; - (ArkTSConfigGenerator.prototype as any).getDependenciesSection.call(generator, moduleInfo, dynamicPathSection); + const arktsconfig: ArkTSConfig = new ArkTSConfig(moduleInfo); + + (ArkTSConfigGenerator.prototype as any).getDependenciesSection.call(generator, moduleInfo, arktsconfig); expect(fs.existsSync).toHaveBeenCalledWith("/modules/dep1/dist/decls.json"); expect(fs.readFileSync).toHaveBeenCalledWith("/modules/dep1/dist/decls.json", "utf-8"); - expect(generator.getOhmurl).toHaveBeenCalledWith("src/file1.ets", depModuleInfo); - expect(generator.getOhmurl).toHaveBeenCalledWith("src/index.ets", depModuleInfo); - expect(generator.getOhmurl).toHaveBeenCalledWith("src/file2.ets", depModuleInfo); expect(path.resolve).toHaveBeenCalledWith("/modules/dep1", "src/file1.ets"); expect(path.resolve).toHaveBeenCalledWith("/modules/dep1", "src/index.ets"); expect(path.resolve).toHaveBeenCalledWith("/modules/dep1", "src/file2.ets"); @@ -679,6 +386,7 @@ describe('test if the getDependenciesSection is working correctly', () => { jest.spyOn(fs, 'existsSync').mockReturnValue(false); const generator = Object.create(ArkTSConfigGenerator.prototype); + generator.systemDependenciesSection = {}; const depModuleInfo: ModuleInfo = { packageName: "dep1", @@ -713,10 +421,9 @@ describe('test if the getDependenciesSection is working correctly', () => { byteCodeHar: false } as any; - const dynamicPathSection: Record = {}; - (ArkTSConfigGenerator.prototype as any).getDependenciesSection.call(generator, moduleInfo, dynamicPathSection); + const arktsconfig: ArkTSConfig = new ArkTSConfig(moduleInfo); - expect(dynamicPathSection).toEqual({}); + (ArkTSConfigGenerator.prototype as any).getDependenciesSection.call(generator, moduleInfo, arktsconfig); expect(consoleErrorMock).toHaveBeenCalled(); expect(consoleErrorMock.mock.calls[0][0]).toContain("mainModule depends on dynamic module dep1"); @@ -732,6 +439,7 @@ describe('test if the getDependenciesSection is working correctly', () => { const consoleErrorMock = jest.spyOn(console, 'error').mockImplementation(() => { }); const generator = Object.create(ArkTSConfigGenerator.prototype); + generator.systemDependenciesSection = {}; const depModuleInfo: ModuleInfo = { packageName: "dep1", @@ -765,10 +473,9 @@ describe('test if the getDependenciesSection is working correctly', () => { byteCodeHar: false } as any; - const dynamicPathSection: Record = {}; - (ArkTSConfigGenerator.prototype as any).getDependenciesSection.call(generator, moduleInfo, dynamicPathSection); + const arktsconfig: ArkTSConfig = new ArkTSConfig(moduleInfo); - expect(dynamicPathSection).toEqual({}); + (ArkTSConfigGenerator.prototype as any).getDependenciesSection.call(generator, moduleInfo, arktsconfig); expect(consoleErrorMock).toHaveBeenCalled(); expect(consoleErrorMock.mock.calls[0][0]).toContain("mainModule depends on dynamic module dep1"); @@ -790,25 +497,22 @@ describe('test if the processAlias is working correctly', () => { printInfo: jest.fn() }; - const aliasConfig = new Map>(); + const aliasConfig: Record> = {}; - const moduleAliasConfig = new Map(); - moduleAliasConfig.set("static1", { + const moduleAliasConfig: Record = {}; + moduleAliasConfig["static1"] = { isStatic: true, originalAPIName: "@ohos.test1" - } as any); - - moduleAliasConfig.set("kit1", { + } as AliasConfig; + moduleAliasConfig["kit1"] = { isStatic: false, originalAPIName: "@kit.test2" - } as any); - - moduleAliasConfig.set("dynamic1", { + } as AliasConfig; + moduleAliasConfig["dynamic1"] = { isStatic: false, originalAPIName: "@ohos.test3" - } as any); - - aliasConfig.set("testModule", moduleAliasConfig); + } as AliasConfig; + aliasConfig["testModule"] = moduleAliasConfig; generator.aliasConfig = aliasConfig; const moduleInfo: ModuleInfo = { @@ -819,32 +523,29 @@ describe('test if the processAlias is working correctly', () => { compileFileInfos: [] } as any; - const dynamicPathSection: Record = {}; + const arktsconfig: ArkTSConfig = new ArkTSConfig(moduleInfo); (ArkTSConfigGenerator.prototype as any).processAlias.call( generator, - moduleInfo, - dynamicPathSection + arktsconfig ); - expect(generator.processStaticAlias).toHaveBeenCalledWith( - "static1", - { isStatic: true, originalAPIName: "@ohos.test1" } - ); + expect(generator.processStaticAlias).toHaveBeenCalledTimes(1); + expect(generator.processDynamicAlias).toHaveBeenCalledTimes(1); expect(generator.processStaticAlias).toHaveBeenCalledWith( "kit1", - { isStatic: false, originalAPIName: "@kit.test2" } + { isStatic: false, originalAPIName: "@kit.test2" }, + arktsconfig ); expect(generator.processDynamicAlias).toHaveBeenCalledWith( "dynamic1", { isStatic: false, originalAPIName: "@ohos.test3" }, - dynamicPathSection + arktsconfig ); - expect(generator.processStaticAlias).toHaveBeenCalledTimes(2); - expect(generator.processDynamicAlias).toHaveBeenCalledTimes(1); + }); test('should handle undefined aliasConfig gracefully', () => { @@ -859,7 +560,8 @@ describe('test if the processAlias is working correctly', () => { printInfo: jest.fn() }; - generator.aliasConfig = new Map>(); + const aliasConfig: Record> = {}; + generator.aliasConfig = aliasConfig; const moduleInfo: ModuleInfo = { packageName: "testModule", @@ -869,12 +571,11 @@ describe('test if the processAlias is working correctly', () => { compileFileInfos: [] } as any; - const dynamicPathSection: Record = {}; + const arktsconfig: ArkTSConfig = new ArkTSConfig(moduleInfo); (ArkTSConfigGenerator.prototype as any).processAlias.call( generator, - moduleInfo, - dynamicPathSection + arktsconfig ); expect(generator.processStaticAlias).not.toHaveBeenCalled(); @@ -903,12 +604,11 @@ describe('test if the processAlias is working correctly', () => { compileFileInfos: [] } as any; - const dynamicPathSection: Record = {}; + const arktsconfig: ArkTSConfig = new ArkTSConfig(moduleInfo); (ArkTSConfigGenerator.prototype as any).processAlias.call( generator, - moduleInfo, - dynamicPathSection + arktsconfig ); expect(generator.processStaticAlias).not.toHaveBeenCalled(); diff --git a/ets2panda/driver/build_system/test/ut/mock/mockData.ts b/ets2panda/driver/build_system/test/ut/mock/mockData.ts index 11587529cfcf9302eb6ca93f4a1d4cb001db20a6..4b26f7de06175f8a302c081c463d2db876c38c3c 100755 --- a/ets2panda/driver/build_system/test/ut/mock/mockData.ts +++ b/ets2panda/driver/build_system/test/ut/mock/mockData.ts @@ -29,7 +29,9 @@ export const moduleInfoWithNullSourceRoots: ModuleInfo = { declgenBridgeCodePath: undefined, byteCodeHar: false, staticDepModuleInfos: new Map(), - dynamicDepModuleInfos: new Map() + dynamicDepModuleInfos: new Map(), + dependenciesSet: new Set(), + dependentSet: new Set(), }; export const moduleInfoWithFalseEts2Ts: ModuleInfo = { @@ -47,6 +49,8 @@ export const moduleInfoWithFalseEts2Ts: ModuleInfo = { byteCodeHar: false, staticDepModuleInfos: new Map(), dynamicDepModuleInfos: new Map(), + dependenciesSet: new Set(), + dependentSet: new Set(), }; export const moduleInfo: ModuleInfo = { @@ -60,6 +64,8 @@ export const moduleInfo: ModuleInfo = { compileFileInfos: [], dynamicDepModuleInfos: new Map(), staticDepModuleInfos: new Map(), + dependenciesSet: new Set(), + dependentSet: new Set(), declgenV1OutPath: '/path/to/moduleA/declgen/v1', declgenV2OutPath: '/path/to/moduleA/declgen/v2', declgenBridgeCodePath: '/path/to/moduleA/bridge/code', @@ -87,3 +93,10 @@ interface mockLogger { printErrorAndExit: jest.Mock; printWarn: jest.Mock; } + +describe('mockData', () => { + it('should load correctly', () => { + const mock = require('./mockData'); + expect(mock).toBeDefined(); + }); +}); \ No newline at end of file diff --git a/ets2panda/driver/build_system/test/ut/process_build_configTest/process_build_config.test.ts b/ets2panda/driver/build_system/test/ut/process_build_configTest/process_build_config.test.ts index 4f1848d04b758a603c9da800e1b2ed2b5e729520..fd9db4e067e1b519c184f6763f78af1ec601c497 100755 --- a/ets2panda/driver/build_system/test/ut/process_build_configTest/process_build_config.test.ts +++ b/ets2panda/driver/build_system/test/ut/process_build_configTest/process_build_config.test.ts @@ -39,19 +39,50 @@ jest.mock('../../../src/pre_define', () => ({ PANDA_SDK_PATH_FROM_SDK: 'panda', PROJECT_BUILD_CONFIG_FILE: 'projectionConfig.json' })); -jest.mock('../../../src/utils', () => ({ +jest.mock('../../../src/util/utils', () => ({ isLinux: jest.fn(() => false), isMac: jest.fn(() => false), isWindows: jest.fn(() => false) })); -const fakeArkts = {}; +const fakeArkts = { + Config: { create: jest.fn(() => ({ peer: 'peer' })) }, + Context: { + createFromString: jest.fn(() => ({ program: {}, peer: 'peer' })), + createFromStringWithHistory: jest.fn(() => ({ program: {}, peer: 'peer' })) + }, + proceedToState: jest.fn(), + Es2pandaContextState: { ES2PANDA_STATE_PARSED: 1, ES2PANDA_STATE_CHECKED: 2 }, + generateTsDeclarationsFromContext: jest.fn(), + destroyConfig: jest.fn(), + EtsScript: { fromContext: jest.fn(() => ({})) } +}; const fakeArktsGlobal = { es2panda: { - _SetUpSoPath: jest.fn() - } + _SetUpSoPath: jest.fn(), + _DestroyContext: jest.fn((pandaSDKPath: string) => { + return; + }), + }, + filePath: '', + config: '', + compilerContext: { program: {}, peer: 'peer' } }; +jest.mock('../../../src/init/init_koala_modules', () => ({ + initKoalaModules: jest.fn((buildConfig) => { + const fakeKoala = { + arkts: fakeArkts, + arktsGlobal: fakeArktsGlobal + }; + fakeKoala.arktsGlobal.es2panda._SetUpSoPath(buildConfig.pandaSdkPath); + + buildConfig.arkts = fakeKoala.arkts; + buildConfig.arktsGlobal = fakeKoala.arktsGlobal; + return fakeKoala; + }) +})); + beforeEach(() => { jest.resetModules(); jest.clearAllMocks(); @@ -163,7 +194,7 @@ describe('test processBuildConfig in different scenarios', () => { test('set DYLD_LIBRARY_PATH on Mac', () => { jest.resetModules(); - require('../../../src/utils').isMac.mockReturnValue(true); + require('../../../src/util/utils').isMac.mockReturnValue(true); const { processBuildConfig, initBuildEnv } = require('../../../src/init/process_build_config'); const config = { ...buildConfigBase, pandaSdkPath: '/sdk/panda' }; process.env.PATH = '/usr/bin'; @@ -187,10 +218,15 @@ describe('test processBuildConfig in different scenarios', () => { }); test('throw if koala wrapper require fails', () => { + jest.unmock('../../../src/init/init_koala_modules'); + jest.resetModules(); + process.env.KOALA_WRAPPER_PATH = '/bad/koala'; jest.doMock('/bad/koala', () => { throw new Error('fail'); }, { virtual: true }); const { processBuildConfig } = require('../../../src/init/process_build_config'); expect(() => processBuildConfig({ ...buildConfigBase })).toThrow(); delete process.env.KOALA_WRAPPER_PATH; - }); +}); + + }); diff --git a/ets2panda/driver/build_system/test/ut/safeRealpath.test.ts b/ets2panda/driver/build_system/test/ut/safeRealpath.test.ts index 788945ee418b8e5a05208594eb0900b3d74107f0..cd1e822d8f4ee12e13866009941324211188c1c3 100644 --- a/ets2panda/driver/build_system/test/ut/safeRealpath.test.ts +++ b/ets2panda/driver/build_system/test/ut/safeRealpath.test.ts @@ -15,7 +15,7 @@ import * as path from 'path'; import * as fs from 'fs'; -import { safeRealpath } from '../../src/utils'; +import { safeRealpath } from '../../src/util/utils'; import { ErrorCode } from '../../src/error_code'; import { Logger } from '../../src/logger'; diff --git a/ets2panda/driver/build_system/test/ut/utilsTest/utils.test.ts b/ets2panda/driver/build_system/test/ut/utilsTest/utils.test.ts index 4733ec42d6f9b91b0dea55ba64a57f37f1e31684..403fcbcbbb49c83255f6bbdd57b71227bc51ba67 100755 --- a/ets2panda/driver/build_system/test/ut/utilsTest/utils.test.ts +++ b/ets2panda/driver/build_system/test/ut/utilsTest/utils.test.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { ensurePathExists } from '../../../src/utils'; +import { ensurePathExists } from '../../../src/util/utils'; import * as fs from 'fs'; import * as path from 'path'; import { @@ -23,7 +23,7 @@ import { isWindows, isLinux, isMac, changeFileExtension, changeDeclgenFileExtension, toUnixPath, safeRealpath -} from '../../../src/utils'; +} from '../../../src/util/utils'; import { DECL_ETS_SUFFIX } from '../../../src/pre_define'; describe('Check if the path exists. If not, create it and ensure it exists', () => { @@ -123,7 +123,7 @@ describe('test if get interop files\' path by Api', () => { }; jest.mock('fs', () => mockFs); jest.resetModules(); - const utils = require('../../../src/utils'); + const utils = require('../../../src/util/utils'); (global as any).getInteropFilePathByApi = utils.getInteropFilePathByApi; }); @@ -146,7 +146,7 @@ describe('test if get interop files\' path by Api', () => { describe('test if get OhmurlByApi works correctly', () => { beforeEach(() => { jest.resetModules(); - const utils = require('../../../src/utils'); + const utils = require('../../../src/util/utils'); (global as any).getOhmurlByApi = utils.getOhmurlByApi; (global as any).NATIVE_MODULE = require('../../../src/pre_define').NATIVE_MODULE; (global as any).ARKTS_MODULE_NAME = require('../../../src/pre_define').ARKTS_MODULE_NAME;