-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathcustom-validation.test.ts
More file actions
335 lines (281 loc) · 11.4 KB
/
custom-validation.test.ts
File metadata and controls
335 lines (281 loc) · 11.4 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
import { createTestClient, loadSchemaWithError } from '@zenstackhq/testtools';
import { describe, expect, it } from 'vitest';
describe('Custom validation tests', () => {
it('works with custom validation', async () => {
const db = await createTestClient(
`
model Foo {
id Int @id @default(autoincrement())
str1 String?
str2 String?
str3 String?
str4 String?
str5 String?
str6 String?
int1 Int?
list1 Int[]
list2 Int[]
list3 Int[]
@@validate(
(str1 == null || (length(str1) >= 8 && length(str1) <= 10))
&& (int1 == null || (int1 > 1 && int1 < 4)),
'invalid fields')
@@validate(str1 == null || (startsWith(str1, 'a') && endsWith(str1, 'm') && contains(str1, 'b')), 'invalid fields')
@@validate(str2 == null || regex(str2, '^x.*z$'), 'invalid str2')
@@validate(str3 == null || isEmail(str3), 'invalid str3')
@@validate(str4 == null || isUrl(str4), 'invalid str4')
@@validate(str5 == null || isDateTime(str5), 'invalid str5')
@@validate(str6 == null || isPhone(str6), 'invalid str6')
@@validate(list1 == null || (has(list1, 1) && hasSome(list1, [2, 3]) && hasEvery(list1, [4, 5])), 'invalid list1')
@@validate(list2 == null || isEmpty(list2), 'invalid list2', ['x', 'y'])
@@validate(list3 == null || length(list3) <2 , 'invalid list3')
}
`,
{ provider: 'postgresql' },
);
await db.foo.create({ data: { id: 100 } });
for (const action of ['create', 'update']) {
const _t =
action === 'create'
? (data: any) => db.foo.create({ data })
: (data: any) => db.foo.update({ where: { id: 100 }, data });
// violates length
await expect(_t({ str1: 'abd@efg.com' })).toBeRejectedByValidation(['invalid fields']);
await expect(_t({ str1: 'a@b.c' })).toBeRejectedByValidation(['invalid fields']);
// violates int1 > 1
await expect(_t({ int1: 1 })).toBeRejectedByValidation(['invalid fields']);
// violates startsWith
await expect(_t({ str1: 'b@cd.com' })).toBeRejectedByValidation(['invalid fields']);
// violates endsWith
await expect(_t({ str1: 'a@b.gov' })).toBeRejectedByValidation(['invalid fields']);
// violates contains
await expect(_t({ str1: 'a@cd.com' })).toBeRejectedByValidation(['invalid fields']);
// violates regex
await expect(_t({ str2: 'xab' })).toBeRejectedByValidation(['invalid str2']);
// violates email
await expect(_t({ str3: 'not-an-email' })).toBeRejectedByValidation(['invalid str3']);
// violates url
await expect(_t({ str4: 'not-an-url' })).toBeRejectedByValidation(['invalid str4']);
// violates datetime
await expect(_t({ str5: 'not-an-datetime' })).toBeRejectedByValidation(['invalid str5']);
// violates phone
await expect(_t({ str6: 'not-a-phone' })).toBeRejectedByValidation(['invalid str6']);
// violates has
await expect(_t({ list1: [2, 3, 4, 5] })).toBeRejectedByValidation(['invalid list1']);
// violates hasSome
await expect(_t({ list1: [1, 4, 5] })).toBeRejectedByValidation(['invalid list1']);
// violates hasEvery
await expect(_t({ list1: [1, 2, 3, 4] })).toBeRejectedByValidation(['invalid list1']);
// violates isEmpty
let thrown = false;
try {
await _t({ list2: [1] });
} catch (err) {
thrown = true;
expect((err as any).cause.issues[0].path).toEqual(['data', 'x', 'y']);
}
expect(thrown).toBe(true);
// validates list length
await expect(_t({ list3: [1, 2] })).toBeRejectedByValidation(['invalid list3']);
// satisfies all
await expect(
_t({
str1: 'ab12345m',
str2: 'x...z',
str3: 'ab@c.com',
str4: 'http://a.b.c',
str5: new Date().toISOString(),
str6: '+15555555555',
int1: 2,
list1: [1, 2, 4, 5],
list2: [],
list3: [1],
}),
).toResolveTruthy();
}
});
it('disabling validation makes validation attributes ineffective', async () => {
const db = await createTestClient(
`
model User {
id Int @id @default(autoincrement())
email String @unique @email
@@validate(length(email) >= 8)
@@allow('all', true)
}
`,
);
await expect(
db.user.create({
data: {
email: 'xyz',
},
}),
).toBeRejectedByValidation();
await expect(
db.user.create({
data: {
email: 'a@b.com',
},
}),
).toBeRejectedByValidation();
const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false });
await expect(
dbNoValidation.user.create({
data: {
id: 1,
email: 'xyz',
},
}),
).toResolveTruthy();
await expect(
dbNoValidation.user.update({
where: { id: 1 },
data: {
email: 'a@b.com',
},
}),
).toResolveTruthy();
// original client not affected
await expect(
db.user.create({
data: {
email: 'xyz',
},
}),
).toBeRejectedByValidation();
await expect(
db.user.create({
data: {
email: 'a@b.com',
},
}),
).toBeRejectedByValidation();
});
it('disabling validation skips structural validation for all CRUD operations', async () => {
const db = await createTestClient(
`
model User {
id Int @id @default(autoincrement())
email String
name String
}
`,
);
const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false });
// Helper: assert that a promise rejects but NOT with a Zod-based validation error
// (the cause of a Zod validation error is a ZodError)
const expectNonValidationError = async (promise: Promise<unknown>) => {
try {
await promise;
} catch (err: any) {
if (err.reason === 'invalid-input') {
expect(err.cause?.constructor?.name).not.toBe('ZodError');
}
return;
}
// resolving is also acceptable — it means validation was skipped and the ORM handled it
};
// create - missing required "data" is normally rejected by Zod validation
await expect(db.user.create({} as any)).toBeRejectedByValidation();
// with validation disabled, it skips Zod validation
await expectNonValidationError(dbNoValidation.user.create({} as any));
// update - missing required "where" is normally rejected by Zod validation
await expect(db.user.update({ data: { email: 'new@b.com' } } as any)).toBeRejectedByValidation();
await expectNonValidationError(dbNoValidation.user.update({ data: { email: 'new@b.com' } } as any));
// delete - missing required "where" is normally rejected by Zod validation
await expect(db.user.delete({} as any)).toBeRejectedByValidation();
await expectNonValidationError(dbNoValidation.user.delete({} as any));
// upsert - missing required fields is normally rejected by Zod validation
await expect(db.user.upsert({} as any)).toBeRejectedByValidation();
await expectNonValidationError(dbNoValidation.user.upsert({} as any));
});
it('$setInputValidation toggles validation', async () => {
const db = await createTestClient(
`
model Item {
id Int @id @default(autoincrement())
url String @url
}
`,
);
// validation enabled by default
await expect(db.item.create({ data: { url: 'not-a-url' } })).toBeRejectedByValidation();
// disable via $setInputValidation
const dbDisabled = db.$setInputValidation(false);
await expect(dbDisabled.item.create({ data: { url: 'not-a-url' } })).toResolveTruthy();
// re-enable via $setInputValidation
const dbReEnabled = dbDisabled.$setInputValidation(true);
await expect(dbReEnabled.item.create({ data: { url: 'still-not-a-url' } })).toBeRejectedByValidation();
// valid data should work with re-enabled validation
await expect(dbReEnabled.item.create({ data: { url: 'https://example.com' } })).toResolveTruthy();
});
it('disabling validation at client creation time', async () => {
const db = await createTestClient(
`
model Post {
id Int @id @default(autoincrement())
title String @length(min: 5)
}
`,
{ validateInput: false },
);
// should skip validation since validateInput is false from the start
await expect(db.post.create({ data: { id: 1, title: 'ab' } })).toResolveTruthy();
// re-enable validation
const dbValidated = db.$setInputValidation(true);
await expect(dbValidated.post.create({ data: { title: 'ab' } })).toBeRejectedByValidation();
});
it('checks arg type for validation functions', async () => {
// length() on relation field
await loadSchemaWithError(
`
model Foo {
id Int @id @default(autoincrement())
bars Bar[]
@@validate(length(bars) > 0)
}
model Bar {
id Int @id @default(autoincrement())
foo Foo @relation(fields: [fooId], references: [id])
fooId Int
}
`,
'argument must be a string or list field',
);
// length() on non-string/list field
await loadSchemaWithError(
`
model Foo {
id Int @id @default(autoincrement())
x Int
@@validate(length(x) > 0)
}
`,
'argument must be a string or list field',
);
// invalid regex pattern
await loadSchemaWithError(
`
model Foo {
id Int @id @default(autoincrement())
x String
@@validate(regex(x, '[abc'))
}
`,
'invalid regular expression',
);
// using field as regex pattern
await loadSchemaWithError(
`
model Foo {
id Int @id @default(autoincrement())
x String
y String
@@validate(regex(x, y))
}
`,
'second argument must be a string literal',
);
});
});