microsoft/typespec
Publicmirrored from https://github.com/microsoft/typespecAvailable
packages/compiler/testing/test-utils.ts
54lines · modecode
| 1 | import { Diagnostic, Program, Type } from "../core/index.js"; |
| 2 | import { CompilerOptions } from "../core/options.js"; |
| 3 | import { TestHost } from "./types.js"; |
| 4 | |
| 5 | export interface BasicTestRunner { |
| 6 | readonly program: Program; |
| 7 | readonly fs: Map<string, string>; |
| 8 | |
| 9 | /** |
| 10 | * Compile the given code and assert no diagnostics are present. |
| 11 | */ |
| 12 | compile(code: string, options?: CompilerOptions): Promise<Record<string, Type>>; |
| 13 | |
| 14 | /** |
| 15 | * Compile the code and return the list of diagnostics. |
| 16 | */ |
| 17 | diagnose(code: string, options?: CompilerOptions): Promise<readonly Diagnostic[]>; |
| 18 | |
| 19 | /** |
| 20 | * Compile the code and return the test types as well as the list of diagnostics. |
| 21 | */ |
| 22 | compileAndDiagnose( |
| 23 | code: string, |
| 24 | options?: CompilerOptions |
| 25 | ): Promise<[Record<string, Type>, readonly Diagnostic[]]>; |
| 26 | } |
| 27 | |
| 28 | export function createTestWrapper( |
| 29 | host: TestHost, |
| 30 | wrapper: (code: string) => string, |
| 31 | defaultCompilerOptions?: CompilerOptions |
| 32 | ): BasicTestRunner { |
| 33 | defaultCompilerOptions ??= {}; |
| 34 | return { |
| 35 | get program() { |
| 36 | return host.program; |
| 37 | }, |
| 38 | |
| 39 | fs: host.fs, |
| 40 | |
| 41 | compile: (code: string, options?: CompilerOptions) => { |
| 42 | host.addCadlFile("./main.cadl", wrapper(code)); |
| 43 | return host.compile("./main.cadl", { ...defaultCompilerOptions, ...options }); |
| 44 | }, |
| 45 | diagnose: (code: string, options?: CompilerOptions) => { |
| 46 | host.addCadlFile("./main.cadl", wrapper(code)); |
| 47 | return host.diagnose("./main.cadl", { ...defaultCompilerOptions, ...options }); |
| 48 | }, |
| 49 | compileAndDiagnose: (code: string, options?: CompilerOptions) => { |
| 50 | host.addCadlFile("./main.cadl", wrapper(code)); |
| 51 | return host.compileAndDiagnose("./main.cadl", { ...defaultCompilerOptions, ...options }); |
| 52 | }, |
| 53 | }; |
| 54 | } |