Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use WebAssembly version libraries for unit testing #16264

Merged
merged 3 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@ const { compilerOptions } = tsConfig.config;
module.exports = {
testEnvironment: './tests/test-environment.ts',
testRegex: '/tests/.*\\.(test|spec)?\\.(ts|tsx)$',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: `${__dirname}/` }),
moduleNameMapper: {
...pathsToModuleNameMapper(compilerOptions.paths, { prefix: `${__dirname}/` }),
'external:(.*)': '<rootDir>/native/external/$1',
},
transformIgnorePatterns: [
// ignore everything in the node_modules EXCEPT for:
// - @cocos/dragonbones-js
'node_modules/(?!(@cocos/dragonbones-js)/)',
'native/external/emscripten/',
// ignore everything in the native/external/emscripten EXCEPT for:
// - meshopt
// Since above packages are in ESM module format, whereas we currently use CJS for testing.
'native/external/emscripten/(?!(meshopt)/)',
],
setupFilesAfterEnv: [
"./tests/setup-after-env.ts",
Expand Down
4 changes: 3 additions & 1 deletion tests/constants-for-test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { WebAssemblySupportMode } from "../cocos/misc/webassembly-support";

const _globalThis = typeof global === 'undefined' ? globalThis : global;
const _global = typeof window === 'undefined' ? _globalThis : window;

Expand Down Expand Up @@ -39,4 +41,4 @@ export const VIVO = tryDefineGlobal('CC_VIVO', false);
// @ts-expect-error: 'loadRuntime' exits only in runtime environment.
export const SUPPORT_JIT = tryDefineGlobal('CC_SUPPORT_JIT', (typeof loadRuntime === 'function'));
export const SERVER_MODE = false;
export const WASM_SUPPORT_MODE = 0;
export const WASM_SUPPORT_MODE = WebAssemblySupportMode.SUPPORT;
73 changes: 5 additions & 68 deletions tests/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ jest.mock(

jest.mock(
'pal/wasm',
() => jest.requireActual('../pal/wasm/wasm-native'), // NOTE: fix CI, we used import.meta in wasm-web.ts
() => jest.requireActual('./utils/pal-wasm-testing'), // NOTE: fix CI, we used import.meta in wasm-web.ts
{ virtual: true, },
);

Expand All @@ -81,80 +81,17 @@ jest.mock(
'external:emscripten/physx/physx.release.wasm.wasm',
'external:emscripten/spine/spine.wasm',
'external:emscripten/box2d/box2d.release.wasm.wasm',
].forEach(moduleId => {
jest.mock(moduleId,
'external:emscripten/meshopt/meshopt_decoder.wasm.wasm',
].forEach(mockModuleId => {
jest.mock(mockModuleId,
() => ({
__esModule: true,
default: 'this should be a wasm url',
default: mockModuleId,
}),
{ virtual: true, },
);
});

jest.mock('external:emscripten/meshopt/meshopt_decoder.wasm.wasm',
() => ({
__esModule: true,
default: 'this should be a wasm url',
}),
{ virtual: true, },
);

// Mock external wasm js module here
[
'external:emscripten/webgpu/webgpu_wasm.js',
'external:emscripten/webgpu/glslang.js',
'external:emscripten/physx/physx.release.wasm.js',
'external:emscripten/spine/spine.js',
'external:emscripten/box2d/box2d.release.wasm.js',
].forEach(moduleId => {
jest.mock(moduleId,
() => ({
__esModule: true,
default: function factory () { return Promise.resolve({}); },
}),
{ virtual: true, },
);
});

jest.mock('external:emscripten/meshopt/meshopt_decoder.wasm.js',
() => ({
__esModule: true,
default: function factory () { return Promise.resolve({}); },
}),
{ virtual: true, },
);

jest.mock(
'external:emscripten/physx/physx.release.asm.js',
() => jest.requireActual('../native/external/emscripten/physx/physx.release.asm.js'),
{ virtual: true },
);


jest.mock(
'external:emscripten/bullet/bullet.asm.js',
() => jest.requireActual('../native/external/emscripten/bullet/bullet.asm.js'),
{ virtual: true },
);

jest.mock(
'external:emscripten/meshopt/meshopt_decoder.asm.js',
() => jest.requireActual('../native/external/emscripten/meshopt/meshopt_decoder.asm.js'),
{ virtual: true },
);

jest.mock(
'external:emscripten/spine/spine.asm.js',
() => jest.requireActual('../native/external/emscripten/spine/spine.asm.js'),
{ virtual: true },
);

jest.mock(
'external:emscripten/box2d/box2d.release.asm.js',
() => jest.requireActual('../native/external/emscripten/box2d/box2d.release.asm.js'),
{ virtual: true },
);

jest.mock('../cocos/core/platform/debug', () => {
const result = {
__esModule: true, // Use it when dealing with esModules
Expand Down
6 changes: 4 additions & 2 deletions tests/physics/physics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ import CharacterControllerTest from "./character-controller";
import { Node, Scene } from "../../cocos/scene-graph";
import { builtinResMgr } from "../../exports/base";

waitForAmmoInstantiation();
InitPhysXLibs();
beforeAll(async () => {
await waitForAmmoInstantiation();
await InitPhysXLibs();
});

game.emit(Game.EVENT_PRE_SUBSYSTEM_INIT);
// Manually construct and register the system
Expand Down
5 changes: 4 additions & 1 deletion tests/physics2d/physics2d.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import * as physics2d from "../../exports/physics-2d-framework";
import { Node, Scene } from "../../cocos/scene-graph";

import waitForBox2dWasmInstantiation from "../../exports/wait-for-box2d-instantiation";
waitForBox2dWasmInstantiation();
import "../../exports/physics-2d-box2d-wasm";
import "../../exports/physics-2d-box2d";
import "../../exports/physics-2d-builtin";
Expand All @@ -17,6 +16,10 @@ import EventTest from "./events";
game.emit(Game.EVENT_PRE_SUBSYSTEM_INIT);
physics2d.PhysicsSystem2D.constructAndRegister();

beforeAll(async () => {
await waitForBox2dWasmInstantiation();
});

test(`physics2d test | utils`, done => {
Utils();
done();
Expand Down
53 changes: 53 additions & 0 deletions tests/utils/pal-wasm-testing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
Copyright (c) 2023 Xiamen Yaji Software Co., Ltd.

https://www.cocos.com/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

import { checkPalIntegrity, withImpl } from '../../pal/integrity-check';
import { join } from 'node:path';
import { readFileSync } from 'node:fs';

export async function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise<any> {
return fetchBuffer(wasmUrl).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, importObject));
}

export async function fetchBuffer (binaryUrl: string): Promise<ArrayBuffer> {
const relativePathToExternal = /^external:(.*)/.exec(binaryUrl)?.[1];
if (relativePathToExternal) {
const externalHome = join(__dirname, '..', '..', 'native', 'external');
const path = join(externalHome, relativePathToExternal);
try {
const content = readFileSync(path);
return content.buffer;
} catch (err) {
throw new Error(`Unable to fetch buffer from ${binaryUrl}`, { cause: error });
}
}

throw new Error(`Don't know how to fetch buffer at url ${binaryUrl}`);
}

export async function ensureWasmModuleReady() {
return Promise.resolve();
}

checkPalIntegrity<typeof import('@pal/wasm')>(withImpl<typeof import('./pal-wasm-testing')>());
Comment on lines +29 to +53
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why add this file ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes it possible to use wasm in unit test.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why don't actually mock pal/wasm module to the web implementation

Loading