Skip to content

Commit

Permalink
test: 新增单元测试
Browse files Browse the repository at this point in the history
  • Loading branch information
baranwang committed Oct 25, 2024
1 parent ef09c0e commit 0012a9c
Show file tree
Hide file tree
Showing 16 changed files with 346 additions and 34 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"build": "cross-env NX_DAEMON=false nx run-many -t build --exclude @examples/* @e2e/* --parallel=10",
"mk:dev": "nx run-many -t dev --projects=@iringo/utils,@iringo/modkit* --parallel=10",
"mk:build": "nx run-many -t build --projects=@iringo/utils,@iringo/modkit* --parallel=10",
"mk:test": "nx run-many -t test --projects=@iringo/utils,@iringo/modkit* --parallel=10",
"change": "changeset"
},
"author": "",
Expand Down
4 changes: 4 additions & 0 deletions packages/modkit/plugins/boxjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@
"devDependencies": {
"@iringo/modkit-config": "workspace:^",
"@modern-js/module-tools": "^2.60.2",
"@test/modkit": "workspace:^",
"@types/jest": "^29.5.13",
"@types/node": "^20.0.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.2"
},
"repository": {
Expand Down
4 changes: 4 additions & 0 deletions packages/modkit/plugins/dts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
"devDependencies": {
"@iringo/modkit-config": "workspace:^",
"@modern-js/module-tools": "^2.60.2",
"@test/modkit": "workspace:^",
"@types/jest": "^29.5.13",
"@types/node": "^20.0.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.2"
},
"repository": {
Expand Down
4 changes: 4 additions & 0 deletions packages/modkit/plugins/loon/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@
"devDependencies": {
"@iringo/modkit-config": "workspace:^",
"@modern-js/module-tools": "^2.60.2",
"@test/modkit": "workspace:^",
"@types/jest": "^29.5.13",
"@types/node": "^20.0.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.2"
},
"repository": {
Expand Down
4 changes: 4 additions & 0 deletions packages/modkit/plugins/quantumultx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@
"devDependencies": {
"@iringo/modkit-config": "workspace:^",
"@modern-js/module-tools": "^2.60.2",
"@test/modkit": "workspace:^",
"@types/jest": "^29.5.13",
"@types/node": "^20.0.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.2"
},
"repository": {
Expand Down
4 changes: 4 additions & 0 deletions packages/modkit/plugins/stash/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
"devDependencies": {
"@iringo/modkit-config": "workspace:^",
"@modern-js/module-tools": "^2.60.2",
"@test/modkit": "workspace:^",
"@types/jest": "^29.5.13",
"@types/node": "^20.0.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.2"
},
"repository": {
Expand Down
7 changes: 7 additions & 0 deletions packages/modkit/plugins/surge/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** @type {import('ts-jest').JestConfigWithTsJest} **/
module.exports = {
testEnvironment: 'node',
transform: {
'^.+.tsx?$': ['ts-jest', {}],
},
};
7 changes: 6 additions & 1 deletion packages/modkit/plugins/surge/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"types": "dist/index.d.ts",
"scripts": {
"dev": "modern build -w",
"build": "modern build"
"build": "modern build",
"test": "jest"
},
"files": ["dist", "types", "CHANGELOG.md"],
"dependencies": {
Expand All @@ -17,8 +18,12 @@
"devDependencies": {
"@iringo/modkit-config": "workspace:^",
"@modern-js/module-tools": "^2.60.2",
"@test/modkit": "workspace:^",
"@types/jest": "^29.5.13",
"@types/node": "^20.0.0",
"@types/qrcode-terminal": "^0.12.2",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.2"
},
"repository": {
Expand Down
68 changes: 40 additions & 28 deletions packages/modkit/plugins/surge/src/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import { Template, logger, objectEntries, toKebabCase } from '@iringo/modkit-sha

export class SurgeTemplate extends Template {
get Metadata() {
const { name, description, system, ...rest } = this.metadata;
const { name, description, system, version, extra = {} } = this.metadata;
const { argumentsText, argumentsDescription } = this.#handleArguments();
const result: Record<string, string | number | boolean | undefined> = {};
const result: Record<string, any> = {};
result.name = name;
result.desc = description;
result.version = version;
if (system) {
result.requirement = system?.map((item) => `SYSTEM = ${item}`).join(' || ');
}
Expand All @@ -16,7 +17,7 @@ export class SurgeTemplate extends Template {
if (argumentsDescription) {
result['arguments-desc'] = argumentsDescription;
}
Object.entries(rest).forEach(([key, value]) => {
objectEntries(extra).forEach(([key, value]) => {
result[key] = Array.isArray(value) ? value.join(', ') : value;
});
return this.renderKeyValuePairs(result, { prefix: '#!' });
Expand Down Expand Up @@ -65,19 +66,23 @@ export class SurgeTemplate extends Template {
get Script() {
const scripts: string[] = [];
const { scriptParams } = this.#handleArguments();
this.content.script.forEach((script, index) => {
const parameters: Record<string, string | number | boolean | undefined> = {};
const { name, scriptKey, debug, ...rest } = script;
this.content.script?.forEach((script, index) => {
const parameters: Record<string, any> = {};
const { name, scriptKey, debug, injectArgument, argument, extra, ...rest } = script;
parameters['script-path'] = this.utils.getScriptPath(scriptKey);
objectEntries(rest).forEach(([key, value]) => {
parameters[toKebabCase(key)] = value;

objectEntries({ ...rest, ...extra }).forEach(([key, value]) => {
if (value !== undefined) {
parameters[toKebabCase(key as string)] = value.toString();
}
});
if (injectArgument || argument) {
parameters.argument = argument || scriptParams;
}

if (debug || process.env.NODE_ENV === 'development') {
parameters.debug = true;
}
if (script.injectArgument || script.argument) {
parameters.argument = script.argument || scriptParams;
}
scripts.push(
`${name || `script${index}`} = ${this.renderKeyValuePairs(parameters, { join: ', ', separator: '=' })}`,
);
Expand All @@ -91,10 +96,10 @@ export class SurgeTemplate extends Template {
}
let result = '';
if (this.content.mitm.hostname?.length) {
result += `hostname = %APPEND% ${this.content.mitm.hostname.join(', ')}\n`;
result += `hostname = %APPEND% ${this.content.mitm.hostname.join(', ')}\n`;
}
if (this.content.mitm.clientSourceAddress?.length) {
result += `client-source-address = %APPEND% ${this.content.mitm.clientSourceAddress.join(', ')}\n`;
result += `client-source-address = %APPEND% ${this.content.mitm.clientSourceAddress.join(', ')}\n`;
}
return result.trim();
}
Expand All @@ -118,20 +123,27 @@ export class SurgeTemplate extends Template {
case 'header-add':
case 'header-del':
case 'header-replace-regex': {
const options = [];
options.push(rewrite.type);
options.push(rewrite.pattern);
options.push(rewrite.mode);
options.push(rewrite.content);
headerRewrites.push(options.join(' '));
if (typeof rewrite.content === 'string') {
headerRewrites.push([rewrite.type, rewrite.pattern, rewrite.mode, rewrite.content].join(' '));
break;
}
Object.entries(rewrite.content).forEach(([key, value]) => {
headerRewrites.push([rewrite.type, rewrite.pattern, rewrite.mode, key, value].join(' '));
});
break;
}
default: {
const options = [];
options.push(rewrite.type);
options.push(rewrite.pattern);
options.push(rewrite.content);
bodyRewrites.push(options.join(' '));
if (typeof rewrite.content === 'string') {
headerRewrites.push([rewrite.type, rewrite.pattern, rewrite.content].join(' '));
break;
}
bodyRewrites.push(
[
rewrite.type,
rewrite.pattern,
...Object.entries(rewrite.content).map(([key, value]) => [key, value].join(' ')),
].join(' '),
);
break;
}
}
Expand Down Expand Up @@ -164,23 +176,23 @@ export class SurgeTemplate extends Template {
options.push(`data-type=${mock.dataType}`);
}
if (typeof mock.data === 'string') {
options.push(`data=${this.utils.getFilePath(mock.data) || mock.data}`);
options.push(`data="${this.utils.getFilePath(mock.data) || mock.data}"`);
} else if (!!mock.data && 'content' in mock.data) {
options.push(`data=${mock.data.content}`);
options.push(`data="${mock.data.content}"`);
}
if (mock.statusCode) {
options.push(`status-code=${mock.statusCode}`);
}
if (mock.headers) {
switch (typeof mock.headers) {
case 'string':
options.push(`header=${mock.headers}`);
options.push(`header="${mock.headers}"`);
break;
case 'object': {
const header = Object.entries(mock.headers)
.map((value) => value.join(':'))
.join('|');
options.push(`header=${header}`);
options.push(`header="${header}"`);
break;
}
default:
Expand Down
53 changes: 53 additions & 0 deletions packages/modkit/plugins/surge/tests/template.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { testParams } from '@test/modkit/common-test-config';
import { SurgeTemplate } from '../src/template';

describe('SurgeTemplate', () => {
const surgeTemplate = new SurgeTemplate(testParams);

it('metadata', () => {
expect(surgeTemplate.Metadata).toContain('#!desc = This is a source config\\nand this is a new line');
expect(surgeTemplate.Metadata).toContain('#!category = modkit');
});

it('script', () => {
expect(surgeTemplate.Script).toContain(
'script1 = script-path=./test.js, type=http-response, pattern=^http://www.example.com/test, max-size=16384, argument=boolean={{{boolean}}}&string={{{string}}}&number={{{number}}}&array={{{array}}}',
);
expect(surgeTemplate.Script).toContain('script2 = script-path=./fired.js, type=cron, cronexp=* * * * *');
});

it('rule', () => {
expect(surgeTemplate.Rule).toContain('DOMAIN,www.apple.com,Proxy');
expect(surgeTemplate.Rule).toContain('RULE-SET, foo, REJECT // it is comment');
});

it('host', () => {
expect(surgeTemplate.Host).toContain('abc.com = 1.2.3.4');
});

it('url rewrite', () => {
expect(surgeTemplate.URLRewrite).toContain('^http://www.google.cn http://www.google.com header');
expect(surgeTemplate.URLRewrite).toContain('^http://ad.com/ad.png _ reject');
});

it('header rewrite', () => {
expect(surgeTemplate.HeaderRewrite).toContain('http-request ^http://example.com header-add DNT 1');
});

it('body rewrite', () => {
expect(surgeTemplate.BodyRewrite).toContain(
'http-response ^https?://example.com/ regex1 replacement1 regex2 replacement2',
);
});

it('mock', () => {
expect(surgeTemplate.MapLocal).toContain('^http://surgetest.com/json data-type=text data="{}" status-code=500');
expect(surgeTemplate.MapLocal).toContain(
'^http://surgetest.com/file data-type=file data="foo" header="a:b|foo:bar"',
);
});

it('mitm', () => {
expect(surgeTemplate.MITM).toContain('hostname = %APPEND% example.com');
});
});
4 changes: 4 additions & 0 deletions packages/modkit/plugins/surge/tests/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "../tsconfig.json",
"include": ["**/*.ts"]
}
6 changes: 3 additions & 3 deletions packages/modkit/shared/src/types/source/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ export interface ModuleMetadata {
* 模块名称
* @default 读取 package.json 中的 displayName
*/
name: string;
name?: string;
/**
* 模块描述
* @default 读取 package.json 中的 description
*/
description: string;
description?: string;
/**
* 版本号
* @default 默认读取 package.json 中的 version
Expand All @@ -21,5 +21,5 @@ export interface ModuleMetadata {
/**
* 额外的配置
*/
[key: string]: string | string[] | number | boolean | undefined;
extra?: Record<string, any>;
}
2 changes: 1 addition & 1 deletion packages/modkit/shared/src/types/source/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,5 @@ export interface ModuleScript {
/**
* 额外的配置
*/
[key: string]: string | number | boolean | undefined;
extra?: Record<string, any>;
}
Loading

0 comments on commit 0012a9c

Please sign in to comment.