forked from finos/architecture-as-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.spec.ts
More file actions
415 lines (353 loc) · 17.8 KB
/
validate.spec.ts
File metadata and controls
415 lines (353 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import { Command } from 'commander';
import { Mock } from 'vitest';
import { getFormattedOutput, validate, exitBasedOffOfValidationOutcome, validationEnrichmentTest } from '@finos/calm-shared';
import { mkdirp } from 'mkdirp';
import { writeFileSync } from 'fs';
import path from 'path';
import { runValidate, writeOutputFile, checkValidateOptions, ValidateOptions } from './validate';
const dummyArch = { dummy: 'arch' };
const dummyPattern = { dummy: 'pattern' };
const dummyArchOfAPattern = { '$schema': 'pattern.json', dummy: 'arch' };
const dummyArchOfCalmSchema = { '$schema': 'calm-schema.json', dummy: 'arch' };
const dummyCalmSchema = { '$id': 'calm-schema.json', dummy: 'calm schema' };
const dummyTimeline = { '$schema': 'calm-timeline-schema.json', dummy: 'timeline' };
const dummyCalmTimelineSchema = { '$id': 'calm-timeline-schema.json', dummy: 'calm timeline schema' };
const mocks = vi.hoisted(() => ({
validate: vi.fn(),
getFormattedOutput: vi.fn(),
exitBasedOffOfValidationOutcome: vi.fn(),
initLogger: vi.fn(() => ({ error: vi.fn(), debug: vi.fn() })),
processExit: vi.fn(),
mkdirpSync: vi.fn(),
writeFileSync: vi.fn(),
parseDocumentLoaderConfig: vi.fn(),
buildDocumentLoader: vi.fn(() => ({
loadMissingDocument: mocks.loadMissingDocument
})),
loadSchemas: vi.fn(),
getSchema: vi.fn(),
loadMissingDocument: vi.fn()
}));
vi.mock('@finos/calm-shared', async () => ({
...(await vi.importActual('@finos/calm-shared')),
validate: mocks.validate,
getFormattedOutput: mocks.getFormattedOutput,
exitBasedOffOfValidationOutcome: mocks.exitBasedOffOfValidationOutcome,
initLogger: mocks.initLogger,
loadSchemas: mocks.loadSchemas,
buildDocumentLoader: mocks.buildDocumentLoader
}));
vi.mock('mkdirp', () => ({
mkdirp: { sync: mocks.mkdirpSync },
}));
vi.mock('fs', () => ({
...vi.importActual('fs'),
writeFileSync: mocks.writeFileSync,
}));
vi.mock('../cli', async () => ({
...(await vi.importActual('../cli')),
parseDocumentLoaderConfig: mocks.parseDocumentLoaderConfig,
buildSchemaDirectory: vi.fn(() => ({
loadSchemas: mocks.loadSchemas,
getSchema: mocks.getSchema
})),
}));
describe('runValidate', () => {
const fakeOutcome = { valid: true };
beforeEach(() => {
vi.resetAllMocks();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.exit = mocks.processExit as any;
mocks.parseDocumentLoaderConfig.mockResolvedValue({});
// Inline mock for loadMissingDocument
mocks.loadMissingDocument.mockImplementation((filePath: string, _: string) => {
if (filePath === 'arch.json') return Promise.resolve(dummyArch);
if (filePath === 'arch-of-pattern.json') return Promise.resolve(dummyArchOfAPattern);
if (filePath === 'arch-of-calm.json') return Promise.resolve(dummyArchOfCalmSchema);
if (filePath === 'pattern.json') return Promise.resolve(dummyPattern);
// Handle resolved absolute paths for $schema references
if (filePath.endsWith('pattern.json')) return Promise.resolve(dummyPattern);
if (filePath === 'timeline.json') return Promise.resolve(dummyTimeline);
return Promise.resolve();
});
mocks.getSchema.mockImplementation((schemaId: string) => {
// Handle both relative and resolved absolute paths
if (schemaId === 'calm-schema.json' || schemaId.endsWith('calm-schema.json')) return dummyCalmSchema;
if (schemaId === 'calm-timeline-schema.json' || schemaId.endsWith('calm-timeline-schema.json')) return dummyCalmTimelineSchema;
throw new Error(`Schema ${schemaId} not found`);
});
(validate as Mock).mockResolvedValue(fakeOutcome);
(getFormattedOutput as Mock).mockReturnValue('formatted output');
});
it('should process validation successfully with both architecture and pattern', async () => {
const options: ValidateOptions = {
architecturePath: 'arch.json',
patternPath: 'pattern.json',
metaSchemaPath: 'schemas',
verbose: true,
outputFormat: 'json',
outputPath: 'out.json',
strict: false,
};
await runValidate(options);
expect(mocks.loadSchemas).toHaveBeenCalled();
expect(mocks.loadMissingDocument).toHaveBeenCalledWith('arch.json', 'architecture');
expect(mocks.loadMissingDocument).toHaveBeenCalledWith('pattern.json', 'pattern');
expect(validate).toHaveBeenCalledWith(dummyArch, dummyPattern, undefined, expect.anything(), true);
expect(getFormattedOutput).toHaveBeenCalledWith(fakeOutcome, 'json', expect.anything());
expect(exitBasedOffOfValidationOutcome).toHaveBeenCalledWith(fakeOutcome, false);
expect(mkdirp.sync).toHaveBeenCalledWith(path.dirname('out.json'));
expect(writeFileSync).toHaveBeenCalledWith('out.json', 'formatted output');
});
it('should process validation successfully with architecture only', async () => {
const options: ValidateOptions = {
architecturePath: 'arch.json',
patternPath: undefined,
metaSchemaPath: 'schemas',
verbose: true,
outputFormat: 'json',
outputPath: 'out.json',
strict: false,
};
await runValidate(options);
expect(mocks.loadSchemas).toHaveBeenCalled();
expect(mocks.loadMissingDocument).toHaveBeenCalledWith('arch.json', 'architecture');
expect(validate).toHaveBeenCalledWith(dummyArch, undefined, undefined, expect.anything(), true);
expect(getFormattedOutput).toHaveBeenCalledWith(fakeOutcome, 'json', expect.anything());
expect(exitBasedOffOfValidationOutcome).toHaveBeenCalledWith(fakeOutcome, false);
expect(mkdirp.sync).toHaveBeenCalledWith(path.dirname('out.json'));
expect(writeFileSync).toHaveBeenCalledWith('out.json', 'formatted output');
});
it('should process validation successfully with architecture only and architecture has a pattern', async () => {
const options: ValidateOptions = {
architecturePath: 'arch-of-pattern.json',
patternPath: undefined,
metaSchemaPath: 'schemas',
verbose: true,
outputFormat: 'json',
outputPath: 'out.json',
strict: false,
};
await runValidate(options);
expect(mocks.loadSchemas).toHaveBeenCalled();
// $schema reference is resolved to absolute path relative to architecture file
const resolvedPatternPath = path.resolve(process.cwd(), 'pattern.json');
expect(mocks.getSchema).toHaveBeenCalledWith(resolvedPatternPath);
expect(mocks.loadMissingDocument).toHaveBeenCalledWith('arch-of-pattern.json', 'architecture');
expect(mocks.loadMissingDocument).toHaveBeenCalledWith(resolvedPatternPath, 'pattern');
expect(validate).toHaveBeenCalledWith(dummyArchOfAPattern, dummyPattern, undefined, expect.anything(), true);
expect(getFormattedOutput).toHaveBeenCalledWith(fakeOutcome, 'json', expect.anything());
expect(exitBasedOffOfValidationOutcome).toHaveBeenCalledWith(fakeOutcome, false);
expect(mkdirp.sync).toHaveBeenCalledWith(path.dirname('out.json'));
expect(writeFileSync).toHaveBeenCalledWith('out.json', 'formatted output');
});
it('should process validation successfully with architecture only and architecture references CALM schema', async () => {
const options: ValidateOptions = {
architecturePath: 'arch-of-calm.json',
patternPath: undefined,
metaSchemaPath: 'schemas',
verbose: true,
outputFormat: 'json',
outputPath: 'out.json',
strict: false,
};
await runValidate(options);
expect(mocks.loadSchemas).toHaveBeenCalled();
// $schema reference is resolved to absolute path relative to architecture file
const resolvedSchemaPath = path.resolve(process.cwd(), 'calm-schema.json');
expect(mocks.getSchema).toHaveBeenCalledWith(resolvedSchemaPath);
expect(mocks.loadMissingDocument).toHaveBeenCalledWith('arch-of-calm.json', 'architecture');
expect(mocks.loadMissingDocument).toHaveBeenCalledOnce();
expect(validate).toHaveBeenCalledWith(dummyArchOfCalmSchema, dummyCalmSchema, undefined, expect.anything(), true);
expect(getFormattedOutput).toHaveBeenCalledWith(fakeOutcome, 'json', expect.anything());
expect(exitBasedOffOfValidationOutcome).toHaveBeenCalledWith(fakeOutcome, false);
expect(mkdirp.sync).toHaveBeenCalledWith(path.dirname('out.json'));
expect(writeFileSync).toHaveBeenCalledWith('out.json', 'formatted output');
});
it('should process validation successfully with pattern only', async () => {
const options: ValidateOptions = {
architecturePath: undefined,
patternPath: 'pattern.json',
metaSchemaPath: 'schemas',
verbose: true,
outputFormat: 'json',
outputPath: 'out.json',
strict: false,
};
await runValidate(options);
expect(mocks.loadSchemas).toHaveBeenCalled();
expect(mocks.loadMissingDocument).toHaveBeenCalledWith('pattern.json', 'pattern');
expect(validate).toHaveBeenCalledWith(undefined, dummyPattern, undefined, expect.anything(), true);
expect(getFormattedOutput).toHaveBeenCalledWith(fakeOutcome, 'json', expect.anything());
expect(exitBasedOffOfValidationOutcome).toHaveBeenCalledWith(fakeOutcome, false);
expect(mkdirp.sync).toHaveBeenCalledWith(path.dirname('out.json'));
expect(writeFileSync).toHaveBeenCalledWith('out.json', 'formatted output');
});
it('should process validation successfully with timeline', async () => {
const options: ValidateOptions = {
architecturePath: undefined,
patternPath: undefined,
timelinePath: 'timeline.json',
metaSchemaPath: 'schemas',
verbose: true,
outputFormat: 'json',
outputPath: 'out.json',
strict: false,
};
await runValidate(options);
expect(mocks.loadSchemas).toHaveBeenCalled();
// $schema reference is resolved to absolute path relative to architecture file
const resolvedSchemaPath = path.resolve(process.cwd(), 'calm-timeline-schema.json');
expect(mocks.getSchema).toHaveBeenCalledWith(resolvedSchemaPath);
expect(mocks.loadMissingDocument).toHaveBeenCalledWith('timeline.json', 'timeline');
expect(validate).toHaveBeenCalledWith(undefined, dummyCalmTimelineSchema, dummyTimeline, expect.anything(), true);
expect(getFormattedOutput).toHaveBeenCalledWith(fakeOutcome, 'json', expect.anything());
expect(exitBasedOffOfValidationOutcome).toHaveBeenCalledWith(fakeOutcome, false);
expect(mkdirp.sync).toHaveBeenCalledWith(path.dirname('out.json'));
expect(writeFileSync).toHaveBeenCalledWith('out.json', 'formatted output');
});
it('should call process.exit(1) when an error occurs', async () => {
const options: ValidateOptions = {
architecturePath: 'arch.json',
patternPath: 'pattern.json',
metaSchemaPath: 'schemas',
verbose: true,
outputFormat: 'json',
outputPath: 'out.json',
strict: false,
};
mocks.parseDocumentLoaderConfig.mockResolvedValue({});
mocks.buildDocumentLoader.mockReturnValue({
loadMissingDocument: vi.fn((filePath: string) => {
if (filePath === 'arch.json') return dummyArch;
if (filePath === 'pattern.json') return dummyPattern;
return undefined;
})
});
const error = new Error('Validation failed');
(validate as Mock).mockRejectedValue(error);
await runValidate(options);
expect(mocks.processExit).toHaveBeenCalledWith(1);
});
});
describe('writeOutputFile', () => {
beforeEach(() => {
vi.resetAllMocks();
});
it('should write output to file if output is provided', () => {
const output = 'dir/out.txt';
const content = 'some content';
writeOutputFile(output, content);
expect(mkdirp.sync).toHaveBeenCalledWith(path.dirname(output));
expect(writeFileSync).toHaveBeenCalledWith(output, content);
});
it('should write output to stdout if no output is provided', () => {
const content = 'stdout content';
const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
writeOutputFile('', content);
expect(stdoutSpy).toHaveBeenCalledWith(content);
stdoutSpy.mockRestore();
});
});
describe('checkValidateOptions', () => {
it('should call program.error if neither pattern, architecture nor timeline is provided', () => {
const program = new Command();
const errorSpy = vi.spyOn(program, 'error').mockImplementation((msg: string) => { throw new Error(msg); });
const options = {};
expect(() => checkValidateOptions(program, options, '-p, --pattern <file>',
'-a, --architecture <file>', '--timeline <file>')).toThrow(/one of the required options/);
errorSpy.mockRestore();
});
it('should not call program.error if a pattern is provided', () => {
const program = new Command();
const errorSpy = vi.spyOn(program, 'error').mockImplementation((msg: string) => { throw new Error(msg); });
const options = { pattern: 'pattern.json' };
expect(() => checkValidateOptions(program, options, '-p, --pattern <file>',
'-a, --architecture <file>', '--timeline <file>')).not.toThrow();
errorSpy.mockRestore();
});
it('should not call program.error if an architecture is provided', () => {
const program = new Command();
const errorSpy = vi.spyOn(program, 'error').mockImplementation((msg: string) => { throw new Error(msg); });
const options = { architecture: 'arch.json' };
expect(() => checkValidateOptions(program, options, '-p, --pattern <file>',
'-a, --architecture <file>', '--timeline <file>')).not.toThrow();
errorSpy.mockRestore();
});
it('should call program.error if pattern and timeline are provided', () => {
const program = new Command();
const errorSpy = vi.spyOn(program, 'error').mockImplementation((msg: string) => { throw new Error(msg); });
const options = { pattern: 'pattern.json', timeline: 'timeline.json' };
expect(() => checkValidateOptions(program, options, '-p, --pattern <file>',
'-a, --architecture <file>', '--timeline <file>')).toThrow(/cannot be used with either of the options/);
errorSpy.mockRestore();
});
it('should call program.error if architecture and timeline are provided', () => {
const program = new Command();
const errorSpy = vi.spyOn(program, 'error').mockImplementation((msg: string) => { throw new Error(msg); });
const options = { architecture: 'arch.json', timeline: 'timeline.json' };
expect(() => checkValidateOptions(program, options, '-p, --pattern <file>',
'-a, --architecture <file>', '--timeline <file>')).toThrow(/cannot be used with either of the options/);
errorSpy.mockRestore();
});
it('should not call program.error if an timeline is provided', () => {
const program = new Command();
const errorSpy = vi.spyOn(program, 'error').mockImplementation((msg: string) => { throw new Error(msg); });
const options = { timeline: 'timeline.json' };
expect(() => checkValidateOptions(program, options, '-p, --pattern <file>',
'-a, --architecture <file>', '--timeline <file>')).not.toThrow();
errorSpy.mockRestore();
});
});
describe('rewritePathWithIds', () => {
const { rewritePathWithIds } = validationEnrichmentTest;
const document = {
nodes: [
{
'unique-id': 'api-producer',
interfaces: [
{
'unique-id': 'producer-ingress',
port: 8080
},
{
'unique-id': 'http-config',
config: {
targets: [
{ 'unique-id': 'target-a', url: 'a' },
{ url: 'b' }
]
}
}
]
},
{
interfaces: [
{
port: 9090
}
]
}
],
meta: { id: 'root' }
} as const;
it('rewrites simple object paths unchanged', () => {
expect(rewritePathWithIds('/meta/id', document)).toBe('/meta/id');
});
it('uses array unique-ids when present', () => {
expect(rewritePathWithIds('/nodes/0/interfaces/0/port', document))
.toBe('/nodes/api-producer/interfaces/producer-ingress/port');
});
it('falls back to array index when no unique-id is present', () => {
expect(rewritePathWithIds('/nodes/1/interfaces/0/port', document))
.toBe('/nodes/1/interfaces/0/port');
});
it('handles nested array segments combining ids and indexes', () => {
expect(rewritePathWithIds('/nodes/0/interfaces/1/config/targets/1/url', document))
.toBe('/nodes/api-producer/interfaces/http-config/config/targets/1/url');
});
it('returns undefined when pointer path is empty or data missing', () => {
expect(rewritePathWithIds('', document)).toBeUndefined();
expect(rewritePathWithIds('/anything', undefined)).toBeUndefined();
});
});