kubernetes-fluent-client 3.1.2 → 3.1.3

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 (57) hide show
  1. package/.husky/pre-commit +1 -0
  2. package/.lintstagedrc.json +5 -0
  3. package/dist/fluent/watch.d.ts.map +1 -1
  4. package/dist/fluent/watch.js +4 -3
  5. package/package.json +8 -5
  6. package/src/fluent/watch.ts +6 -4
  7. package/dist/fetch.test.d.ts +0 -2
  8. package/dist/fetch.test.d.ts.map +0 -1
  9. package/dist/fetch.test.js +0 -97
  10. package/dist/fileSystem.test.d.ts +0 -2
  11. package/dist/fileSystem.test.d.ts.map +0 -1
  12. package/dist/fileSystem.test.js +0 -75
  13. package/dist/fluent/http2-watch.spec.d.ts +0 -2
  14. package/dist/fluent/http2-watch.spec.d.ts.map +0 -1
  15. package/dist/fluent/http2-watch.spec.js +0 -284
  16. package/dist/fluent/index.test.d.ts +0 -2
  17. package/dist/fluent/index.test.d.ts.map +0 -1
  18. package/dist/fluent/index.test.js +0 -193
  19. package/dist/fluent/utils.test.d.ts +0 -2
  20. package/dist/fluent/utils.test.d.ts.map +0 -1
  21. package/dist/fluent/utils.test.js +0 -215
  22. package/dist/fluent/watch.spec.d.ts +0 -2
  23. package/dist/fluent/watch.spec.d.ts.map +0 -1
  24. package/dist/fluent/watch.spec.js +0 -261
  25. package/dist/generate.test.d.ts +0 -2
  26. package/dist/generate.test.d.ts.map +0 -1
  27. package/dist/generate.test.js +0 -320
  28. package/dist/helpers.test.d.ts +0 -2
  29. package/dist/helpers.test.d.ts.map +0 -1
  30. package/dist/helpers.test.js +0 -37
  31. package/dist/kinds.test.d.ts +0 -2
  32. package/dist/kinds.test.d.ts.map +0 -1
  33. package/dist/kinds.test.js +0 -155
  34. package/dist/postProcessing.test.d.ts +0 -2
  35. package/dist/postProcessing.test.d.ts.map +0 -1
  36. package/dist/postProcessing.test.js +0 -550
  37. package/e2e/cli.e2e.test.ts +0 -127
  38. package/e2e/crds/policyreports.default.expected/policyreport-v1alpha1.ts +0 -332
  39. package/e2e/crds/policyreports.default.expected/policyreport-v1alpha2.ts +0 -360
  40. package/e2e/crds/policyreports.default.expected/policyreport-v1beta1.ts +0 -360
  41. package/e2e/crds/policyreports.no.post.expected/policyreport-v1alpha1.ts +0 -331
  42. package/e2e/crds/policyreports.no.post.expected/policyreport-v1alpha2.ts +0 -360
  43. package/e2e/crds/policyreports.no.post.expected/policyreport-v1beta1.ts +0 -360
  44. package/e2e/crds/test.yaml/policyreports.test.yaml +0 -1008
  45. package/e2e/crds/test.yaml/uds-podmonitors.test.yaml +0 -1245
  46. package/e2e/crds/uds-podmonitors.default.expected/podmonitor-v1.ts +0 -1333
  47. package/e2e/crds/uds-podmonitors.no.post.expected/podmonitor-v1.ts +0 -1360
  48. package/src/fetch.test.ts +0 -115
  49. package/src/fileSystem.test.ts +0 -67
  50. package/src/fluent/http2-watch.spec.ts +0 -335
  51. package/src/fluent/index.test.ts +0 -268
  52. package/src/fluent/utils.test.ts +0 -276
  53. package/src/fluent/watch.spec.ts +0 -299
  54. package/src/generate.test.ts +0 -399
  55. package/src/helpers.test.ts +0 -42
  56. package/src/kinds.test.ts +0 -166
  57. package/src/postProcessing.test.ts +0 -742
@@ -1,299 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
-
3
- import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
4
- import nock from "nock";
5
- import { PassThrough } from "readable-stream";
6
-
7
- import { K8s } from ".";
8
- import { WatchEvent, kind } from "..";
9
- import { WatchPhase } from "./types";
10
- import { Watcher } from "./watch";
11
-
12
- describe("Watcher", () => {
13
- const evtMock = jest.fn<(update: kind.Pod, phase: WatchPhase) => void>();
14
- const errMock = jest.fn<(err: Error) => void>();
15
-
16
- const setupAndStartWatcher = (eventType: WatchEvent, handler: (...args: any[]) => void) => {
17
- watcher.events.on(eventType, handler);
18
- watcher.start().catch(errMock);
19
- };
20
-
21
- let watcher: Watcher<typeof kind.Pod>;
22
-
23
- beforeEach(() => {
24
- jest.resetAllMocks();
25
-
26
- nock("http://jest-test:8080")
27
- .get("/api/v1/pods")
28
- .reply(200, {
29
- kind: "PodList",
30
- apiVersion: "v1",
31
- metadata: {
32
- resourceVersion: "10",
33
- },
34
- items: [createMockPod(`pod-0`, `1`)],
35
- });
36
-
37
- nock("http://jest-test:8080")
38
- .get("/api/v1/pods")
39
- .query({ watch: "true", resourceVersion: "10" })
40
- .reply(200, () => {
41
- const stream = new PassThrough();
42
-
43
- const resources = [
44
- { type: "ADDED", object: createMockPod(`pod-0`, `1`) },
45
- { type: "MODIFIED", object: createMockPod(`pod-0`, `2`) },
46
- ];
47
-
48
- resources.forEach(resource => {
49
- stream.write(JSON.stringify(resource) + "\n");
50
- });
51
-
52
- stream.end();
53
-
54
- return stream;
55
- });
56
- });
57
-
58
- afterEach(() => {
59
- watcher.close();
60
- });
61
-
62
- it("should watch named resources", done => {
63
- nock.cleanAll();
64
- nock("http://jest-test:8080")
65
- .get("/api/v1/namespaces/tester/pods")
66
- .query({ fieldSelector: "metadata.name=demo" })
67
- .reply(200, createMockPod(`demo`, `15`));
68
-
69
- nock("http://jest-test:8080")
70
- .get("/api/v1/namespaces/tester/pods")
71
- .query({
72
- watch: "true",
73
- fieldSelector: "metadata.name=demo",
74
- resourceVersion: "15",
75
- })
76
- .reply(200);
77
-
78
- watcher = K8s(kind.Pod, { name: "demo" }).InNamespace("tester").Watch(evtMock);
79
-
80
- setupAndStartWatcher(WatchEvent.CONNECT, () => {
81
- done();
82
- });
83
- });
84
-
85
- it("should handle resource version is too old", done => {
86
- nock.cleanAll();
87
- nock("http://jest-test:8080")
88
- .get("/api/v1/pods")
89
- .reply(200, {
90
- kind: "PodList",
91
- apiVersion: "v1",
92
- metadata: {
93
- resourceVersion: "25",
94
- },
95
- items: [createMockPod(`pod-0`, `1`)],
96
- });
97
- nock("http://jest-test:8080")
98
- .get("/api/v1/pods")
99
- .query({ watch: "true", resourceVersion: "25" })
100
- .reply(200, () => {
101
- const stream = new PassThrough();
102
- stream.write(
103
- JSON.stringify({
104
- type: "ERROR",
105
- object: {
106
- kind: "Status",
107
- apiVersion: "v1",
108
- metadata: {},
109
- status: "Failure",
110
- message: "too old resource version: 123 (391079)",
111
- reason: "Gone",
112
- code: 410,
113
- },
114
- }) + "\n",
115
- );
116
-
117
- stream.end();
118
- return stream;
119
- });
120
-
121
- watcher = K8s(kind.Pod).Watch(evtMock);
122
-
123
- setupAndStartWatcher(WatchEvent.OLD_RESOURCE_VERSION, res => {
124
- expect(res).toEqual("25");
125
- done();
126
- });
127
- });
128
-
129
- it("should call the event handler for each event", done => {
130
- watcher = K8s(kind.Pod).Watch((evt, phase) => {
131
- expect(evt.metadata?.name).toEqual(`pod-0`);
132
- expect(phase).toEqual(WatchPhase.Added);
133
- done();
134
- });
135
-
136
- watcher.start().catch(errMock);
137
- });
138
-
139
- it("should return the cache id", () => {
140
- watcher = K8s(kind.Pod).Watch(evtMock, {
141
- resyncDelaySec: 1,
142
- });
143
- expect(watcher.getCacheID()).toEqual("d69b75a611");
144
- });
145
-
146
- it("should handle the CONNECT event", done => {
147
- watcher = K8s(kind.Pod).Watch(evtMock, {
148
- resyncDelaySec: 1,
149
- });
150
- setupAndStartWatcher(WatchEvent.CONNECT, () => {
151
- done();
152
- });
153
- });
154
-
155
- it("should handle the DATA event", done => {
156
- watcher = K8s(kind.Pod).Watch(evtMock, {
157
- resyncDelaySec: 1,
158
- });
159
- setupAndStartWatcher(WatchEvent.DATA, (pod, phase) => {
160
- expect(pod.metadata?.name).toEqual(`pod-0`);
161
- expect(phase).toEqual(WatchPhase.Added);
162
- done();
163
- });
164
- });
165
-
166
- it("should handle the NETWORK_ERROR event", done => {
167
- nock.cleanAll();
168
- nock("http://jest-test:8080")
169
- .get("/api/v1/pods")
170
- .reply(200, {
171
- kind: "PodList",
172
- apiVersion: "v1",
173
- metadata: {
174
- resourceVersion: "45",
175
- },
176
- items: [createMockPod(`pod-0`, `1`)],
177
- });
178
- nock("http://jest-test:8080")
179
- .get("/api/v1/pods")
180
- .query({ watch: "true", resourceVersion: "45" })
181
- .replyWithError("Something bad happened");
182
-
183
- watcher = K8s(kind.Pod).Watch(evtMock, {
184
- resyncDelaySec: 1,
185
- });
186
-
187
- setupAndStartWatcher(WatchEvent.NETWORK_ERROR, error => {
188
- expect(error.message).toEqual(
189
- "request to http://jest-test:8080/api/v1/pods?watch=true&resourceVersion=45 failed, reason: Something bad happened",
190
- );
191
- done();
192
- });
193
- });
194
-
195
- it("should handle the RECONNECT event on an error", done => {
196
- nock.cleanAll();
197
- nock("http://jest-test:8080")
198
- .get("/api/v1/pods")
199
- .reply(200, {
200
- kind: "PodList",
201
- apiVersion: "v1",
202
- metadata: {
203
- resourceVersion: "65",
204
- },
205
- items: [createMockPod(`pod-0`, `1`)],
206
- });
207
- nock("http://jest-test:8080")
208
- .get("/api/v1/pods")
209
- .query({ watch: "true", resourceVersion: "65" })
210
- .replyWithError("Something bad happened");
211
-
212
- watcher = K8s(kind.Pod).Watch(evtMock, {
213
- resyncDelaySec: 0.01,
214
- });
215
-
216
- setupAndStartWatcher(WatchEvent.RECONNECT, count => {
217
- expect(count).toEqual(1);
218
- done();
219
- });
220
- });
221
-
222
- it("should perform a resync after the resync interval", done => {
223
- watcher = K8s(kind.Pod).Watch(evtMock, {
224
- resyncDelaySec: 0.01,
225
- lastSeenLimitSeconds: 0.01,
226
- });
227
-
228
- setupAndStartWatcher(WatchEvent.RECONNECT, count => {
229
- expect(count).toEqual(1);
230
- done();
231
- });
232
- });
233
-
234
- it("should handle the GIVE_UP event", done => {
235
- nock.cleanAll();
236
- nock("http://jest-test:8080")
237
- .get("/api/v1/pods")
238
- .reply(200, {
239
- kind: "PodList",
240
- apiVersion: "v1",
241
- metadata: {
242
- resourceVersion: "75",
243
- },
244
- items: [createMockPod(`pod-0`, `1`)],
245
- });
246
- nock("http://jest-test:8080")
247
- .get("/api/v1/pods")
248
- .query({ watch: "true", resourceVersion: "75" })
249
- .replyWithError("Something bad happened");
250
-
251
- watcher = K8s(kind.Pod).Watch(evtMock, {
252
- resyncFailureMax: 1,
253
- resyncDelaySec: 0.01,
254
- lastSeenLimitSeconds: 1,
255
- });
256
-
257
- setupAndStartWatcher(WatchEvent.GIVE_UP, error => {
258
- expect(error.message).toContain("Retry limit (1) exceeded, giving up");
259
- done();
260
- });
261
- });
262
- });
263
-
264
- /**
265
- * Creates a mock pod object
266
- *
267
- * @param name The name of the pod
268
- * @param resourceVersion The resource version of the pod
269
- * @returns A mock pod object
270
- */
271
- function createMockPod(name: string, resourceVersion: string): kind.Pod {
272
- return {
273
- kind: "Pod",
274
- apiVersion: "v1",
275
- metadata: {
276
- name: name,
277
- resourceVersion: resourceVersion,
278
- uid: Math.random().toString(36).substring(7),
279
- // ... other metadata fields
280
- },
281
- spec: {
282
- containers: [
283
- {
284
- name: "nginx",
285
- image: "nginx:1.14.2",
286
- ports: [
287
- {
288
- containerPort: 80,
289
- protocol: "TCP",
290
- },
291
- ],
292
- },
293
- ],
294
- },
295
- status: {
296
- // ... pod status
297
- },
298
- };
299
- }
@@ -1,399 +0,0 @@
1
- import { beforeEach, describe, expect, jest, test } from "@jest/globals";
2
- import { convertCRDtoTS, GenerateOptions, readOrFetchCrd } from "./generate";
3
- import fs from "fs";
4
- import path from "path";
5
- import { quicktype } from "quicktype-core";
6
- import { fetch } from "./fetch";
7
- import { loadAllYaml } from "@kubernetes/client-node";
8
- import { K8s } from "./fluent";
9
- import { CustomResourceDefinition } from "./upstream";
10
-
11
- // Mock the file system
12
- jest.mock("fs", () => ({
13
- ...(jest.requireActual("fs") as object), // Preserve the rest of the fs module
14
- writeFileSync: jest.fn(), // Mock only writeFileSync
15
- existsSync: jest.fn(),
16
- readFileSync: jest.fn(),
17
- }));
18
- jest.mock("./fetch");
19
- jest.mock("quicktype-core", () => {
20
- const actualQuicktypeCore = jest.requireActual<typeof import("quicktype-core")>("quicktype-core");
21
- return {
22
- quicktype: jest.fn(),
23
- JSONSchemaInput: actualQuicktypeCore.JSONSchemaInput,
24
- FetchingJSONSchemaStore: actualQuicktypeCore.FetchingJSONSchemaStore,
25
- InputData: actualQuicktypeCore.InputData,
26
- };
27
- });
28
- jest.mock("@kubernetes/client-node", () => {
29
- const actualModule = jest.requireActual("@kubernetes/client-node");
30
- return {
31
- ...(typeof actualModule === "object" ? actualModule : {}),
32
- loadAllYaml: jest.fn(), // Mock only the specific method
33
- };
34
- });
35
- jest.mock("./fluent", () => ({
36
- K8s: jest.fn(),
37
- }));
38
- jest.mock("./generate", () => {
39
- const actualGenerate = jest.requireActual("./generate");
40
- return {
41
- ...(typeof actualGenerate === "object" ? actualGenerate : {}),
42
- resolveFilePath: jest.fn(), // Mock resolveFilePath globally
43
- tryParseUrl: jest.fn(),
44
- };
45
- });
46
-
47
- // Sample CRD content to use in tests
48
- const sampleCrd = {
49
- apiVersion: "apiextensions.k8s.io/v1",
50
- kind: "CustomResourceDefinition",
51
- metadata: { name: "movies.example.com" },
52
- spec: {
53
- group: "example.com",
54
- names: { kind: "Movie", plural: "movies" },
55
- scope: "Namespaced",
56
- versions: [
57
- {
58
- name: "v1",
59
- served: true,
60
- storage: true,
61
- schema: {
62
- openAPIV3Schema: {
63
- type: "object",
64
- description: "Movie nerd",
65
- properties: {
66
- spec: {
67
- properties: {
68
- title: { type: "string" },
69
- author: { type: "string" },
70
- },
71
- },
72
- },
73
- },
74
- },
75
- },
76
- ],
77
- },
78
- };
79
-
80
- const expectedMovie = [
81
- "/**",
82
- " * Movie nerd",
83
- " */",
84
- "export interface Movie {",
85
- " spec?: any[] | boolean | number | number | null | SpecObject | string;",
86
- " [property: string]: any;",
87
- "}",
88
- "",
89
- "export interface SpecObject {",
90
- " author?: string;",
91
- " title?: string;",
92
- " [property: string]: any;",
93
- "}",
94
- "",
95
- ];
96
-
97
- describe("CRD Generate", () => {
98
- let logFn: jest.Mock; // Mock log function
99
-
100
- beforeEach(() => {
101
- jest.clearAllMocks(); // Reset all mocks before each test
102
- logFn = jest.fn(); // Mock the log function with correct typing
103
- });
104
-
105
- test("convertCRDtoTS should generate the expected TypeScript file", async () => {
106
- // Mock convertCRDtoTS to return a valid result structure
107
- (quicktype as jest.MockedFunction<typeof quicktype>).mockResolvedValueOnce({
108
- lines: expectedMovie,
109
- annotations: [],
110
- });
111
-
112
- const options = {
113
- source: "test-crd.yaml",
114
- language: "ts",
115
- logFn,
116
- directory: "test-dir",
117
- plain: false,
118
- npmPackage: "kubernetes-fluent-client",
119
- };
120
-
121
- // Call convertCRDtoTS with sample CRD
122
- const result = await convertCRDtoTS(sampleCrd, options);
123
-
124
- // Extract the generated types from the result
125
- const generatedTypes = result[0].results["movie-v1"];
126
-
127
- // Assert that the generated types match the expected TypeScript code
128
- expect(generatedTypes).toEqual(expectedMovie);
129
-
130
- // Assert the file writing happens with the expected TypeScript content
131
- expect(fs.writeFileSync).toHaveBeenCalledWith(
132
- path.join("test-dir", "movie-v1.ts"),
133
- expectedMovie.join("\n"),
134
- );
135
-
136
- // Assert the logs contain expected log messages
137
- expect(logFn).toHaveBeenCalledWith("- Generating example.com/v1 types for Movie");
138
- });
139
- });
140
-
141
- describe("readOrFetchCrd", () => {
142
- let mockOpts: GenerateOptions;
143
-
144
- beforeEach(() => {
145
- jest.clearAllMocks();
146
- mockOpts = {
147
- source: "mock-file-path",
148
- logFn: jest.fn(),
149
- };
150
-
151
- // Reapply mock for resolveFilePath inside beforeEach
152
- const { resolveFilePath } = jest.requireMock("./generate") as { resolveFilePath: jest.Mock };
153
- resolveFilePath.mockReturnValue("mock-file-path");
154
- });
155
-
156
- test("should load CRD from a local file", async () => {
157
- // Inside the test:
158
- const absoluteFilePath = path.join(process.cwd(), "mock-file-path");
159
-
160
- // Mock file system functions
161
- (fs.existsSync as jest.Mock).mockReturnValue(true);
162
- (fs.readFileSync as jest.Mock).mockReturnValue("mock file content");
163
-
164
- // Mock loadAllYaml to return parsed CRD
165
- const mockCrd = [{ kind: "CustomResourceDefinition" }] as CustomResourceDefinition[];
166
- (loadAllYaml as jest.Mock).mockReturnValue(mockCrd);
167
-
168
- // Call the function
169
- const result = await readOrFetchCrd(mockOpts);
170
-
171
- // Assert fs and loadAllYaml were called with correct args
172
- expect(fs.existsSync).toHaveBeenCalledWith(absoluteFilePath);
173
- expect(fs.readFileSync).toHaveBeenCalledWith(absoluteFilePath, "utf8");
174
- expect(loadAllYaml).toHaveBeenCalledWith("mock file content");
175
-
176
- // Assert the result matches the mocked CRD
177
- expect(result).toEqual(mockCrd);
178
-
179
- // Assert log function was called with correct message
180
- expect(mockOpts.logFn).toHaveBeenCalledWith(
181
- "Attempting to load mock-file-path as a local file",
182
- );
183
- });
184
- });
185
-
186
- describe("readOrFetchCrd with URL", () => {
187
- let mockOpts: GenerateOptions;
188
-
189
- beforeEach(() => {
190
- jest.clearAllMocks();
191
- mockOpts = {
192
- source: "http://example.com/mock-crd",
193
- logFn: jest.fn(),
194
- };
195
-
196
- // Mock resolveFilePath to simulate URL logic
197
- const { resolveFilePath } = jest.requireMock("./generate") as {
198
- resolveFilePath: jest.Mock;
199
- };
200
- resolveFilePath.mockReturnValue("mock-file-path");
201
-
202
- // Ensure fs.existsSync returns false for URL tests to skip file logic
203
- (fs.existsSync as jest.Mock).mockReturnValue(false);
204
- });
205
-
206
- test("should fetch CRD from a URL and parse YAML", async () => {
207
- const { tryParseUrl } = jest.requireMock("./generate") as { tryParseUrl: jest.Mock };
208
- tryParseUrl.mockReturnValue(new URL("http://example.com/mock-crd"));
209
-
210
- // Mock fetch to return a valid response
211
- (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValue({
212
- ok: true,
213
- data: "mock fetched data",
214
- status: 0,
215
- statusText: "",
216
- });
217
-
218
- // Mock loadAllYaml to return parsed CRD
219
- const mockCrd = [{ kind: "CustomResourceDefinition" }] as CustomResourceDefinition[];
220
- (loadAllYaml as jest.Mock).mockReturnValue(mockCrd);
221
-
222
- // Call the function
223
- const result = await readOrFetchCrd(mockOpts);
224
-
225
- // Assert fetch was called with correct URL
226
- expect(fetch).toHaveBeenCalledWith("http://example.com/mock-crd");
227
-
228
- // Assert loadAllYaml was called with fetched data
229
- expect(loadAllYaml).toHaveBeenCalledWith("mock fetched data");
230
-
231
- // Assert the result matches the mocked CRD
232
- expect(result).toEqual(mockCrd);
233
-
234
- // Assert log function was called with correct message
235
- expect(mockOpts.logFn).toHaveBeenCalledWith(
236
- "Attempting to load http://example.com/mock-crd as a URL",
237
- );
238
- });
239
- });
240
-
241
- describe("readOrFetchCrd from Kubernetes cluster", () => {
242
- let mockOpts: GenerateOptions;
243
-
244
- beforeEach(() => {
245
- jest.clearAllMocks();
246
- mockOpts = {
247
- source: "my-crd",
248
- logFn: jest.fn(),
249
- };
250
-
251
- // Mock resolveFilePath and tryParseUrl to return null or invalid results
252
- const { resolveFilePath, tryParseUrl } = jest.requireMock("./generate") as {
253
- resolveFilePath: jest.Mock;
254
- tryParseUrl: jest.Mock;
255
- };
256
- resolveFilePath.mockReturnValue("mock-file-path");
257
- tryParseUrl.mockReturnValue(null);
258
-
259
- // Ensure fs.existsSync returns false to force fallback to Kubernetes
260
- (fs.existsSync as jest.Mock).mockReturnValue(false);
261
- });
262
-
263
- test("should load CRD from Kubernetes cluster", async () => {
264
- // Mock K8s to return a mocked CRD from the Kubernetes cluster
265
- const mockCrd = { kind: "CustomResourceDefinition" } as CustomResourceDefinition;
266
- const mockK8sGet = jest
267
- .fn<() => Promise<CustomResourceDefinition>>()
268
- .mockResolvedValue(mockCrd);
269
- (K8s as jest.Mock).mockReturnValue({ Get: mockK8sGet });
270
-
271
- // Call the function
272
- const result = await readOrFetchCrd(mockOpts);
273
-
274
- // Assert K8s.Get was called with the correct source
275
- expect(K8s).toHaveBeenCalledWith(CustomResourceDefinition);
276
- expect(mockK8sGet).toHaveBeenCalledWith("my-crd");
277
-
278
- // Assert the result matches the mocked CRD
279
- expect(result).toEqual([mockCrd]);
280
-
281
- // Assert log function was called with correct message
282
- expect(mockOpts.logFn).toHaveBeenCalledWith(
283
- "Attempting to read my-crd from the Kubernetes cluster",
284
- );
285
- });
286
-
287
- test("should log an error if Kubernetes cluster read fails", async () => {
288
- // Mock K8s to throw an error
289
- const mockError = new Error("Kubernetes API error");
290
- const mockK8sGet = jest.fn<() => Promise<never>>().mockRejectedValue(mockError);
291
- (K8s as jest.Mock).mockReturnValue({ Get: mockK8sGet });
292
-
293
- // Call the function and assert that it throws an error
294
- await expect(readOrFetchCrd(mockOpts)).rejects.toThrowError(
295
- `Failed to read my-crd as a file, URL, or Kubernetes CRD`,
296
- );
297
-
298
- // Assert log function was called with error message
299
- expect(mockOpts.logFn).toHaveBeenCalledWith("Error loading CRD: Kubernetes API error");
300
-
301
- // Assert K8s.Get was called with the correct source
302
- expect(K8s).toHaveBeenCalledWith(CustomResourceDefinition);
303
- expect(mockK8sGet).toHaveBeenCalledWith("my-crd");
304
- });
305
- });
306
-
307
- describe("readOrFetchCrd error handling", () => {
308
- let mockOpts: GenerateOptions;
309
-
310
- beforeEach(() => {
311
- jest.clearAllMocks();
312
- mockOpts = {
313
- source: "mock-source",
314
- logFn: jest.fn(),
315
- };
316
- });
317
-
318
- test("should throw an error if file reading fails", async () => {
319
- (fs.existsSync as jest.Mock).mockReturnValue(true);
320
- (fs.readFileSync as jest.Mock).mockImplementation(() => {
321
- throw new Error("File read error");
322
- });
323
-
324
- await expect(readOrFetchCrd(mockOpts)).rejects.toThrowError(
325
- "Failed to read mock-source as a file, URL, or Kubernetes CRD",
326
- );
327
-
328
- expect(mockOpts.logFn).toHaveBeenCalledWith("Error loading CRD: File read error");
329
- });
330
- });
331
-
332
- describe("convertCRDtoTS with invalid CRD", () => {
333
- test("should skip CRD with no versions", async () => {
334
- const invalidCrd = {
335
- ...sampleCrd,
336
- spec: {
337
- ...sampleCrd.spec,
338
- versions: [], // CRD with no versions
339
- },
340
- };
341
-
342
- const options = {
343
- source: "mock-source",
344
- language: "ts",
345
- logFn: jest.fn(), // Ensure the mock log function is set
346
- directory: "test-dir",
347
- plain: false,
348
- npmPackage: "kubernetes-fluent-client",
349
- };
350
-
351
- const result = await convertCRDtoTS(invalidCrd, options);
352
-
353
- // Assert that result is empty due to invalid CRD
354
- expect(result).toEqual([]);
355
-
356
- // Assert the log function is called with the correct message
357
- expect(options.logFn).toHaveBeenCalledWith(
358
- "Skipping movies.example.com, it does not appear to be a CRD",
359
- );
360
- });
361
-
362
- test("should handle schema with no OpenAPI schema", async () => {
363
- // Modify the sampleCrd to simulate the invalid CRD
364
- const invalidCrd = {
365
- ...sampleCrd,
366
- spec: {
367
- ...sampleCrd.spec,
368
- versions: [
369
- {
370
- name: "v1",
371
- served: true,
372
- storage: true,
373
- schema: undefined, // No OpenAPI schema
374
- },
375
- ],
376
- },
377
- };
378
-
379
- const options = {
380
- source: "mock-source",
381
- language: "ts",
382
- logFn: jest.fn(), // Mock log function
383
- directory: "test-dir",
384
- plain: false,
385
- npmPackage: "kubernetes-fluent-client",
386
- };
387
-
388
- // Call the convertCRDtoTS function with the invalid CRD
389
- const result = await convertCRDtoTS(invalidCrd, options);
390
-
391
- // Assert that result is empty due to invalid schema
392
- expect(result).toEqual([]);
393
-
394
- // Assert that the log function was called with the appropriate message
395
- expect(options.logFn).toHaveBeenCalledWith(
396
- "Skipping movies.example.com, it does not appear to have a valid schema",
397
- );
398
- });
399
- });