-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathopenapi-restful.test.ts
400 lines (327 loc) · 12.9 KB
/
openapi-restful.test.ts
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
/* eslint-disable @typescript-eslint/no-explicit-any */
/// <reference types="@types/jest" />
import OpenAPIParser from '@readme/openapi-parser';
import { getLiteral, getObjectLiteral } from '@zenstackhq/sdk';
import { Model, Plugin, isPlugin } from '@zenstackhq/sdk/ast';
import { loadZModelAndDmmf, normalizePath } from '@zenstackhq/testtools';
import fs from 'fs';
import path from 'path';
import * as tmp from 'tmp';
import YAML from 'yaml';
import generate from '../src';
tmp.setGracefulCleanup();
describe('Open API Plugin RESTful Tests', () => {
it('run plugin', async () => {
for (const specVersion of ['3.0.0', '3.1.0']) {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '${specVersion}'
}
enum role {
USER
ADMIN
}
model User {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
role role @default(USER)
posts post_Item[]
profile Profile?
likes PostLike[]
}
model Profile {
id String @id @default(cuid())
image String?
user User @relation(fields: [userId], references: [id])
userId String @unique
}
model post_Item {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
author User? @relation(fields: [authorId], references: [id])
authorId String?
published Boolean @default(false)
viewCount Int @default(0)
notes String?
likes PostLike[]
@@openapi.meta({
tagDescription: 'Post-related operations'
})
}
model PostLike {
post post_Item @relation(fields: [postId], references: [id])
postId String
user User @relation(fields: [userId], references: [id])
userId String
@@id([postId, userId])
}
model Foo {
id String @id
@@openapi.ignore
}
model Bar {
id String @id
@@ignore
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output, specVersion);
await generate(model, options, dmmf);
console.log(`OpenAPI specification generated for ${specVersion}: ${output}`);
const api = await OpenAPIParser.validate(output);
expect(api.tags).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: 'user', description: 'User operations' }),
expect.objectContaining({ name: 'post_Item', description: 'Post-related operations' }),
])
);
expect(api.paths?.['/user']?.['get']).toBeTruthy();
expect(api.paths?.['/user']?.['post']).toBeTruthy();
expect(api.paths?.['/user']?.['put']).toBeFalsy();
expect(api.paths?.['/user/{id}']?.['get']).toBeTruthy();
expect(api.paths?.['/user/{id}']?.['patch']).toBeTruthy();
expect(api.paths?.['/user/{id}']?.['delete']).toBeTruthy();
expect(api.paths?.['/user/{id}/posts']?.['get']).toBeTruthy();
expect(api.paths?.['/user/{id}/relationships/posts']?.['get']).toBeTruthy();
expect(api.paths?.['/user/{id}/relationships/posts']?.['post']).toBeTruthy();
expect(api.paths?.['/user/{id}/relationships/posts']?.['patch']).toBeTruthy();
expect(api.paths?.['/user/{id}/relationships/likes']?.['get']).toBeTruthy();
expect(api.paths?.['/user/{id}/relationships/likes']?.['post']).toBeTruthy();
expect(api.paths?.['/user/{id}/relationships/likes']?.['patch']).toBeTruthy();
expect(api.paths?.['/post_Item/{id}/relationships/author']?.['get']).toBeTruthy();
expect(api.paths?.['/post_Item/{id}/relationships/author']?.['post']).toBeUndefined();
expect(api.paths?.['/post_Item/{id}/relationships/author']?.['patch']).toBeTruthy();
expect(api.paths?.['/post_Item/{id}/relationships/likes']?.['get']).toBeTruthy();
expect(api.paths?.['/post_Item/{id}/relationships/likes']?.['post']).toBeTruthy();
expect(api.paths?.['/post_Item/{id}/relationships/likes']?.['patch']).toBeTruthy();
expect(api.paths?.['/foo']).toBeUndefined();
expect(api.paths?.['/bar']).toBeUndefined();
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe(specVersion);
const baseline = YAML.parse(
fs.readFileSync(`${__dirname}/baseline/rest-${specVersion}.baseline.yaml`, 'utf-8')
);
expect(parsed).toMatchObject(baseline);
}
});
it('options', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '3.0.0'
title = 'My Awesome API'
version = '1.0.0'
description = 'awesome api'
prefix = '/myapi'
}
model User {
id String @id
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe('3.0.0');
const api = await OpenAPIParser.validate(output);
expect(api.info).toEqual(
expect.objectContaining({
title: 'My Awesome API',
version: '1.0.0',
description: 'awesome api',
})
);
expect(api.paths?.['/myapi/user']).toBeTruthy();
});
it('security schemes valid', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' },
myBearer: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
myApiKey: { type: 'apiKey', in: 'header', name: 'X-API-KEY' }
}
}
model User {
id String @id
posts Post[]
}
model Post {
id String @id
author User @relation(fields: [authorId], references: [id])
authorId String
@@allow('read', true)
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.components.securitySchemes).toEqual(
expect.objectContaining({
myBasic: { type: 'http', scheme: 'basic' },
myBearer: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
myApiKey: { type: 'apiKey', in: 'header', name: 'X-API-KEY' },
})
);
expect(parsed.security).toEqual(expect.arrayContaining([{ myBasic: [] }, { myBearer: [] }]));
const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user']?.['get']?.security).toBeUndefined();
expect(api.paths?.['/user/{id}/posts']?.['get']?.security).toEqual([]);
expect(api.paths?.['/post']?.['get']?.security).toEqual([]);
expect(api.paths?.['/post']?.['post']?.security).toBeUndefined();
});
it('security model level override', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' }
}
}
model User {
id String @id
value Int
@@allow('all', value > 0)
@@openapi.meta({
security: []
})
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user']?.['get']?.security).toHaveLength(0);
expect(api.paths?.['/user/{id}']?.['put']?.security).toHaveLength(0);
});
it('security schemes invalid', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'invalid', scheme: 'basic' }
}
}
model User {
id String @id
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await expect(generate(model, options, dmmf)).rejects.toEqual(
expect.objectContaining({ message: expect.stringContaining('"securitySchemes" option is invalid') })
);
});
it('ignored model used as relation', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
}
model User {
id String @id
email String @unique
posts Post[]
}
model Post {
id String @id
title String
author User? @relation(fields: [authorId], references: [id])
authorId String?
@@openapi.ignore()
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output, '3.1.0');
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
await OpenAPIParser.validate(output);
});
it('field type coverage', async () => {
for (const specVersion of ['3.0.0', '3.1.0']) {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '${specVersion}'
}
model Foo {
id String @id @default(cuid())
string String
int Int
bigInt BigInt
date DateTime
float Float
decimal Decimal
boolean Boolean
bytes Bytes
@@allow('all', true)
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output, specVersion);
await generate(model, options, dmmf);
console.log(`OpenAPI specification generated for ${specVersion}: ${output}`);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe(specVersion);
const baseline = YAML.parse(
fs.readFileSync(`${__dirname}/baseline/rest-type-coverage-${specVersion}.baseline.yaml`, 'utf-8')
);
expect(parsed).toMatchObject(baseline);
}
});
it('int field as id', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
}
model Foo {
id Int @id @default(autoincrement())
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output, '3.0.0');
await generate(model, options, dmmf);
console.log(`OpenAPI specification generated: ${output}`);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.components.schemas.Foo.properties.id.type).toBe('integer');
});
it('exposes individual fields from a compound id as attributes', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
}
model User {
email String
role String
company String
@@id([role, company])
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output, '3.1.0');
await generate(model, options, dmmf);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe('3.1.0');
expect(Object.keys(parsed.components.schemas.User.properties.attributes.properties)).toEqual(
expect.arrayContaining(['role', 'company'])
);
});
});
function buildOptions(model: Model, modelFile: string, output: string, specVersion = '3.0.0') {
const optionFields = model.declarations.find((d): d is Plugin => isPlugin(d))?.fields || [];
const options: any = { schemaPath: modelFile, output, specVersion, flavor: 'rest' };
optionFields.forEach((f) => (options[f.name] = getLiteral(f.value) ?? getObjectLiteral(f.value)));
return options;
}