feat: 添加新的模块测试支持

This commit is contained in:
msojocs 2024-07-06 09:41:39 +08:00
parent 7944fb6190
commit ce6a977c17
30 changed files with 4919 additions and 28 deletions

View File

@ -6,29 +6,28 @@ const wcsc = (args: string[], projectPath: string, outputPath: string | undefine
if(!fs.existsSync(projectPath)){
throw new Error('projectPath not exists.')
}
const node_exec = spawn(
const binaryExec = spawn(
path.resolve(__dirname, "../../build/wcsc"),
args,
{
cwd: projectPath,
env: {
WX_DEBUG_COMPILER_OUTPUT: outputPath,
},
// stdio: 'inherit'
}
);
const spwanData: any[] = [],
errData: any[] = [];
node_exec.stdout.on("data", (e) => {
binaryExec.stdout.on("data", (e) => {
spwanData.push(e);
// console.log(e.toString())
});
node_exec.stderr.on("data", (e) => {
binaryExec.stderr.on("data", (e) => {
errData.push(e);
// console.log(e.toString())
});
return new Promise((resolve, reject) => {
node_exec.on("close", (n) => {
binaryExec.on("close", (n) => {
outputPath && require('fs').writeFileSync(`${outputPath}/linux_err.js`, Buffer.concat(errData).toString())
if (0 === n) {
@ -47,29 +46,28 @@ const wcc = (args: string[], projectPath: string, outputPath: string | undefined
if(!fs.existsSync(projectPath)){
throw new Error('projectPath not exists.')
}
const node_exec = spawn(
const binaryExec = spawn(
path.resolve(__dirname, "../../build/wcc"),
args,
{
cwd: projectPath,
env: {
WX_DEBUG_COMPILER_OUTPUT: outputPath,
},
// stdio: 'inherit'
}
);
const spwanData: any[] = [],
errData: any[] = [];
node_exec.stdout.on("data", (e) => {
binaryExec.stdout.on("data", (e) => {
spwanData.push(e);
// console.log(e.toString())
});
node_exec.stderr.on("data", (e) => {
binaryExec.stderr.on("data", (e) => {
errData.push(e);
// console.log(e.toString())
});
return new Promise((resolve, reject) => {
node_exec.on("close", (n) => {
binaryExec.on("close", (n) => {
// console.log("node n: ", n);
outputPath && require('fs').writeFileSync(`${outputPath}/linux_err.js`, Buffer.concat(errData).toString())
if (0 === n) {

View File

@ -0,0 +1,95 @@
import { spawn } from "child_process";
import path from "path";
import * as fs from 'fs'
const NW_VERSION = '0.55.0'
const wcscNative = (optionsPath: string, projectPath: string, outputPath: string | undefined = undefined): Promise<string> => {
if(!fs.existsSync(projectPath))
{
throw new Error('projectPath not exists.')
}
const nodeExec = spawn(
path.resolve(__dirname, `../../../cache/nwjs-sdk-v${NW_VERSION}-linux-x64/nw`),
[ 'wcsc.js', optionsPath ],
{
cwd: projectPath,
env: {
WX_DEBUG_COMPILER_OUTPUT: outputPath,
},
// stdio: 'inherit'
}
);
const spwanData: any[] = [],
errData: any[] = [];
nodeExec.stdout.on("data", (e) => {
spwanData.push(e);
// console.log(e.toString())
});
nodeExec.stderr.on("data", (e) => {
errData.push(e);
// console.log(e.toString())
});
return new Promise((resolve, reject) => {
nodeExec.on("close", (n) => {
outputPath && require('fs').writeFileSync(`${outputPath}/linux_err.js`, Buffer.concat(errData).toString())
if (0 === n) {
let result = Buffer.concat(spwanData).toString();
// result = JSON.parse(result);
resolve(result);
} else {
// process.stderr.write(Buffer.concat(errData).toString());
// process.stderr.write(Buffer.concat(spwanData).toString());
reject(n);
}
});
});
};
const wccNative = (optionsPath: string, projectPath: string, outputPath: string | undefined = undefined): Promise<string> => {
if(!fs.existsSync(projectPath)){
throw new Error('projectPath not exists.')
}
const nodeExec = spawn(
path.resolve(__dirname, `../../../cache/nwjs-sdk-v${NW_VERSION}-linux-x64/nw`),
['wcc.js', optionsPath],
{
cwd: projectPath,
env: {
WX_DEBUG_COMPILER_OUTPUT: outputPath,
},
// stdio: 'inherit'
}
);
const spwanData: any[] = [],
errData: any[] = [];
nodeExec.stdout.on("data", (e) => {
spwanData.push(e);
// console.log(e.toString())
});
nodeExec.stderr.on("data", (e) => {
errData.push(e);
// console.log(e.toString())
});
return new Promise((resolve, reject) => {
nodeExec.on("close", (n) => {
// console.log("node n: ", n);
outputPath && require('fs').writeFileSync(`${outputPath}/linux_err.js`, Buffer.concat(errData).toString())
if (0 === n) {
let result = Buffer.concat(spwanData).toString();
// process.stdout.write(result);
// result = JSON.parse(result);
resolve(result);
} else {
process.stderr.write(Buffer.concat(errData).toString());
// process.stderr.write(Buffer.concat(spwanData).toString());
reject(n);
}
});
});
};
export default {
wcsc: wcscNative,
wcc: wccNative
}

View File

@ -0,0 +1,63 @@
import * as fs from 'fs'
import { request } from "http";
import { CompilerOptions } from './types';
// 预先启动wine focker环境再使用HTTP协议最后销毁容器
const HTTP = {
POST: (type: 'wcc' | 'wcsc', compilerOptions: CompilerOptions): Promise<string> => {
return new Promise((resolve, reject) => {
const postData = JSON.stringify(compilerOptions);
const options = {
hostname: 'localhost',
port: 8083,
path: `/${type}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
},
};
const req = request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
let ret = ""
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
ret += chunk
});
res.on('end', () => {
console.log('No more data in response.');
resolve(ret)
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
reject(e)
});
// Write data to request body
req.write(postData);
req.end();
})
}
}
const wcscNative = async (optionsPath: string) => {
const options = JSON.parse(fs.readFileSync(optionsPath).toString())
return await HTTP.POST('wcsc', options)
};
const wccNative = async (optionsPath: string) => {
const options = JSON.parse(fs.readFileSync(optionsPath).toString())
return await HTTP.POST('wcc', options)
};
export default {
wcsc: wcscNative,
wcc: wccNative
}

View File

@ -0,0 +1,16 @@
const fs = require("fs");
const compiler = require("./wcc");
const args = process.argv.slice(1);
const [type, p] = args;
const optionsData = fs.readFileSync(p).toString();
const options = JSON.parse(optionsData);
(async () => {
const result = await compiler[type](options);
if (typeof result === "string") {
process.stdout.write(result);
} else {
process.stdout.write(JSON.stringify(result));
}
})();

View File

@ -0,0 +1,4 @@
module.exports = {
wcc: require('./wcc'),
wcsc: require('./wcsc')
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,94 @@
const util = require('./util')
const path = require('path')
let wcc
function loadWccAddon() {
if (wcc) return
wcc = require('../build/Release/wcc.node')
}
const fs = util.fs
exports = async function (options) {
loadWccAddon()
if (!options) throw Error('options is required')
const lazyload = !!options.lazyloadConfig
options = Object.assign(
{
files: [],
contents: [],
replaceContent: {},
verbose: false,
debug: false,
debugWXS: false,
showNewTree: false,
isPlugin: false,
addTestAttre: false,
independent: false,
genfuncname: '$gwx',
isCut: false,
cwd: process.cwd,
debug: false,
lazyload,
lazyloadConfig: '',
},
options,
)
return new Promise(async (resolve, reject) => {
let st = Date.now()
// 获取文件内容
if (!options.contents.length) {
const tasks = options.files.map((file) => {
if (typeof options.replaceContent[file] === 'string') {
return options.replaceContent[file]
}
return fs.readFile(path.resolve(options.cwd, file), 'utf8')
})
options.contents = await Promise.all(tasks) || []
}
// console.log('wcc get files', Date.now() - st, options.contents)
let result
try {
result = wcc(options)
} catch(errmsg) {
reject(new Error(errmsg))
return
}
console.log('wcc get compile', Date.now() - st)
if (options.output) {
const output = path.resolve(options.cwd, options.output)
const dir = path.dirname(output)
if (lazyload) {
// lazyload 为 true时wcc 返回值是个对象, 需要序列化一下
result = JSON.stringify(result)
}
try {
await fs.stat(dir)
} catch (e) {
await fs.mkdir(dir, {
recursive: true,
})
}
await fs.writeFile(output, result, 'utf8')
}
console.log('wcc get output', Date.now() - st)
resolve(result)
})
}
Object.defineProperty(exports, 'version', {
get() {
loadWccAddon()
return wcc.version
},
})
module.exports = exports

View File

@ -0,0 +1,92 @@
const util = require('./util')
const path = require('path')
const fs = util.fs
let wcsc
function loadWcscAddon() {
if (wcsc) return
wcsc = require('../build/Release/wcsc.node')
}
function tranWcscResultToObject(resultStr) {
const resultArr = resultStr.split('=')
const result = {}
for (let i = 0, len = resultArr.length; i < len && resultArr[i + 1]; i += 2) {
result[resultArr[i]] = resultArr[i + 1]
}
return result
}
exports = async function (options) {
loadWcscAddon()
if (!options) throw Error('options is required')
// avoid undefined or null
if (typeof options.subPackage !== 'string') {
delete options.subPackage
}
if (typeof options.lazyload !== 'boolean') {
delete options.lazyload
}
options = Object.assign(
{
files: [],
contents: [],
pageCount: 0,
cwd: process.cwd,
replaceContent: {},
debug: false,
classPrefix: '',
lazyload: false,
},
options,
)
if (!options.contents.length) {
const tasks = options.files.map((file) => {
if (typeof options.replaceContent[file] === 'string') {
return options.replaceContent[file]
}
return fs.readFile(path.resolve(options.cwd, file), 'utf8')
})
options.contents = await Promise.all(tasks) || []
}
let wccResult
try {
wccResult = wcsc(options)
} catch (errmsg) {
throw new Error(errmsg)
}
const result = options.lazyload ? wccResult : tranWcscResultToObject(wccResult)
if (options.output) {
const output = path.resolve(options.cwd, options.output)
const dir = path.dirname(output)
try {
await fs.stat(dir)
} catch (e) {
await fs.mkdir(dir, {
recursive: true,
})
}
await fs.writeFile(output, JSON.stringify(result, null, 2), 'utf8')
}
return result
}
Object.defineProperty(exports, 'version', {
get() {
loadWcscAddon()
return wcsc.version
},
})
module.exports = exports

View File

@ -0,0 +1,18 @@
{
"name": "miniprogram-wcc",
"version": "0.0.1",
"description": "WCC node C++ addon",
"main": "lib/index.js",
"scripts": {
"rebuild": "node-gyp rebuild",
"build": "node-gyp build",
"test": "node ./test/wcc/index && node ./test/wcsc/index",
"format": "prettier *.js test/*.js scripts/*.js --write"
},
"author": "coverguo",
"license": "MIT",
"devDependencies": {
"licia": "^1.21.2",
"node-gyp": "^7.0.0"
}
}

12
test/runner/types.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
export interface CompilerOptions {
files: string[]
debugWXS: boolean
debug: boolean
genfuncname: string
isCut: boolean
wxmlCompileConfig: string
wxmlCompileConfigSplit: string
replaceContent: Record<string, string>
cwd: string
lazyloadConfig: string
}

View File

@ -1,8 +1,8 @@
import assert from 'assert';
import path from 'path';
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
describe("wcc - empty", function () {

View File

@ -1,7 +1,7 @@
import assert from "assert"
import path from "path"
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
describe("wcc - lla", function () {

View File

@ -1,8 +1,8 @@
import assert from 'assert';
import path from 'path';
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
describe("wcc - llw", function () {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,46 @@
import assert from 'assert';
import path from 'path';
import linux from '../../../runner/module-linux'
import windows from '../../../runner/module-windows'
import * as fs from 'fs'
import { execFileSync, execSync } from 'child_process';
describe("wcc - module", function () {
this.beforeAll(() => {
// TODO: 启动docker wine容器
execFileSync(path.resolve(__dirname, './nwjs-download.sh'))
const rootDir = path.resolve(__dirname, '../../../')
const cmd = `docker run -it --volume=${rootDir}:/workspace --env=USE_XVFB=yes --env=XVFB_SERVER=:95 --env=XVFB_SCREEN=0 --env=XVFB_RESOLUTION=320x240x8 --env=DISPLAY=:95 --rm --hostname=DESKTOP-1TV4OAG --name=wine --shm-size=1g --workdir=/home/wineuser --env=TZ=Asia/Shanghai --volume=winehome:/home/wineuser -p 8083:8083 scottyhardy/docker-wine:latest wine /workspace/nwjs-sdk-v0.55.0-win-x64/nw.exe`
execSync(cmd)
})
describe("llw: linux output should deep equal with wine", function () {
// afterEach(function(){
// if(this.currentTest.state === 'failed'){
// console.error('failed', this.currentTest)
// }
// })
it("初次加载1", async function () {
const p = path.resolve(__dirname, './data/options-1719836862880.json')
const storagePath = path.resolve(
__dirname,
`miniprogram-demo/${this.test?.title}`
);
try {
fs.mkdirSync(storagePath, { recursive: true });
} catch (error) {}
const n = JSON.parse(await linux.wcc(p, ''));
const w = JSON.parse(await windows.wcc(p));
fs.writeFileSync(
`${storagePath}/wine-output.json`,
JSON.stringify(w, null, 4)
);
fs.writeFileSync(
`${storagePath}/node-output.json`,
JSON.stringify(n, null, 4)
);
assert.deepEqual(w, n);
});
});
});

View File

@ -0,0 +1,16 @@
#! /bin/bash
set -e
root_dir=$(cd `dirname $0`/../../../.. && pwd -P)
nw_version="0.55.0"
if [ ! -f "$root_dir/cache/nwjs-sdk-v$nw_version-win-x64.zip" ];then
wget -c -O "$root_dir/cache/nwjs-sdk-v$nw_version-win-x64.zip.tmp" "https://dl.nwjs.io/v0.55.0/nwjs-v0.55.0-win-x64.zip"
mv "$root_dir/cache/nwjs-sdk-v$nw_version-win-x64.zip.tmp" "$root_dir/cache/nwjs-sdk-v$nw_version-win-x64.zip"
fi
if [ ! -d "$root_dir/cache/nwjs-sdk-v$nw_version-win-x64" ];then
cd "$root_dir/cache"
unzip "nwjs-sdk-v$nw_version-win-x64.zip"
fi

View File

@ -1,8 +1,8 @@
import assert from 'assert';
import path from 'path';
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
describe("wcc - raw", function () {

View File

@ -1,8 +1,8 @@
import assert from 'assert';
import path from 'path';
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
import { resolve } from 'path'

View File

@ -1,8 +1,8 @@
import assert from 'assert';
import path from 'path';
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
describe("wcsc - empty", function () {

View File

@ -1,7 +1,7 @@
import assert from "assert";
import path from "path";
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
describe("wcsc", function () {

View File

@ -1,7 +1,7 @@
import assert from "assert";
import path from "path";
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
describe("wcsc", function () {

View File

@ -1,7 +1,7 @@
import assert from "assert";
import path from "path";
import linux from '../../../runner/linux'
import windows from '../../../runner/windows'
import linux from '../../../runner/binary-linux'
import windows from '../../../runner/binary-windows'
import * as fs from 'fs'
import { resolve } from 'path'