Skip to content

Commit 73fdb25

Browse files
committed
✨ feat: test output is more beautiful and comes with colors
1 parent 8fc8d51 commit 73fdb25

File tree

12 files changed

+71
-112
lines changed

12 files changed

+71
-112
lines changed

biome.json

Lines changed: 0 additions & 43 deletions
This file was deleted.

bun.lockb

-3.42 KB
Binary file not shown.

generated/cookbook.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"cookbook":{"foo":{"params":"{ sad: string }","cases":[{"name":"Basic","handler":"\t\t\tconst { stream, getResult } = await test.executeStream({\n\t\t\t\tparams: { sad: 'UWU' }\n\t\t\t})\n\t\t\tconst xxx = getResult()\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tconsole.log('foo', chunk);\n\t\t\t}"}]},"test":{"title":"test","desc":"\ntest","params":"Params","cases":[{"name":"Basic","handler":"\t\t\tconst result = await test.execute({ params: { foo: '123' } });\n\t\t\tif (!result.success) return test.reject(`The result was not success`);\n\t\t\tconsole.log(result);"}]},"cookbook":{"params":"string & typia.tags.MinLength<3> & typia.tags.MaxLength<16>","cases":[]}},"readme":"# 你好世界\n\nHello world\n\n```sh\n世界你好 # enenen\n```\n\n","indexes":{"(root)":["foo","test","cookbook"]},"folderIndexes":{"(root)":[]},"generatedAt":"t!Date:2024-06-02T13:34:58.298Z"}
1+
{"cookbook":{"foo":{"params":"{ sad: string }","cases":[{"name":"Basic","handler":"\t\t\tconst { stream, getResult } = await test.executeStream({\n\t\t\t\tparams: { sad: 'UWU' }\n\t\t\t})\n\t\t\tconst xxx = getResult()\n\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tconsole.log('foo', chunk);\n\t\t\t}"}]},"test":{"title":"test","desc":"\ntest","params":"Params","cases":[{"name":"Basic","handler":"\t\t\tconst result = await test.execute({ params: { foo: '123' } });\n\t\t\tif (!result.success) return test.reject(`The result was not success`);\n\t\t\tconsole.log(result);"},{"name":"Basic","handler":"\t\t\tconst result = await test.execute({ params: { foo: '123' } });\n\t\t\tif (!result.success) return test.reject(`The result was not success`);\n\t\t\tconsole.log(result);"},{"name":"Basic","handler":"\t\t\tconst result = await test.execute({ params: { foo: '123' } });\n\t\t\tif (!result.success) return test.reject(`The result was not success`);\n\t\t\tconsole.log(result);"},{"name":"Basic","handler":"\t\t\tconst result = await test.execute({ params: { foo: '123' } });\n\t\t\tif (!result.success) return test.reject(`The result was not success`);\n\t\t\tconsole.log(result);"},{"name":"Basic","handler":"\t\t\tconst result = await test.execute({ params: { foo: '123' } });\n\t\t\tif (!result.success) return test.reject(`The result was not success`);\n\t\t\tconsole.log(result);"}]},"cookbook":{"params":"string & typia.tags.MinLength<3> & typia.tags.MaxLength<16>","cases":[]}},"readme":"# 你好世界\n\nHello world\n\n```sh\n世界你好 # enenen\n```\n\n","indexes":{"(root)":["foo","test","cookbook"]},"folderIndexes":{"(root)":[]},"generatedAt":"t!Date:2024-06-03T10:01:07.393Z"}

generated/products/api-validator.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* ⚠️This file is generated and modifications will be overwritten
33
*/
44
export default {
5-
generatedAt: 1717335297357,
5+
generatedAt: 1717408866126,
66
validate: {
77
'foo': () => import('./apps/foo.ts'),
88
'test': () => import('./apps/test.ts'),

generated/raw/api-validator.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
*/
44

55
export default {
6-
generatedAt: 1717335297357,
6+
generatedAt: 1717408866126,
77
validate: {
88
'foo': () => import('./apps/foo.ts'),
99
'test': () => import('./apps/test.ts'),

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
"typia": "^6.0.3"
3636
},
3737
"devDependencies": {
38-
"@biomejs/biome": "1.7.3",
3938
"@types/bun": "latest",
4039
"drizzle-kit": "^0.20.14",
4140
"typescript": "^5.4.0",

packages/milkio/api-test/index.ts

Lines changed: 52 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import schema from "../../../generated/api-schema";
2-
import { useLogger, type MilkioApp } from "..";
2+
import { ExecuteResultFail, type MilkioApp } from "..";
3+
import { cwd } from "node:process";
4+
import chalk from "chalk";
5+
import { handleCatchError } from "../utils/handle-catch-error.ts";
36

47
export const executeApiTests = async <Path extends Array<keyof (typeof schema)["apiTestsSchema"]>>(app: MilkioApp, path: Path | string | true | 1 | undefined) => {
5-
console.log(`🥛 Milkio Api Testing..\n`);
8+
console.log(`${chalk.hex("#81C7D4")(`🧊 test running on`)} ${chalk.hex("#999A9E").underline(cwd())}`);
69

710
let pathArr = [] as Array<string>;
811
if (!path || path === "1" || path === 1 || path === true) {
@@ -11,61 +14,63 @@ export const executeApiTests = async <Path extends Array<keyof (typeof schema)["
1114
pathArr = [path] as Path;
1215
}
1316

14-
const tests = [];
1517
const startedAt = new Date().getTime();
16-
1718
const apiTestHooks = await import("../../../src/api-test.ts");
1819
await apiTestHooks.default.onBootstrap();
20+
const results: Array<{ path: string, case: number, fail: boolean, failMessage?: string }> = [];
21+
console.log(chalk.hex("#0B346E")(`₋₋₋₋₋₋₋₋`));
1922

2023
for (const pathRaw of pathArr) {
2124
let path = pathRaw.replaceAll("\\", "/");
2225
if (path.startsWith("/")) path = path.slice(1) as Path[number];
2326

24-
tests.push(
25-
// @ts-ignore
26-
(async () => {
27-
// @ts-ignore
28-
const module = await schema.apiTestsSchema[path]().module;
29-
const cases = module.test.getCases();
30-
let i = 0;
31-
for (const cs of cases) {
32-
++i;
33-
const csStartedAt = new Date().getTime();
34-
const clear = setTimeout(() => {
35-
console.error(`------`);
36-
console.error(`❌ TIMEOUT -- More than ${cs.timeout ?? 8192}ms`);
37-
console.error(` ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i}`);
38-
console.error(`------`);
39-
throw new Error("");
40-
}, cs.timeout ?? 8192);
41-
await cs.handler({
42-
...((await apiTestHooks.default.onBefore()) ?? {}),
43-
log: (...args: Array<unknown>) => console.log(...args),
44-
// @ts-ignore
45-
execute: async (options?: any) => app.execute((path as any), options),
46-
executeOther: async (path: any, options?: any) => app.execute((path as any), options),
47-
executeStream: async (options?: any) => app.executeStream((path as any), options),
48-
randParams: () => app.randParams(path as any),
49-
randOtherParams: (path: any) => app.randParams(path),
50-
reject: (message?: string) => {
51-
console.error(`------`);
52-
console.error(`❌ REJECT -- ${message ?? "Test not satisfied"}`);
53-
console.error(` ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i} | Time: ${new Date().getTime() - csStartedAt}ms`);
54-
console.error(`------`);
55-
throw new Error("");
56-
},
57-
} as any);
58-
clearTimeout(clear);
59-
console.log(`✅ DIRECT -- ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i} | Time: ${new Date().getTime() - csStartedAt}ms`);
60-
}
61-
})(),
62-
);
27+
// @ts-ignore
28+
const module = await schema.apiTestsSchema[path]().module;
29+
const cases = module.test.getCases();
30+
let i = 0;
31+
for (const cs of cases) {
32+
++i;
33+
const csStartedAt = new Date().getTime();
34+
let fail = false;
35+
let failMessage: string | undefined = undefined;
36+
try {
37+
await cs.handler({
38+
...((await apiTestHooks.default.onBefore()) ?? {}),
39+
log: (...args: Array<unknown>) => console.log(...args),
40+
// @ts-ignore
41+
execute: async (options?: any) => app.execute((path as any), options),
42+
executeOther: async (path: any, options?: any) => app.execute((path as any), options),
43+
executeStream: async (options?: any) => app.executeStream((path as any), options),
44+
randParams: () => app.randParams(path as any),
45+
randOtherParams: (path: any) => app.randParams(path),
46+
reject: (message?: string) => {
47+
fail = true;
48+
failMessage = message;
49+
},
50+
});
51+
} catch (e: any) {
52+
const response = handleCatchError(e, 'no-execute-id') as ExecuteResultFail;
53+
fail = true;
54+
failMessage = response.fail.message;
55+
}
56+
if (fail) {
57+
console.log(`${chalk.hex("#D75455")(`\nrejected`)}${chalk.hex("#999A9E")(` · ${cs.name} | path: src/apps/${path as string}.ts | case: ${i} | time: ${new Date().getTime() - csStartedAt}ms`)}`);
58+
console.log(chalk.hex("#999A9E")(failMessage ?? "Test not satisfied"));
59+
} else {
60+
console.log(`${chalk.hex("#1B813E")(`directed`)}${chalk.hex("#999A9E")(` · ${cs.name} | path: src/apps/${path as string}.ts | case: ${i} | time: ${new Date().getTime() - csStartedAt}ms`)}`);
61+
}
62+
results.push({ path, case: i, fail, failMessage });
63+
console.log(chalk.hex("#0B346E")(`₋₋₋₋₋₋₋₋`));
64+
await new Promise(resolve => setTimeout(resolve, 64));
65+
}
6366
}
6467

65-
await Promise.all(tests);
66-
6768
const endedAt = new Date().getTime();
6869

69-
console.log(`\n✅ All tests passed.`);
70-
console.log(`🥛 Milkio Api Testing took ${((endedAt - startedAt) / 1000).toFixed(2)}s\n`);
70+
const failTotal = results.filter(r => r.fail).length;
71+
const passTotal = results.length - failTotal;
72+
73+
console.log("");
74+
if (failTotal === 0) console.log(chalk.hex("#1B813E")(`🥳 all tests ${chalk.hex("#1B813E")(`passed`)} ${chalk.hex("#999A9E")(`🌟 milkio testing took ${((endedAt - startedAt) / 1000).toFixed(2)}s\n`)}`));
75+
else console.log(chalk.hex("#999A9E")(`🤗️️ ${failTotal} test${failTotal > 1 ? "s" : ""} ${chalk.hex("#D75455")(`failed`)}${passTotal > 0 ? `, and ${results.length - failTotal} ${chalk.hex("#1B813E")(`passed`)}` : ''} ${chalk.hex("#999A9E")(`🌟 milkio testing took ${((endedAt - startedAt) / 1000).toFixed(2)}s`)}`));
7176
};

packages/milkio/c.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env bun
22

33
import { argv, exit } from "node:process";
4-
import { $ } from "bun";
4+
import { $, env } from "bun";
55

66
const method = argv[2] as keyof typeof commands;
77
const params = argv.slice(3) as Parameters<(typeof commands)[keyof typeof commands]>;
@@ -26,14 +26,14 @@ const commands = {
2626
async EAR(commandBase64ed: string) {
2727
try {
2828
console.clear();
29-
} catch (e) {}
29+
} catch (e) { }
3030
const command = Buffer.from(commandBase64ed, "base64").toString("utf-8");
3131
console.log("\x1B[2m%s\x1B[0m", `$ ${command}`);
3232
console.log(``);
3333
try {
34-
await $`${{ raw: command }}`;
35-
} catch (e) {}
36-
process.on("SIGINT", () => {}); // prevent users from exiting by pressing ctrl + c
34+
await $`${{ raw: command }}`.env({ ...env, FORCE_COLOR: "3" });
35+
} catch (e) { }
36+
process.on("SIGINT", () => { }); // prevent users from exiting by pressing ctrl + c
3737
while (true) await new Promise((resolve) => process.stdin.on("keypress", resolve));
3838
},
3939
};

packages/milkio/defines/define-http-handler.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -148,13 +148,6 @@ export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOpti
148148

149149
const resultsRaw = await app._call(mode, pathstr, params, headers, { executeId, logger, detail });
150150

151-
if (resultsRaw.$result.success === false) {
152-
if (resultsRaw.$result.fail.code === "TYPE_SAFE_ERROR") {
153-
if (((resultsRaw.$result.fail.data as any).value) === undefined) (resultsRaw.$result.fail.data as any).value === "undefined";
154-
if (((resultsRaw.$result.fail.data as any).value) === null) (resultsRaw.$result.fail.data as any).value === "null";
155-
}
156-
}
157-
158151
let fn: any;
159152
try {
160153
fn = await schema.apiValidator.validate[pathstr]();

packages/milkio/kernel/validate.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ export function _validate(validator: IValidation.IFailure | IValidation.ISuccess
55
if (validator.success) return validator.data;
66
const error = validator.errors[0];
77

8+
if ((error.value) === undefined) error.value === "undefined";
9+
if ((error.value) === null) error.value === "null";
10+
811
throw reject("TYPE_SAFE_ERROR", {
912
path: error.path,
1013
expected: error.expected,

0 commit comments

Comments
 (0)