-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema_test.lua
More file actions
518 lines (425 loc) · 15 KB
/
schema_test.lua
File metadata and controls
518 lines (425 loc) · 15 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
-- schema_test.lua — test suite for schema.lua
local s = require("schema")
local passed = 0
local failed = 0
local function test(name, fn)
local ok, err = pcall(fn)
if ok then
passed = passed + 1
print(" PASS " .. name)
else
failed = failed + 1
print(" FAIL " .. name)
print(" " .. tostring(err))
end
end
local function assert_ok(val, errors)
if errors then
local msgs = {}
for _, e in ipairs(errors) do msgs[#msgs + 1] = e.message end
error("expected success but got errors: " .. table.concat(msgs, "; "))
end
return val
end
local function assert_err(val, errors, pattern)
_ = val
if not errors then error("expected validation error but got success") end
if pattern then
local msgs = {}
for _, e in ipairs(errors) do msgs[#msgs + 1] = e.message end
local combined = table.concat(msgs, " | ")
if not combined:find(pattern) then
error("expected error matching '" .. pattern .. "', got: " .. combined)
end
end
end
print("=== String tests ===")
test("string accepts string", function()
local v, errs = s.string():parse("hello")
assert_ok(v, errs)
assert(v == "hello")
end)
test("string rejects number", function()
local v, errs = s.string():parse(42)
assert_err(v, errs, "expected string")
end)
test("string:min passes", function()
local v, errs = s.string():min(3):parse("hello")
assert_ok(v, errs)
end)
test("string:min fails", function()
local v, errs = s.string():min(10):parse("hi")
assert_err(v, errs, "too short")
end)
test("string:max passes", function()
local v, errs = s.string():max(10):parse("hello")
assert_ok(v, errs)
end)
test("string:max fails", function()
local v, errs = s.string():max(3):parse("toolong")
assert_err(v, errs, "too long")
end)
test("string:pattern passes", function()
local v, errs = s.string():pattern("^%d+$"):parse("12345")
assert_ok(v, errs)
end)
test("string:pattern fails", function()
local v, errs = s.string():pattern("^%d+$"):parse("abc")
assert_err(v, errs, "pattern")
end)
test("string:email passes", function()
local v, errs = s.string():email():parse("user@example.com")
assert_ok(v, errs)
end)
test("string:email fails", function()
local v, errs = s.string():email():parse("notanemail")
assert_err(v, errs)
end)
test("string:trim transform", function()
local v, errs = s.string():trim():parse(" hello ")
assert_ok(v, errs)
assert(v == "hello", "expected 'hello', got '" .. tostring(v) .. "'")
end)
test("string:lower transform", function()
local v, errs = s.string():lower():parse("HELLO")
assert_ok(v, errs)
assert(v == "hello")
end)
test("string optional nil passes", function()
local v, errs = s.string():optional():parse(nil)
assert(errs == nil, "expected no errors")
assert(v == nil)
end)
test("string required nil fails", function()
local v, errs = s.string():parse(nil)
assert_err(v, errs, "required")
end)
print("\n=== Number tests ===")
test("number accepts number", function()
local v, errs = s.number():parse(42)
assert_ok(v, errs)
assert(v == 42)
end)
test("number rejects string", function()
local v, errs = s.number():parse("42")
assert_err(v, errs, "expected number")
end)
test("number:min passes", function()
local v, errs = s.number():min(0):parse(5)
assert_ok(v, errs)
end)
test("number:min fails", function()
local v, errs = s.number():min(10):parse(5)
assert_err(v, errs, "too small")
end)
test("number:max passes", function()
local v, errs = s.number():max(100):parse(50)
assert_ok(v, errs)
end)
test("number:max fails", function()
local v, errs = s.number():max(10):parse(100)
assert_err(v, errs, "too large")
end)
test("number:int passes on integer", function()
local v, errs = s.number():int():parse(5)
assert_ok(v, errs)
end)
test("number:int fails on float", function()
local v, errs = s.number():int():parse(3.14)
assert_err(v, errs, "integer")
end)
test("number:positive passes", function()
local v, errs = s.number():positive():parse(1)
assert_ok(v, errs)
end)
test("number:positive fails on zero", function()
local v, errs = s.number():positive():parse(0)
assert_err(v, errs, "positive")
end)
print("\n=== Boolean tests ===")
test("boolean accepts true", function()
local v, errs = s.boolean():parse(true)
assert_ok(v, errs)
assert(v == true)
end)
test("boolean accepts false", function()
local v, errs = s.boolean():parse(false)
assert_ok(v, errs)
assert(v == false)
end)
test("boolean rejects string", function()
local v, errs = s.boolean():parse("true")
assert_err(v, errs, "expected boolean")
end)
print("\n=== Table/object tests ===")
test("table validates shape", function()
local UserSchema = s.table({
name = s.string(),
age = s.number():int():min(0),
})
local v, errs = UserSchema:parse({ name = "Alice", age = 30 })
assert_ok(v, errs)
assert(v.name == "Alice")
assert(v.age == 30)
end)
test("table fails on missing required field", function()
local UserSchema = s.table({ name = s.string(), age = s.number() })
local v, errs = UserSchema:parse({ name = "Alice" })
assert_err(v, errs, "age")
end)
test("table optional field passes when absent", function()
local UserSchema = s.table({ name = s.string(), bio = s.string():optional() })
local v, errs = UserSchema:parse({ name = "Alice" })
assert_ok(v, errs)
end)
test("table nested schema", function()
local AddrSchema = s.table({ city = s.string(), zip = s.string() })
local UserSchema = s.table({ name = s.string(), address = AddrSchema })
local v, errs = UserSchema:parse({ name = "Bob", address = { city = "NYC", zip = "10001" } })
assert_ok(v, errs)
assert(v.address.city == "NYC")
end)
test("table strict mode rejects extra keys", function()
local Schema = s.table({ name = s.string() }):strict()
local v, errs = Schema:parse({ name = "Alice", extra = "oops" })
assert_err(v, errs, "unexpected key")
end)
test("table passes through extra keys in non-strict mode", function()
local Schema = s.table({ name = s.string() })
local v, errs = Schema:parse({ name = "Alice", extra = "ok" })
assert_ok(v, errs)
assert(v.extra == "ok")
end)
print("\n=== Array tests ===")
test("array validates items", function()
local Schema = s.array(s.string())
local v, errs = Schema:parse({ "a", "b", "c" })
assert_ok(v, errs)
assert(#v == 3)
end)
test("array fails when item invalid", function()
local Schema = s.array(s.number())
local v, errs = Schema:parse({ 1, 2, "three" })
assert_err(v, errs, "expected number")
end)
test("array:min passes", function()
local v, errs = s.array(s.number()):min(2):parse({ 1, 2, 3 })
assert_ok(v, errs)
end)
test("array:min fails", function()
local v, errs = s.array(s.number()):min(5):parse({ 1, 2 })
assert_err(v, errs, "too short")
end)
test("array:nonempty fails on empty", function()
local v, errs = s.array(s.string()):nonempty():parse({})
assert_err(v, errs)
end)
test("array without item schema accepts any", function()
local v, errs = s.array():parse({ 1, "two", true })
assert_ok(v, errs)
end)
print("\n=== Enum tests ===")
test("enum accepts valid value", function()
local Schema = s.enum({ "admin", "user", "guest" })
local v, errs = Schema:parse("admin")
assert_ok(v, errs)
assert(v == "admin")
end)
test("enum rejects invalid value", function()
local Schema = s.enum({ "admin", "user", "guest" })
local v, errs = Schema:parse("superuser")
assert_err(v, errs, "one of")
end)
print("\n=== Union tests ===")
test("union accepts first matching type", function()
local Schema = s.union({ s.string(), s.number() })
local v, errs = Schema:parse("hello")
assert_ok(v, errs)
assert(v == "hello")
end)
test("union accepts second matching type", function()
local Schema = s.union({ s.string(), s.number() })
local v, errs = Schema:parse(42)
assert_ok(v, errs)
assert(v == 42)
end)
test("union fails when no type matches", function()
local Schema = s.union({ s.string(), s.number() })
local v, errs = Schema:parse(true)
assert_err(v, errs)
end)
print("\n=== Literal tests ===")
test("literal accepts exact value", function()
local v, errs = s.literal("hello"):parse("hello")
assert_ok(v, errs)
end)
test("literal rejects different value", function()
local v, errs = s.literal("hello"):parse("world")
assert_err(v, errs, "literal")
end)
print("\n=== Custom message tests ===")
test("custom message on string type error", function()
local v, errs = s.string():message("name must be a string"):parse(42)
assert_err(v, errs, "name must be a string")
end)
print("\n=== schema.parse (throw) ===")
test("schema.parse returns value on success", function()
local v = s.parse(s.string(), "hello")
assert(v == "hello")
end)
test("schema.parse throws on failure", function()
local ok, err = pcall(function()
s.parse(s.string(), 42)
end)
assert(not ok, "expected error to be thrown")
assert(err:find("validation failed"), "expected 'validation failed' in: " .. err)
end)
print("\n=== schema.safe_parse ===")
test("safe_parse returns ok=true on success", function()
local ok, val = s.safe_parse(s.number(), 42)
assert(ok == true)
assert(val == 42)
end)
test("safe_parse returns ok=false on failure", function()
local ok, val, errs = s.safe_parse(s.number(), "not a number")
assert(ok == false)
assert(val == nil)
assert(errs ~= nil)
end)
-- ─── Summary ──────────────────────────────────────────────────────────────────
print("\n" .. string.rep("─", 40))
print(string.format(" %d passed, %d failed", passed, failed))
if failed > 0 then
os.exit(1)
end
test("nested optional field absent passes", function()
local Schema = s.table({ meta = s.table({ tags = s.array(s.string()):optional() }) })
local v, errs = Schema:parse({ meta = {} })
assert_ok(v, errs)
end)
test("enum required nil fails", function()
local Schema = s.enum({ "a", "b", "c" })
local v, errs = Schema:parse(nil)
assert_err(v, errs, "required")
end)
test("union optional passes nil", function()
local Schema = s.union({ s.string(), s.number() }):optional()
local v, errs = Schema:parse(nil)
assert(errs == nil)
end)
test("literal rejects wrong type entirely", function()
local v, errs = s.literal(42):parse("42")
assert_err(v, errs, "literal")
end)
test("table extend adds new fields", function()
local Base = s.table({ name = s.string() })
local Extended = Base:extend({ age = s.number() })
local v, errs = Extended:parse({ name = "Alice", age = 25 })
assert_ok(v, errs)
assert(v.age == 25)
end)
test("safe_parse errors table has path field", function()
local ok, _, errs = s.safe_parse(s.table({ x = s.number() }), { x = "bad" })
assert(ok == false)
assert(errs ~= nil and errs[1].path ~= nil)
end)
test("array no schema passes heterogeneous input", function()
local v, errs = s.array():parse({ 1, "two", false, {} })
assert_ok(v, errs)
assert(#v == 4)
end)
test("boolean does not coerce string", function()
local v, errs = s.boolean():parse("true")
assert_err(v, errs, "expected boolean")
end)
test("union custom message surfaces on failure", function()
local Schema = s.union({ s.string(), s.number() }):message("must be string or number")
local v, errs = Schema:parse(true)
assert_err(v, errs, "must be string or number")
end)
test("number coerce from string", function()
local v, errs = s.number():coerce():parse("3.14")
assert_ok(v, errs)
assert(v == 3.14)
end)
test("table preserves unrecognised keys in non-strict mode", function()
local Schema = s.table({ id = s.number() })
local v, errs = Schema:parse({ id = 1, label = "x", active = true })
assert_ok(v, errs)
assert(v.label == "x" and v.active == true)
end)
test("array item error path includes index", function()
local Schema = s.array(s.number())
local _, errs = Schema:parse({ 1, "bad", 3 })
assert(errs ~= nil)
assert(errs[1].path:find("%[2%]"), "expected path to contain [2]")
end)
test("literal accepts boolean literal", function()
local v, errs = s.literal(true):parse(true)
assert_ok(v, errs)
assert(v == true)
end)
test("number int rejects infinity", function()
local v, errs = s.number():int():parse(math.huge)
assert_err(v, errs, "integer")
end)
test("parse throws error containing field path", function()
local ok, err = pcall(function()
s.parse(s.table({ name = s.string() }), { name = 99 })
end)
assert(not ok)
assert(err:find("name"), "expected field name in error: " .. tostring(err))
end)
test("missing required string error path is root", function()
local _, errs = s.string():parse(nil)
assert(errs ~= nil and errs[1].path == ".", "expected path ., got: " .. tostring(errs and errs[1].path))
end)
test("number min boundary is inclusive", function()
local v, errs = s.number():min(5):parse(5)
assert_ok(v, errs)
assert(v == 5)
end)
test("array max constraint fails when exceeded", function()
local Schema = s.array(s.number()):max(3)
local v, errs = Schema:parse({ 1, 2, 3, 4 })
assert_err(v, errs, "too long")
end)
test("table field with numeric string key", function()
local Schema = s.table({ ["1"] = s.string() })
local v, errs = Schema:parse({ ["1"] = "one" })
assert_ok(v, errs)
assert(v["1"] == "one")
end)
test("nested table collects multiple errors", function()
local Schema = s.table({ a = s.number(), b = s.string() })
local _, errs = Schema:parse({ a = "bad", b = 42 })
assert(errs ~= nil and #errs == 2, "expected 2 errors, got " .. tostring(errs and #errs))
end)
test("number coerce from non-numeric string returns original", function()
-- tonumber("abc") returns nil; coerce falls back to original value
local v, _ = s.number():coerce():parse("abc")
assert(v == "abc", "expected fallback to original value")
end)
test("enum accepts all declared values", function()
local vals = { "r", "g", "b", "a" }
local Schema = s.enum(vals)
for _, val in ipairs(vals) do
local v, errs = Schema:parse(val)
assert_ok(v, errs)
end
end)
test("strict table rejects extra key with error", function()
local Schema = s.table({ name = s.string() }):strict()
local _, errs = Schema:parse({ name = "x", extra = "y" })
assert(errs ~= nil, "expected validation errors from strict mode")
end)
test("nullable string accepts nil value", function()
local v, errs = s.string():nullable():parse(nil)
assert(errs == nil, "nullable should accept nil")
end)
test("array min error message includes counts", function()
local _, errs = s.array(s.string()):min(5):parse({ "a", "b" })
assert(errs ~= nil)
local msg = errs[1].message
assert(msg:find("2"), "expected actual count in message: " .. msg)
end)