microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/add-python-test-case-duration

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/asset-emitter/test/host.ts

67lines · modecode

1import { resolvePath } from "@typespec/compiler";
2import { createTester, mockFile } from "@typespec/compiler/testing";
3import { expect, type MockInstance, vi } from "vitest";
4import { createAssetEmitter, TypeEmitter } from "../src/index.js";
5
6const Tester = createTester(resolvePath(import.meta.dirname, ".."), {
7 libraries: [],
8});
9
10export async function getHostForTypeSpecFile(contents: string, decorators?: Record<string, any>) {
11 let tester = Tester;
12 if (decorators) {
13 tester = tester.files({ "dec.js": mockFile.js(decorators) });
14 contents = `import "./dec.js";\n` + contents;
15 }
16 const [result] = await tester.compileAndDiagnose(contents, {
17 compilerOptions: { outputDir: "tsp-output" },
18 });
19 return { program: result.program, compilerHost: result.fs.compilerHost };
20}
21
22export async function emitTypeSpec(
23 Emitter: typeof TypeEmitter<any>,
24 code: string,
25 callCounts: Partial<Record<keyof TypeEmitter<any>, number>> = {},
26 validateCallCounts = true,
27) {
28 const host = await getHostForTypeSpecFile(code);
29 const emitter = createAssetEmitter(host.program, Emitter, {
30 emitterOutputDir: "tsp-output",
31 options: {},
32 } as any);
33 const spies = emitterSpies(Emitter);
34 emitter.emitProgram();
35 await emitter.writeOutput();
36 if (validateCallCounts) {
37 assertSpiesCalled(spies, callCounts);
38 }
39 return emitter;
40}
41
42type EmitterSpies = Record<string, MockInstance<any>>;
43function emitterSpies(emitter: typeof TypeEmitter<any, any>) {
44 const spies: EmitterSpies = {};
45 const methods = Object.getOwnPropertyNames(emitter.prototype);
46 for (const key of methods) {
47 if (key === "constructor") continue;
48 if ((emitter.prototype as any)[key].restore) {
49 // assume this whole thing is already spied.
50 return spies;
51 }
52 if (typeof (emitter.prototype as any)[key] !== "function") continue;
53 spies[key] = vi.spyOn(emitter.prototype, key as any);
54 }
55
56 return spies;
57}
58
59function assertSpiesCalled(
60 spies: EmitterSpies,
61 callCounts: Partial<Record<keyof TypeEmitter<any>, number>>,
62) {
63 for (const [key, spy] of Object.entries(spies)) {
64 const expectedCount = (callCounts as any)[key] ?? 1;
65 expect(spy).toHaveBeenCalledTimes(expectedCount);
66 }
67}
68