kubernetes-fluent-client 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.prettierignore +4 -0
  2. package/README.md +24 -0
  3. package/dist/cli.js +21 -1
  4. package/dist/fileSystem.d.ts +11 -0
  5. package/dist/fileSystem.d.ts.map +1 -0
  6. package/dist/fileSystem.js +42 -0
  7. package/dist/fileSystem.test.d.ts +2 -0
  8. package/dist/fileSystem.test.d.ts.map +1 -0
  9. package/dist/fileSystem.test.js +75 -0
  10. package/dist/generate.d.ts +71 -11
  11. package/dist/generate.d.ts.map +1 -1
  12. package/dist/generate.js +130 -117
  13. package/dist/generate.test.js +293 -346
  14. package/dist/postProcessing.d.ts +246 -0
  15. package/dist/postProcessing.d.ts.map +1 -0
  16. package/dist/postProcessing.js +497 -0
  17. package/dist/postProcessing.test.d.ts +2 -0
  18. package/dist/postProcessing.test.d.ts.map +1 -0
  19. package/dist/postProcessing.test.js +550 -0
  20. package/e2e/cli.e2e.test.ts +123 -0
  21. package/e2e/crds/policyreports.default.expected/policyreport-v1alpha1.ts +332 -0
  22. package/e2e/crds/policyreports.default.expected/policyreport-v1alpha2.ts +360 -0
  23. package/e2e/crds/policyreports.default.expected/policyreport-v1beta1.ts +360 -0
  24. package/e2e/crds/policyreports.no.post.expected/policyreport-v1alpha1.ts +331 -0
  25. package/e2e/crds/policyreports.no.post.expected/policyreport-v1alpha2.ts +360 -0
  26. package/e2e/crds/policyreports.no.post.expected/policyreport-v1beta1.ts +360 -0
  27. package/e2e/crds/test.yaml/policyreports.test.yaml +1008 -0
  28. package/e2e/crds/test.yaml/uds-podmonitors.test.yaml +1245 -0
  29. package/e2e/crds/uds-podmonitors.default.expected/podmonitor-v1.ts +1333 -0
  30. package/e2e/crds/uds-podmonitors.no.post.expected/podmonitor-v1.ts +1360 -0
  31. package/package.json +6 -5
  32. package/src/cli.ts +25 -1
  33. package/src/fileSystem.test.ts +67 -0
  34. package/src/fileSystem.ts +25 -0
  35. package/src/generate.test.ts +368 -358
  36. package/src/generate.ts +173 -154
  37. package/src/postProcessing.test.ts +742 -0
  38. package/src/postProcessing.ts +568 -0
@@ -0,0 +1,550 @@
1
+ "use strict";
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // SPDX-FileCopyrightText: 2023-Present The Kubernetes Fluent Client Authors
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
19
+ });
20
+ var __importStar = (this && this.__importStar) || function (mod) {
21
+ if (mod && mod.__esModule) return mod;
22
+ var result = {};
23
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
+ __setModuleDefault(result, mod);
25
+ return result;
26
+ };
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ const postProcessingModule = __importStar(require("./postProcessing"));
29
+ const fileSystem_1 = require("./fileSystem");
30
+ const globals_1 = require("@jest/globals");
31
+ const fs = __importStar(require("fs")); // We'll mock fs
32
+ // Mock fs
33
+ globals_1.jest.mock("fs");
34
+ // Mock path.join
35
+ globals_1.jest.mock("path", () => ({
36
+ join: (...args) => args.join("/"), // Simulates path.join behavior
37
+ }));
38
+ // Mock NodeFileSystem methods
39
+ globals_1.jest.mock("./fileSystem", () => ({
40
+ NodeFileSystem: globals_1.jest.fn().mockImplementation(() => ({
41
+ readdirSync: globals_1.jest.fn(),
42
+ readFile: globals_1.jest.fn(),
43
+ writeFile: globals_1.jest.fn(),
44
+ })),
45
+ }));
46
+ globals_1.jest.mock("./types", () => ({
47
+ GenericKind: globals_1.jest.fn().mockImplementation(() => ({
48
+ kind: "MockKind",
49
+ apiVersion: "v1",
50
+ })),
51
+ }));
52
+ globals_1.jest.mock("./postProcessing", () => {
53
+ const originalModule = globals_1.jest.requireActual("./postProcessing");
54
+ return {
55
+ ...(typeof originalModule === "object" ? originalModule : {}),
56
+ processAndModifySingleFile: globals_1.jest.fn(), // Mock the specific function
57
+ mapFilesToCRD: globals_1.jest.fn(), // Mock mapFilesToCRD to avoid conflict
58
+ };
59
+ });
60
+ const mockFileSystem = new fileSystem_1.NodeFileSystem();
61
+ const mockCRDResults = [
62
+ {
63
+ name: "TestKind",
64
+ crd: {
65
+ spec: {
66
+ group: "test.group",
67
+ names: { kind: "TestKind", plural: "TestKinds" },
68
+ scope: "Namespaced",
69
+ versions: [{ name: "v1", served: true, storage: true }],
70
+ },
71
+ },
72
+ version: "v1",
73
+ },
74
+ ];
75
+ // Define the mock data
76
+ /* const mockLines = ["line1", "line2"];
77
+ const mockName = "TestKind";
78
+ const mockCRD: CustomResourceDefinition = {
79
+ spec: {
80
+ group: "test.group",
81
+ names: { kind: "TestKind", plural: "testkinds" },
82
+ scope: "Namespaced",
83
+ versions: [{ name: "v1", served: true, storage: true }],
84
+ },
85
+ };
86
+ const mockVersion = "v1"; */
87
+ const mockOpts = {
88
+ directory: "mockDir",
89
+ logFn: globals_1.jest.fn(), // Mock logging function
90
+ language: "ts",
91
+ plain: false,
92
+ npmPackage: "mockPackage",
93
+ source: "",
94
+ };
95
+ (0, globals_1.describe)("postProcessing", () => {
96
+ (0, globals_1.beforeEach)(() => {
97
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
98
+ });
99
+ (0, globals_1.afterEach)(() => {
100
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
101
+ });
102
+ (0, globals_1.test)("should log error when directory is not defined", async () => {
103
+ const optsWithoutDirectory = { ...mockOpts, directory: undefined };
104
+ await postProcessingModule.postProcessing(mockCRDResults, optsWithoutDirectory, mockFileSystem);
105
+ (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("⚠️ Error: Directory is not defined.");
106
+ });
107
+ (0, globals_1.test)("should read files from directory and process them", async () => {
108
+ const mockFileResultMap = { "TestKind-v1.ts": mockCRDResults[0] };
109
+ globals_1.jest.spyOn(mockFileSystem, "readFile").mockReturnValue("mock content");
110
+ globals_1.jest.spyOn(mockFileSystem, "writeFile");
111
+ await postProcessingModule.processFiles(["TestKind-v1.ts"], mockFileResultMap, mockOpts, mockFileSystem);
112
+ (0, globals_1.expect)(mockFileSystem.readFile).toHaveBeenCalledWith("mockDir/TestKind-v1.ts");
113
+ (0, globals_1.expect)(mockFileSystem.writeFile).toHaveBeenCalled();
114
+ });
115
+ (0, globals_1.test)("should log error when failing to read the file", async () => {
116
+ // Mock a situation where the file exists but reading it fails
117
+ const mockFileResultMap = { "TestKind-v1.ts": mockCRDResults[0] };
118
+ // Simulate readFile throwing an error
119
+ globals_1.jest.spyOn(mockFileSystem, "readFile").mockImplementation(() => {
120
+ throw new Error("File read error");
121
+ });
122
+ await postProcessingModule.processFiles(["TestKind-v1.ts"], mockFileResultMap, mockOpts, mockFileSystem);
123
+ // Verify the error log
124
+ (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("❌ Error processing file: mockDir/TestKind-v1.ts - File read error");
125
+ });
126
+ (0, globals_1.test)("should log start and completion messages", async () => {
127
+ globals_1.jest.spyOn(mockFileSystem, "readdirSync").mockReturnValue(["TestKind-v1.ts"]);
128
+ globals_1.jest
129
+ .spyOn(postProcessingModule, "mapFilesToCRD")
130
+ .mockReturnValue({ "TestKind-v1.ts": mockCRDResults[0] });
131
+ //jest.spyOn(postProcessingModule, "processFiles").mockImplementation(() => Promise.resolve());
132
+ await postProcessingModule.postProcessing(mockCRDResults, mockOpts, mockFileSystem);
133
+ // Verify the start message was logged
134
+ (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("\n🔧 Post-processing started...");
135
+ // Verify the completion message was logged
136
+ (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("🔧 Post-processing completed.\n");
137
+ });
138
+ (0, globals_1.test)("should handle readdirSync error gracefully", async () => {
139
+ // Simulate an error when reading the directory
140
+ globals_1.jest.spyOn(mockFileSystem, "readdirSync").mockImplementation(() => {
141
+ throw new Error("Directory read error");
142
+ });
143
+ await (0, globals_1.expect)(postProcessingModule.postProcessing(mockCRDResults, mockOpts, mockFileSystem)).rejects.toThrow("Directory read error");
144
+ // Ensure the process is not continued after the error
145
+ (0, globals_1.expect)(mockOpts.logFn).not.toHaveBeenCalledWith("🔧 Post-processing completed.\n");
146
+ });
147
+ });
148
+ (0, globals_1.describe)("mapFilesToCRD", () => {
149
+ (0, globals_1.beforeEach)(() => {
150
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
151
+ });
152
+ (0, globals_1.afterEach)(() => {
153
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
154
+ });
155
+ (0, globals_1.test)("should map files to corresponding CRD results", () => {
156
+ const result = postProcessingModule.mapFilesToCRD(mockCRDResults);
157
+ (0, globals_1.expect)(result).toEqual({
158
+ "TestKind-v1.ts": mockCRDResults[0],
159
+ });
160
+ });
161
+ (0, globals_1.test)("should log a warning if no matching CRD result found for a file", async () => {
162
+ const mockFiles = ["NonExistingKind.ts"];
163
+ const mockFileResultMap = {};
164
+ await postProcessingModule.processFiles(mockFiles, mockFileResultMap, mockOpts, mockFileSystem);
165
+ (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("⚠️ Warning: No matching CRD result found for file: mockDir/NonExistingKind.ts");
166
+ });
167
+ });
168
+ (0, globals_1.describe)("applyCRDPostProcessing", () => {
169
+ const mockContent = "mock content";
170
+ const mockOpts = {
171
+ directory: "mockDir",
172
+ logFn: globals_1.jest.fn(),
173
+ language: "ts",
174
+ plain: false,
175
+ npmPackage: "mockPackage",
176
+ source: "",
177
+ };
178
+ (0, globals_1.beforeEach)(() => {
179
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
180
+ });
181
+ (0, globals_1.afterEach)(() => {
182
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
183
+ });
184
+ (0, globals_1.test)("should process TypeScript file content", () => {
185
+ const result = postProcessingModule.applyCRDPostProcessing(mockContent, "TestKind", mockCRDResults[0].crd, "v1", mockOpts);
186
+ (0, globals_1.expect)(result).toContain("mock content");
187
+ // Add more assertions based on what is expected after processing
188
+ });
189
+ (0, globals_1.test)("should process TypeScript file content", () => {
190
+ const result = postProcessingModule.applyCRDPostProcessing(mockContent, "TestKind", mockCRDResults[0].crd, "v1", mockOpts);
191
+ (0, globals_1.expect)(result).toContain("mock content");
192
+ // Add more assertions based on what is expected after processing
193
+ });
194
+ });
195
+ (0, globals_1.describe)("processFiles", () => {
196
+ const mockOptsWithoutDirectory = { ...mockOpts, directory: undefined };
197
+ (0, globals_1.beforeEach)(() => {
198
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
199
+ });
200
+ (0, globals_1.afterEach)(() => {
201
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
202
+ });
203
+ (0, globals_1.test)("should process files in directory", async () => {
204
+ const mockFileResultMap = { "TestKind-v1.ts": mockCRDResults[0] };
205
+ globals_1.jest.spyOn(mockFileSystem, "readFile").mockReturnValue("mock content");
206
+ globals_1.jest.spyOn(mockFileSystem, "writeFile");
207
+ await postProcessingModule.processFiles(["TestKind-v1.ts"], mockFileResultMap, mockOpts, mockFileSystem);
208
+ (0, globals_1.expect)(mockFileSystem.readFile).toHaveBeenCalledWith("mockDir/TestKind-v1.ts");
209
+ (0, globals_1.expect)(mockFileSystem.writeFile).toHaveBeenCalled();
210
+ });
211
+ (0, globals_1.test)("should throw an error if directory is not defined", async () => {
212
+ const mockFiles = ["TestKind-v1.ts"];
213
+ const mockFileResultMap = { "TestKind-v1.ts": mockCRDResults[0] };
214
+ await (0, globals_1.expect)(postProcessingModule.processFiles(mockFiles, mockFileResultMap, mockOptsWithoutDirectory, mockFileSystem)).rejects.toThrow("Directory is not defined");
215
+ });
216
+ });
217
+ (0, globals_1.describe)("wrapWithFluentClient", () => {
218
+ /* const mockLines = ["line1", "line2"];
219
+ const mockName = "TestKind";
220
+ const mockCRD = {
221
+ spec: {
222
+ group: "test.group",
223
+ names: { kind: "TestKind", plural: "testkinds" },
224
+ scope: "Namespaced",
225
+ versions: [{ name: "v1", served: true, storage: true }],
226
+ },
227
+ };
228
+ const mockVersion = "v1";
229
+ const mockOpts = {
230
+ directory: "mockDir",
231
+ logFn: jest.fn(),
232
+ language: "ts",
233
+ plain: false,
234
+ npmPackage: "mockPackage",
235
+ source: "",
236
+ }; */
237
+ (0, globals_1.beforeEach)(() => {
238
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
239
+ });
240
+ (0, globals_1.test)("should replace interface declaration with class extending GenericKind", () => {
241
+ const inputLines = ["export interface TestKind {", " prop: string;", "}"];
242
+ const crd = {
243
+ spec: {
244
+ group: "test.group",
245
+ names: { plural: "testkinds" },
246
+ },
247
+ }; // mock the CRD
248
+ const expectedOutputLines = [
249
+ "// This file is auto-generated by mockPackage, do not edit manually",
250
+ 'import { GenericKind, RegisterKind } from "mockPackage";',
251
+ "export class TestKind extends GenericKind {",
252
+ " prop: string;",
253
+ "}",
254
+ "RegisterKind(TestKind, {",
255
+ ' group: "test.group",',
256
+ ' version: "v1",',
257
+ ' kind: "TestKind",',
258
+ ' plural: "testkinds",',
259
+ "});",
260
+ ];
261
+ const result = postProcessingModule.wrapWithFluentClient(inputLines, "TestKind", crd, "v1", "mockPackage");
262
+ (0, globals_1.expect)(result).toEqual(expectedOutputLines);
263
+ });
264
+ });
265
+ (0, globals_1.describe)("getGenericKindProperties", () => {
266
+ (0, globals_1.beforeEach)(() => {
267
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
268
+ });
269
+ (0, globals_1.afterEach)(() => {
270
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
271
+ });
272
+ (0, globals_1.test)("should retrieve properties from GenericKind", () => {
273
+ const result = postProcessingModule.getGenericKindProperties();
274
+ (0, globals_1.expect)(result).toContain("kind");
275
+ (0, globals_1.expect)(result).toContain("apiVersion");
276
+ (0, globals_1.expect)(result).not.toContain("[key: string]");
277
+ });
278
+ });
279
+ (0, globals_1.describe)("processLines", () => {
280
+ const mockLines = ["export class TestKind extends GenericKind {", " kind: string;", "}"];
281
+ const mockFoundInterfaces = new Set(["TestKind"]);
282
+ const mockGenericKindProperties = ["kind", "apiVersion"];
283
+ (0, globals_1.beforeEach)(() => {
284
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
285
+ });
286
+ (0, globals_1.afterEach)(() => {
287
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
288
+ });
289
+ (0, globals_1.test)("should process lines and modify properties of classes extending GenericKind", () => {
290
+ const result = postProcessingModule.processLines(mockLines, mockGenericKindProperties, mockFoundInterfaces);
291
+ (0, globals_1.expect)(result).toContain(" declare kind: string;");
292
+ });
293
+ });
294
+ (0, globals_1.describe)("processClassContext", () => {
295
+ const mockGenericKindProperties = ["kind"];
296
+ const mockFoundInterfaces = new Set();
297
+ (0, globals_1.beforeEach)(() => {
298
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
299
+ });
300
+ (0, globals_1.afterEach)(() => {
301
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
302
+ });
303
+ (0, globals_1.test)("should detect class extending GenericKind and modify context", () => {
304
+ const line = "export class TestKind extends GenericKind {";
305
+ const result = postProcessingModule.processClassContext(line, false, 0, mockGenericKindProperties, mockFoundInterfaces);
306
+ (0, globals_1.expect)(result.insideClass).toBe(true);
307
+ (0, globals_1.expect)(result.braceBalance).toBe(1);
308
+ });
309
+ (0, globals_1.test)("should update brace balance when closing braces are found", () => {
310
+ const line = "}";
311
+ const result = postProcessingModule.processClassContext(line, true, 1, mockGenericKindProperties, mockFoundInterfaces);
312
+ (0, globals_1.expect)(result.insideClass).toBe(false);
313
+ (0, globals_1.expect)(result.braceBalance).toBe(0);
314
+ });
315
+ });
316
+ (0, globals_1.describe)("normalizeIndentationAndSpacing", () => {
317
+ const mockOpts = {
318
+ language: "ts",
319
+ source: "",
320
+ logFn: globals_1.jest.fn(),
321
+ };
322
+ (0, globals_1.beforeEach)(() => {
323
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
324
+ });
325
+ (0, globals_1.afterEach)(() => {
326
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
327
+ });
328
+ (0, globals_1.test)("should normalize indentation to two spaces", () => {
329
+ const mockLines = [
330
+ " indentedWithFourSpaces: string;", // Line with 4 spaces, should be normalized
331
+ " alreadyTwoSpaces: string;", // Line with 2 spaces, should remain unchanged
332
+ " sixSpacesIndent: string;", // Line with 6 spaces, only first 4 should be normalized
333
+ "noIndent: string;", // Line with no indentation, should remain unchanged
334
+ ];
335
+ const expectedResult = [
336
+ " indentedWithFourSpaces: string;", // Normalized to 2 spaces
337
+ " alreadyTwoSpaces: string;", // No change
338
+ " sixSpacesIndent: string;", // Only first 4 spaces should be normalized to 2
339
+ "noIndent: string;", // No change
340
+ ];
341
+ const result = postProcessingModule.normalizeIndentation(mockLines);
342
+ (0, globals_1.expect)(result).toEqual(expectedResult);
343
+ });
344
+ (0, globals_1.test)("should normalize single line indentation to two spaces", () => {
345
+ const cases = [
346
+ { input: " indentedWithFourSpaces;", expected: " indentedWithFourSpaces;" }, // 4 spaces to 2 spaces
347
+ { input: " alreadyTwoSpaces;", expected: " alreadyTwoSpaces;" }, // 2 spaces, no change
348
+ { input: " sixSpacesIndent;", expected: " sixSpacesIndent;" }, // First 4 spaces to 2
349
+ { input: "noIndent;", expected: "noIndent;" }, // No indentation, no change
350
+ ];
351
+ cases.forEach(({ input, expected }) => {
352
+ const result = postProcessingModule.normalizeLineIndentation(input);
353
+ (0, globals_1.expect)(result).toBe(expected);
354
+ });
355
+ });
356
+ (0, globals_1.test)("should normalize property spacing", () => {
357
+ const cases = [
358
+ {
359
+ input: "optionalProp ? : string;",
360
+ expected: "optionalProp?: string;",
361
+ }, // Extra spaces around ? and :
362
+ {
363
+ input: "optionalProp?: string;",
364
+ expected: "optionalProp?: string;",
365
+ }, // Already normalized
366
+ {
367
+ input: "optionalProp ? :string;",
368
+ expected: "optionalProp?: string;",
369
+ }, // No space after colon
370
+ {
371
+ input: "nonOptionalProp: string;",
372
+ expected: "nonOptionalProp: string;",
373
+ }, // Non-optional property, should remain unchanged
374
+ ];
375
+ const inputLines = cases.map(c => c.input);
376
+ const expectedLines = cases.map(c => c.expected);
377
+ const result = postProcessingModule.normalizePropertySpacing(inputLines);
378
+ (0, globals_1.expect)(result).toEqual(expectedLines);
379
+ });
380
+ (0, globals_1.test)('should remove lines containing "[property: string]: any;" when language is "ts" or "typescript"', () => {
381
+ const inputLines = [
382
+ "someProp: string;",
383
+ "[property: string]: any;",
384
+ "anotherProp: number;",
385
+ "[property: string]: any;",
386
+ ];
387
+ // Test for TypeScript
388
+ const tsOpts = { ...mockOpts, language: "ts" };
389
+ const resultTs = postProcessingModule.removePropertyStringAny(inputLines, tsOpts);
390
+ const expectedTs = ["someProp: string;", "anotherProp: number;"];
391
+ (0, globals_1.expect)(resultTs).toEqual(expectedTs);
392
+ // Test for TypeScript with "typescript" as language
393
+ const typescriptOpts = { ...mockOpts, language: "typescript" };
394
+ const resultTypescript = postProcessingModule.removePropertyStringAny(inputLines, typescriptOpts);
395
+ (0, globals_1.expect)(resultTypescript).toEqual(expectedTs);
396
+ });
397
+ (0, globals_1.describe)("processEslintDisable", () => {
398
+ (0, globals_1.beforeEach)(() => {
399
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
400
+ });
401
+ (0, globals_1.afterEach)(() => {
402
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
403
+ });
404
+ (0, globals_1.test)('should add ESLint disable comment if line contains "[key: string]: any" and is not part of genericKindProperties', () => {
405
+ const line = "[key: string]: any;";
406
+ const genericKindProperties = ["kind", "apiVersion"]; // No "[key: string]" present
407
+ const result = postProcessingModule.processEslintDisable(line, genericKindProperties);
408
+ (0, globals_1.expect)(result).toEqual(" // eslint-disable-next-line @typescript-eslint/no-explicit-any\n[key: string]: any;");
409
+ });
410
+ (0, globals_1.test)('should not add ESLint disable comment if "[key: string]" is in genericKindProperties', () => {
411
+ const line = "[key: string]: any;";
412
+ const genericKindProperties = ["[key: string]", "kind", "apiVersion"]; // "[key: string]" present
413
+ const result = postProcessingModule.processEslintDisable(line, genericKindProperties);
414
+ (0, globals_1.expect)(result).toEqual("[key: string]: any;"); // No comment added
415
+ });
416
+ (0, globals_1.test)('should not add ESLint disable comment if line does not contain "[key: string]: any"', () => {
417
+ const line = "prop: string;";
418
+ const genericKindProperties = ["kind", "apiVersion"]; // Normal properties
419
+ const result = postProcessingModule.processEslintDisable(line, genericKindProperties);
420
+ (0, globals_1.expect)(result).toEqual("prop: string;"); // No change in the line
421
+ });
422
+ (0, globals_1.test)('should not add ESLint disable comment if line contains "[key: string]: any" but is part of genericKindProperties', () => {
423
+ const line = "[key: string]: any;";
424
+ const genericKindProperties = ["[key: string]"];
425
+ const result = postProcessingModule.processEslintDisable(line, genericKindProperties);
426
+ (0, globals_1.expect)(result).toEqual("[key: string]: any;"); // No comment added since it's in genericKindProperties
427
+ });
428
+ });
429
+ (0, globals_1.test)('should not remove lines when language is not "ts" or "typescript"', () => {
430
+ const inputLines = ["someProp: string;", "[property: string]: any;", "anotherProp: number;"];
431
+ // Test for other languages
432
+ const otherOpts = { ...mockOpts, language: "js" }; // Not TypeScript
433
+ const resultOther = postProcessingModule.removePropertyStringAny(inputLines, otherOpts);
434
+ (0, globals_1.expect)(resultOther).toEqual(inputLines); // Should return the original lines
435
+ });
436
+ });
437
+ (0, globals_1.describe)("makePropertiesOptional", () => {
438
+ (0, globals_1.beforeEach)(() => {
439
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
440
+ });
441
+ (0, globals_1.afterEach)(() => {
442
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
443
+ });
444
+ (0, globals_1.test)("should make property optional if type is found in interfaces and not already optional", () => {
445
+ const line = "myProp: MyInterface;";
446
+ const foundInterfaces = new Set(["MyInterface"]); // Matching interface
447
+ const result = postProcessingModule.makePropertiesOptional(line, foundInterfaces);
448
+ (0, globals_1.expect)(result).toEqual("myProp?: MyInterface;"); // The colon is replaced by `?:`
449
+ });
450
+ (0, globals_1.test)("should not make property optional if type is not found in interfaces", () => {
451
+ const line = "myProp: AnotherType;";
452
+ const foundInterfaces = new Set(["MyInterface"]); // No match for this type
453
+ const result = postProcessingModule.makePropertiesOptional(line, foundInterfaces);
454
+ (0, globals_1.expect)(result).toEqual("myProp: AnotherType;"); // No change
455
+ });
456
+ (0, globals_1.test)("should not make property optional if already optional", () => {
457
+ const line = "myProp?: MyInterface;";
458
+ const foundInterfaces = new Set(["MyInterface"]); // Matching interface, but already optional
459
+ const result = postProcessingModule.makePropertiesOptional(line, foundInterfaces);
460
+ (0, globals_1.expect)(result).toEqual("myProp?: MyInterface;"); // No change since it's already optional
461
+ });
462
+ (0, globals_1.test)("should not change line if it does not match the property pattern", () => {
463
+ const line = "function test() {}";
464
+ const foundInterfaces = new Set(["MyInterface"]); // Matching interface, but the line is not a property
465
+ const result = postProcessingModule.makePropertiesOptional(line, foundInterfaces);
466
+ (0, globals_1.expect)(result).toEqual("function test() {}"); // No change
467
+ });
468
+ });
469
+ (0, globals_1.describe)("collectInterfaceNames", () => {
470
+ (0, globals_1.beforeEach)(() => {
471
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
472
+ });
473
+ (0, globals_1.afterEach)(() => {
474
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
475
+ });
476
+ (0, globals_1.test)("should collect interface names from lines", () => {
477
+ const lines = [
478
+ "export interface MyInterface {",
479
+ "export interface AnotherInterface {",
480
+ "some other line",
481
+ "export interface YetAnotherInterface {",
482
+ ];
483
+ const result = postProcessingModule.collectInterfaceNames(lines);
484
+ (0, globals_1.expect)(result).toEqual(new Set(["MyInterface", "AnotherInterface", "YetAnotherInterface"]));
485
+ });
486
+ (0, globals_1.test)("should return an empty set if no interfaces are found", () => {
487
+ const lines = ["some other line", "function test() {}", "const value = 42;"];
488
+ const result = postProcessingModule.collectInterfaceNames(lines);
489
+ (0, globals_1.expect)(result).toEqual(new Set());
490
+ });
491
+ (0, globals_1.test)("should not add duplicate interface names", () => {
492
+ const lines = ["export interface MyInterface {", "export interface MyInterface {"];
493
+ const result = postProcessingModule.collectInterfaceNames(lines);
494
+ (0, globals_1.expect)(result).toEqual(new Set(["MyInterface"]));
495
+ });
496
+ });
497
+ (0, globals_1.describe)("writeFile", () => {
498
+ const mockFilePath = "test/path/to/file.ts";
499
+ const mockContent = "export const test = 'Test content';";
500
+ (0, globals_1.beforeEach)(() => {
501
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
502
+ });
503
+ (0, globals_1.afterEach)(() => {
504
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
505
+ });
506
+ (0, globals_1.test)("should write file content successfully", () => {
507
+ // Simulate fs.writeFileSync working as expected
508
+ fs.writeFileSync.mockImplementation(() => { });
509
+ // Call the function
510
+ postProcessingModule.writeFile(mockFilePath, mockContent);
511
+ // Assert that writeFileSync was called with the correct arguments
512
+ (0, globals_1.expect)(fs.writeFileSync).toHaveBeenCalledWith(mockFilePath, mockContent, "utf8");
513
+ });
514
+ (0, globals_1.test)("should throw an error when writeFileSync fails", () => {
515
+ // Simulate fs.writeFileSync throwing an error
516
+ fs.writeFileSync.mockImplementation(() => {
517
+ throw new Error("File write error");
518
+ });
519
+ // Expect the function to throw the error
520
+ (0, globals_1.expect)(() => postProcessingModule.writeFile(mockFilePath, mockContent)).toThrow(`Failed to write file at ${mockFilePath}: File write error`);
521
+ });
522
+ });
523
+ (0, globals_1.describe)("readFile", () => {
524
+ const mockFilePath = "test/path/to/file.ts";
525
+ const mockContent = "export const test = 'Test content';";
526
+ (0, globals_1.beforeEach)(() => {
527
+ globals_1.jest.clearAllMocks(); // Clear mocks before each test
528
+ });
529
+ (0, globals_1.afterEach)(() => {
530
+ globals_1.jest.restoreAllMocks(); // Restore all mocks after each test
531
+ });
532
+ (0, globals_1.test)("should read file content successfully", () => {
533
+ // Simulate fs.readFileSync returning content
534
+ fs.readFileSync.mockReturnValue(mockContent);
535
+ // Call the function
536
+ const result = postProcessingModule.readFile(mockFilePath);
537
+ // Assert that readFileSync was called with the correct arguments
538
+ (0, globals_1.expect)(fs.readFileSync).toHaveBeenCalledWith(mockFilePath, "utf8");
539
+ // Assert that the result matches the mock content
540
+ (0, globals_1.expect)(result).toBe(mockContent);
541
+ });
542
+ (0, globals_1.test)("should throw an error when readFileSync fails", () => {
543
+ // Simulate fs.readFileSync throwing an error
544
+ fs.readFileSync.mockImplementation(() => {
545
+ throw new Error("File read error");
546
+ });
547
+ // Expect the function to throw the error
548
+ (0, globals_1.expect)(() => postProcessingModule.readFile(mockFilePath)).toThrow(`Failed to read file at ${mockFilePath}: File read error`);
549
+ });
550
+ });
@@ -0,0 +1,123 @@
1
+ import { execFile } from "child_process";
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ import { describe, beforeEach, test, expect, afterEach } from "@jest/globals";
5
+
6
+ // Utility function to execute the CLI command
7
+ const runCliCommand = (
8
+ args: string[],
9
+ callback: (error: Error | null, stdout: string, stderr: string) => void,
10
+ ) => {
11
+ execFile("node", ["./dist/cli.js", ...args], callback); // Path to built CLI JS file
12
+ };
13
+
14
+ // Utility function to compare generated files to expected files
15
+ const compareGeneratedToExpected = (generatedFile: string, expectedFile: string) => {
16
+ // Check if the expected file exists
17
+ expect(fs.existsSync(expectedFile)).toBe(true);
18
+
19
+ // Read and compare the content of the generated file to the expected file
20
+ const generatedContent = fs.readFileSync(generatedFile, "utf8").trim();
21
+ const expectedContent = fs.readFileSync(expectedFile, "utf8").trim();
22
+
23
+ expect(generatedContent).toBe(expectedContent);
24
+ };
25
+
26
+ describe("End-to-End CLI tests with multiple test files", () => {
27
+ const testFolder = path.join(__dirname, "crds/test.yaml"); // Directory containing .test.yaml files
28
+
29
+ // Get all .test.yaml files in the test folder
30
+ const testFiles = fs.readdirSync(testFolder).filter(file => file.endsWith(".test.yaml"));
31
+
32
+ testFiles.forEach(testFile => {
33
+ const name = path.basename(testFile, ".test.yaml"); // Extract name from the filename
34
+ const mockYamlPath = path.join(testFolder, testFile); // Full path to the test YAML file
35
+ const mockDir = path.join(__dirname, "crds/", name); // Output directory based on name
36
+ const expectedDir = path.join(__dirname, `crds/${name}.default.expected`); // Expected default directory
37
+ const expectedPostDir = path.join(__dirname, `crds/${name}.no.post.expected`); // Expected post-processing directory
38
+
39
+ console.log(`Running tests for ${name}`);
40
+ console.log(`Test file: ${mockYamlPath}`);
41
+ console.log(`Output directory: ${mockDir}`);
42
+ console.log(`Expected directory: ${expectedDir}`);
43
+ console.log(`Expected post-processing directory: ${expectedPostDir}`);
44
+
45
+ beforeEach(() => {
46
+ // Ensure the output directory is clean
47
+ if (fs.existsSync(mockDir)) {
48
+ fs.rmdirSync(mockDir, { recursive: true });
49
+ }
50
+
51
+ // Recreate the output directory
52
+ fs.mkdirSync(mockDir);
53
+ });
54
+
55
+ afterEach(() => {
56
+ // Cleanup the output directory after each test
57
+ if (fs.existsSync(mockDir)) {
58
+ fs.rmdirSync(mockDir, { recursive: true });
59
+ }
60
+ });
61
+
62
+ test(`should generate TypeScript types and run post-processing for ${name}`, done => {
63
+ // Run the CLI command with the appropriate arguments
64
+ runCliCommand(["crd", mockYamlPath, mockDir], (error, stdout) => {
65
+ expect(error).toBeNull(); // Ensure no errors occurred
66
+
67
+ // Get the list of generated files
68
+ const generatedFiles = fs.readdirSync(mockDir);
69
+
70
+ // Compare each generated file to the corresponding expected file in expectedDir
71
+ generatedFiles.forEach(file => {
72
+ const generatedFilePath = path.join(mockDir, file);
73
+ const expectedFilePath = path.join(expectedDir, file);
74
+
75
+ compareGeneratedToExpected(generatedFilePath, expectedFilePath);
76
+ });
77
+
78
+ // Verify stdout output
79
+ expect(stdout).toContain("✅ Generated");
80
+
81
+ // Complete the test
82
+ done();
83
+ });
84
+ });
85
+
86
+ test(`should skip post-processing for ${name} when using --noPost`, done => {
87
+ // Run the CLI command without the --noPost flag
88
+ runCliCommand(["crd", mockYamlPath, mockDir, "--noPost"], (error, stdout) => {
89
+ expect(error).toBeNull(); // Ensure no errors occurred
90
+
91
+ // Ensure post-processing was not run (stdout should reflect this)
92
+ expect(stdout).not.toContain("🔧 Post-processing started");
93
+
94
+ // Complete the test
95
+ done();
96
+ });
97
+ });
98
+
99
+ test(`should skip post-processing for ${name} when using --noPost`, done => {
100
+ // Run the CLI command without post-processing
101
+ runCliCommand(["crd", mockYamlPath, mockDir, "--noPost"], (error, stdout) => {
102
+ expect(error).toBeNull(); // Ensure no errors occurred
103
+
104
+ // Get the list of generated files
105
+ const generatedFiles = fs.readdirSync(mockDir);
106
+
107
+ // Compare each generated file to the corresponding expected file in expectedPostDir
108
+ generatedFiles.forEach(file => {
109
+ const generatedFilePath = path.join(mockDir, file);
110
+ const expectedFilePath = path.join(expectedPostDir, file);
111
+
112
+ compareGeneratedToExpected(generatedFilePath, expectedFilePath);
113
+ });
114
+
115
+ // Ensure post-processing was not run (stdout should reflect this)
116
+ expect(stdout).not.toContain("🔧 Post-processing started");
117
+
118
+ // Complete the test
119
+ done();
120
+ });
121
+ });
122
+ });
123
+ });