]> git.lizzy.rs Git - rust.git/blob - editors/code/tests/unit/index.ts
Merge #10903
[rust.git] / editors / code / tests / unit / index.ts
1 import * as path from 'path';
2
3 class Test {
4     readonly name: string;
5     readonly promise: Promise<void>;
6
7     constructor(name: string, promise: Promise<void>) {
8         this.name = name;
9         this.promise = promise;
10     }
11 }
12
13 class Suite {
14     tests: Test[];
15
16     constructor() {
17         this.tests = [];
18     }
19
20     public addTest(name: string, f: () => Promise<void>): void {
21         const test = new Test(name, f());
22         this.tests.push(test);
23     }
24
25     public async run(): Promise<void> {
26         let failed = 0;
27         for (const test of this.tests) {
28             try {
29                 await test.promise;
30                 ok(`  ✔ ${test.name}`);
31             } catch (e) {
32                 error(`  ✖︎ ${test.name}\n  ${e.stack}`);
33                 failed += 1;
34             }
35         }
36         if (failed) {
37             const plural = failed > 1 ? "s" : "";
38             throw new Error(`${failed} failed test${plural}`);
39         }
40     }
41 }
42
43 export class Context {
44     public async suite(name: string, f: (ctx: Suite) => void): Promise<void> {
45         const ctx = new Suite();
46         f(ctx);
47         try {
48             ok(`⌛︎ ${name}`);
49             await ctx.run();
50             ok(`✔ ${name}`);
51         } catch (e) {
52             error(`✖︎ ${name}\n  ${e.stack}`);
53             throw e;
54         }
55     }
56 }
57
58 export async function run(): Promise<void> {
59     const context = new Context();
60     const testFiles = ["launch_config.test.js", "runnable_env.test.js"];
61     for (const testFile of testFiles) {
62         try {
63             const testModule = require(path.resolve(__dirname, testFile));
64             await testModule.getTests(context);
65         } catch (e) {
66             error(`${e}`);
67             throw e;
68         }
69     }
70 }
71
72 function ok(message: string): void {
73     // eslint-disable-next-line no-console
74     console.log(`\x1b[32m${message}\x1b[0m`);
75 }
76
77 function error(message: string): void {
78     // eslint-disable-next-line no-console
79     console.error(`\x1b[31m${message}\x1b[0m`);
80 }