-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathzod_test.go
More file actions
1432 lines (1246 loc) · 41.3 KB
/
zod_test.go
File metadata and controls
1432 lines (1246 loc) · 41.3 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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package zen
import (
"fmt"
"reflect"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/xorcare/golden"
)
// goldenAssert wraps golden.Assert, prepending metadata comments to the file.
// The metadata is used by the docker type-check script to determine which zod
// version to install and whether to include the file in type checking.
//
// All golden files are type-checked by default.
func goldenAssert(t *testing.T, data string, version string) {
t.Helper()
var lines []string
if version != "" {
lines = append(lines, "// @zod-version: "+version)
}
lines = append(lines, "// @typecheck")
header := strings.Join(lines, "\n") + "\n"
golden.Assert(t, []byte(header+data))
}
// assertSchema is a golden file test helper for Zod schema output.
//
// When no versions are specified, it asserts that v3 and v4 produce identical
// output and golden-tests that output once.
//
// When one version is specified ("v3" or "v4"), it golden-tests that version's
// output directly without a subtest.
//
// When multiple versions are specified, it creates a subtest per version and
// golden-tests each independently.
func assertSchema(t *testing.T, schema any, versions ...string) {
t.Helper()
optsFor := func(ver string) []Opt {
if ver == "v3" {
return []Opt{WithZodV3()}
}
return nil
}
switch len(versions) {
case 0:
v3out := StructToZodSchema(schema, WithZodV3())
v4out := StructToZodSchema(schema)
assert.Equal(t, v3out, v4out)
goldenAssert(t, v4out, "")
case 1:
goldenAssert(t, StructToZodSchema(schema, optsFor(versions[0])...), versions[0])
default:
for _, ver := range versions {
t.Run(ver, func(t *testing.T) {
goldenAssert(t, StructToZodSchema(schema, optsFor(ver)...), ver)
})
}
}
}
// buildValidatorConverter creates a converter with dynamically-built single-field structs.
// Each entry maps a name to a validate tag. The field type is determined by fieldType.
func buildValidatorConverter(fieldType reflect.Type, validators []struct{ name, tag string }, opts ...Opt) *Converter {
c := NewConverterWithOpts(opts...)
for _, v := range validators {
field := reflect.StructField{
Name: "Value",
Type: fieldType,
Tag: reflect.StructTag(fmt.Sprintf(`validate:"%s" json:"value"`, v.tag)),
}
st := reflect.StructOf([]reflect.StructField{field})
c.AddTypeWithName(reflect.New(st).Elem().Interface(), v.name)
}
return c
}
// assertValidators golden-tests a list of validators.
// With no versions: asserts v3==v4, writes one golden file.
// With versions specified: writes separate golden files per version.
func assertValidators(t *testing.T, fieldType reflect.Type, validators []struct{ name, tag string }, versions ...string) {
t.Helper()
switch len(versions) {
case 0:
v3 := buildValidatorConverter(fieldType, validators, WithZodV3())
v4 := buildValidatorConverter(fieldType, validators)
assert.Equal(t, v3.Export(), v4.Export())
goldenAssert(t, v4.Export(), "")
default:
for _, ver := range versions {
t.Run(ver, func(t *testing.T) {
var opts []Opt
if ver == "v3" {
opts = append(opts, WithZodV3())
}
c := buildValidatorConverter(fieldType, validators, opts...)
goldenAssert(t, c.Export(), ver)
})
}
}
}
func TestFieldName(t *testing.T) {
assert.Equal(t,
fieldName(reflect.StructField{Name: "RCONPassword"}),
"RCONPassword",
)
assert.Equal(t,
fieldName(reflect.StructField{Name: "LANMode"}),
"LANMode",
)
assert.Equal(t,
fieldName(reflect.StructField{Name: "ABC"}),
"ABC",
)
}
func TestFieldNameJsonTag(t *testing.T) {
type S struct {
NotTheFieldName string `json:"fieldName"`
}
assert.Equal(t,
fieldName(reflect.TypeOf(S{}).Field(0)),
"fieldName",
)
}
func TestFieldNameJsonTagOmitEmpty(t *testing.T) {
type S struct {
NotTheFieldName string `json:"fieldName,omitempty"`
}
assert.Equal(t,
fieldName(reflect.TypeOf(S{}).Field(0)),
"fieldName",
)
}
func TestSchemaName(t *testing.T) {
assert.Equal(t,
schemaName("", "User"),
"UserSchema",
)
assert.Equal(t,
schemaName("Bot", "User"),
"BotUserSchema",
)
}
func TestStructSimple(t *testing.T) {
type User struct {
Name string
Age int
Height float64
}
assertSchema(t, User{})
}
func TestStructSimpleWithOmittedField(t *testing.T) {
type User struct {
Name string
Age int
Height float64
NotExported string `json:"-"`
}
assertSchema(t, User{})
}
func TestStructSimplePrefix(t *testing.T) {
type User struct {
Name string
Age int
Height float64
}
v3out := StructToZodSchema(User{}, WithPrefix("Bot"), WithZodV3())
v4out := StructToZodSchema(User{}, WithPrefix("Bot"))
assert.Equal(t, v3out, v4out)
goldenAssert(t, v4out, "")
}
func TestNestedStruct(t *testing.T) {
type HasID struct {
ID string
}
type HasName struct {
Name string `json:"name"`
}
type User struct {
HasID
HasName
Tags []string
}
assertSchema(t, User{}, "v3", "v4")
}
func TestStringArray(t *testing.T) {
type User struct {
Tags []string
}
assertSchema(t, User{})
}
func TestStringNestedArray(t *testing.T) {
type TagPair [2]string
type User struct {
TagPairs []TagPair
}
assertSchema(t, User{})
}
func TestStructSlice(t *testing.T) {
type User struct {
Favourites []struct {
Name string
}
}
assertSchema(t, User{})
}
func TestStructSliceOptional(t *testing.T) {
type User struct {
Favourites []struct {
Name string
} `json:",omitempty"`
}
assertSchema(t, User{})
}
func TestStructSliceOptionalNullable(t *testing.T) {
type User struct {
Favourites *[]struct {
Name string
} `json:",omitempty"`
}
assertSchema(t, User{})
}
func TestStringOptional(t *testing.T) {
type User struct {
Name string
Nickname string `json:",omitempty"`
}
assertSchema(t, User{})
}
func TestStringNullable(t *testing.T) {
type User struct {
Name string
Nickname *string
}
assertSchema(t, User{})
}
func TestStringOptionalNotNullable(t *testing.T) {
type User struct {
Name string
Nickname *string `json:",omitempty"` // nil values are omitted
}
assertSchema(t, User{})
}
func TestStringOptionalNullable(t *testing.T) {
type User struct {
Name string
Nickname **string `json:",omitempty"` // nil values are omitted
}
assertSchema(t, User{})
}
func TestOmitZero(t *testing.T) {
type Payload struct {
Name string
Nickname string `json:",omitzero"`
Email *string `json:",omitzero"`
}
assertSchema(t, Payload{})
}
func TestStringArrayNullable(t *testing.T) {
type User struct {
Name string
Tags []*string
}
assertSchema(t, User{})
}
func TestNullableWithValidations(t *testing.T) {
type User struct {
Name string `validate:"required"`
PtrMapOptionalNullable1 *map[string]interface{} `json:",omitempty"`
PtrMapOptionalNullable2 *map[string]interface{} `json:",omitempty" validate:"omitempty,min=2,max=5"`
PtrMap1 *map[string]interface{} `validate:"min=2,max=5"`
PtrMap2 *map[string]interface{} `json:",omitempty" validate:"min=2,max=5"`
PtrMapNullable *map[string]interface{} `validate:"omitempty,min=2,max=5"`
MapOptional1 map[string]interface{} `json:",omitempty"`
MapOptional2 map[string]interface{} `json:",omitempty" validate:"omitempty,min=2,max=5"`
Map1 map[string]interface{} `validate:"min=2,max=5"`
Map2 map[string]interface{} `json:",omitempty" validate:"min=2,max=5"`
MapNullable map[string]interface{} `validate:"omitempty,min=2,max=5"`
PtrSliceOptionalNullable1 *[]string `json:",omitempty"`
PtrSliceOptionalNullable2 *[]string `json:",omitempty" validate:"omitempty,min=2,max=5"`
PtrSlice1 *[]string `validate:"min=2,max=5"`
PtrSlice2 *[]string `json:",omitempty" validate:"min=2,max=5"`
PtrSliceNullable *[]string `validate:"omitempty,min=2,max=5"`
SliceOptional1 []string `json:",omitempty"`
SliceOptional2 []string `json:",omitempty" validate:"omitempty,min=2,max=5"`
Slice1 []string `validate:"min=2,max=5"`
Slice2 []string `json:",omitempty" validate:"min=2,max=5"`
SliceNullable []string `validate:"omitempty,min=2,max=5"`
PtrIntOptional1 *int `json:",omitempty"`
PtrIntOptional2 *int `json:",omitempty" validate:"omitempty,min=2,max=5"`
PtrInt1 *int `validate:"min=2,max=5"`
PtrInt2 *int `json:",omitempty" validate:"min=2,max=5"`
PtrIntNullable *int `validate:"omitempty,min=2,max=5"`
// Not handled by zen for now
// IntOptionalNullable int `json:",omitempty"`
// Int1 int `validate:"min=2,max=5"`
// Int2 int `json:",omitempty" validate:"min=2,max=5"`
// IntNullable1 int `validate:"omitempty,min=2,max=5"`
// IntNullable2 int `json:",omitempty" validate:"omitempty,min=2,max=5"`
PtrStringOptional1 *string `json:",omitempty"`
PtrStringOptional2 *string `json:",omitempty" validate:"omitempty,min=2,max=5"`
PtrString1 *string `validate:"min=2,max=5"`
PtrString2 *string `json:",omitempty" validate:"min=2,max=5"`
PtrStringNullable *string `validate:"omitempty,min=2,max=5"`
// Not handled by zen for now
// StringOptionalNullable string `json:",omitempty"`
// String1 string `validate:"min=2,max=5"`
// String2 string `json:",omitempty" validate:"min=2,max=5"`
// StringNullable1 string `validate:"omitempty,min=2,max=5"`
// StringNullable2 string `json:",omitempty" validate:"omitempty,min=2,max=5"`
}
assertSchema(t, User{})
}
func TestStringValidations(t *testing.T) {
assertValidators(t, reflect.TypeOf(""), []struct{ name, tag string }{
{"eq", "eq=hello"},
{"ne", "ne=hello"},
{"oneof", "oneof=hello world"},
{"oneof_separated", "oneof='a b c' 'd e f'"},
{"len", "len=5"},
{"min", "min=5"},
{"max", "max=5"},
{"minmax", "min=3,max=7"},
{"gt", "gt=5"},
{"gte", "gte=5"},
{"lt", "lt=5"},
{"lte", "lte=5"},
{"contains", "contains=hello"},
{"endswith", "endswith=hello"},
{"startswith", "startswith=hello"},
{"required", "required"},
{"url_encoded", "url_encoded"},
{"alpha", "alpha"},
{"alphanum", "alphanum"},
{"alphanumunicode", "alphanumunicode"},
{"alphaunicode", "alphaunicode"},
{"ascii", "ascii"},
{"boolean_validator", "boolean"},
{"lowercase", "lowercase"},
{"number_validator", "number"},
{"numeric", "numeric"},
{"uppercase", "uppercase"},
{"mongodb", "mongodb"},
{"json_validator", "json"},
{"latitude", "latitude"},
{"longitude", "longitude"},
{"md4", "md4"},
})
t.Run("bad tag panics", func(t *testing.T) {
type Bad struct {
Name string `validate:"bad=hello"`
}
assert.Panics(t, func() { StructToZodSchema(Bad{}) })
})
t.Run("unknown tag panics", func(t *testing.T) {
type Bad2 struct {
Name string `validate:"bad2"`
}
assert.Panics(t, func() { StructToZodSchema(Bad2{}) })
})
t.Run("gt with non-integer panics", func(t *testing.T) {
type Bad struct {
Name string `validate:"gt=abc"`
}
assert.Panics(t, func() { StructToZodSchema(Bad{}) })
})
t.Run("lt with non-integer panics", func(t *testing.T) {
type Bad struct {
Name string `validate:"lt=abc"`
}
assert.Panics(t, func() { StructToZodSchema(Bad{}) })
})
t.Run("escapeJSString escapes quotes and backslashes", func(t *testing.T) {
assert.Equal(t, `foo\"bar`, escapeJSString(`foo"bar`))
assert.Equal(t, `foo\\bar`, escapeJSString(`foo\bar`))
assert.Equal(t, `a\"b\\c`, escapeJSString(`a"b\c`))
assert.Equal(t, `no change`, escapeJSString(`no change`))
})
t.Run("special chars in tag values are escaped in output", func(t *testing.T) {
// Go struct tag syntax can't contain raw quotes, but reflect.StructOf can.
// This tests that the generated JS output correctly escapes them.
c := NewConverterWithOpts()
contains := reflect.StructOf([]reflect.StructField{{
Name: "Value", Type: reflect.TypeOf(""),
Tag: reflect.StructTag(`validate:"contains=foo\"bar" json:"value"`),
}})
c.AddTypeWithName(reflect.New(contains).Elem().Interface(), "ContainsQuote")
eq := reflect.StructOf([]reflect.StructField{{
Name: "Value", Type: reflect.TypeOf(""),
Tag: reflect.StructTag(`validate:"eq=a\\b" json:"value"`),
}})
c.AddTypeWithName(reflect.New(eq).Elem().Interface(), "EqBackslash")
goldenAssert(t, c.Export(), "")
})
t.Run("enum ignores other validators", func(t *testing.T) {
c := NewConverterWithOpts()
c.AddTypeWithName(struct {
V string `validate:"required,oneof=a b" json:"v"`
}{}, "RequiredOneof")
c.AddTypeWithName(struct {
V string `validate:"oneof=a b,contains=x" json:"v"`
}{}, "OneofContains")
c.AddTypeWithName(struct {
V string `validate:"oneof=a b,startswith=a" json:"v"`
}{}, "OneofStartswith")
c.AddTypeWithName(struct {
V string `validate:"oneof=a b,endswith=z" json:"v"`
}{}, "OneofEndswith")
c.AddTypeWithName(struct {
V string `validate:"oneof='127.0.0.1' '::1',ip" json:"v"`
}{}, "OneofIp")
goldenAssert(t, c.Export(), "")
})
t.Run("string tag order is preserved around v4 format helpers", func(t *testing.T) {
type Payload struct {
TrimmedThenEmail string `validate:"trim,email"`
EmailThenTrimmed string `validate:"email,trim"`
}
customTagHandlers := map[string]CustomFn{
"trim": func(c *Converter, t reflect.Type, validate string, i int) string {
return ".trim()"
},
}
for _, ver := range []string{"v3", "v4"} {
t.Run(ver, func(t *testing.T) {
opts := []Opt{WithCustomTags(customTagHandlers)}
if ver == "v3" {
opts = append(opts, WithZodV3())
}
goldenAssert(t, NewConverterWithOpts(opts...).Convert(Payload{}), ver)
})
}
})
}
func TestOneofRequired(t *testing.T) {
type Payload struct {
Status string `json:"status" validate:"required,oneof=active inactive"`
// Would generate the same schema as the above. This doesn't mirror go validator exactly as it allows empty values.
// For now let's assume that empty strings are not valid enum values, but we can revisit if there's demand for that.
StatusImplicitRequired string `json:"statusImplicitRequired" validate:"oneof=active inactive"`
Channel *string `json:"channel,omitempty" validate:"omitempty,oneof=email sms"`
}
assertSchema(t, Payload{})
}
func TestZodV4Defaults(t *testing.T) {
t.Run("embedded structs use shape spreads", func(t *testing.T) {
type HasID struct {
ID string
}
type HasName struct {
Name string `json:"name"`
}
type User struct {
HasID
HasName
Tags []string
}
assertSchema(t, User{}, "v4")
})
t.Run("string formats use zod v4 builders", func(t *testing.T) {
type Payload struct {
Email string `validate:"email"`
Link string `validate:"http_url"`
Base64 string `validate:"base64"`
ID string `validate:"uuid4"`
Checksum string `validate:"md5"`
}
assertSchema(t, Payload{}, "v4")
})
t.Run("custom tag before required base64 preserves min(1)", func(t *testing.T) {
type Payload struct {
Data string `validate:"trim,required,base64"`
Hex string `validate:"trim,required,hexadecimal"`
}
customTagHandlers := map[string]CustomFn{
"trim": func(c *Converter, t reflect.Type, validate string, i int) string {
return ".trim()"
},
}
goldenAssert(t, NewConverterWithOpts(WithCustomTags(customTagHandlers)).Convert(Payload{}), "v4")
})
t.Run("ip unions inherit generic string constraints", func(t *testing.T) {
type Payload struct {
Address string `validate:"ip,required,max=45"`
}
assertSchema(t, Payload{}, "v4")
})
t.Run("format combined with union panics", func(t *testing.T) {
type Payload struct {
Address string `validate:"email,ip"`
}
assert.Panics(t, func() { StructToZodSchema(Payload{}) })
})
t.Run("multiple formats panics", func(t *testing.T) {
type Payload struct {
Value string `validate:"email,url"`
}
assert.Panics(t, func() { StructToZodSchema(Payload{}) })
})
t.Run("optional format with nullable pointer", func(t *testing.T) {
type Payload struct {
Email *string `validate:"omitempty,email" json:"email"`
}
assertSchema(t, Payload{}, "v3", "v4")
})
t.Run("named field shadows embedded field", func(t *testing.T) {
type Base struct {
ID string `json:"id"`
Name string `json:"name"`
}
type Child struct {
Base
ID int `json:"id"` // shadows Base.ID, keeps Base.Name
}
assertSchema(t, Child{}, "v3", "v4")
})
t.Run("recursive embedded shapes preserve encounter order for duplicate keys", func(t *testing.T) {
type Base struct {
ID string `json:"id"`
}
type Node struct {
Base
ID int `json:"id"`
Next *Node `json:"next"`
}
goldenAssert(t, StructToZodSchema(Node{}), "v4")
})
t.Run("recursive embedded shapes keep named fields after spreads to override embedded fields", func(t *testing.T) {
type TreeNode struct {
Value string
CreatedAt time.Time
Children *[]TreeNode
UpdatedAt string
}
type Tree struct {
TreeNode
UpdatedAt time.Time
}
assertSchema(t, Tree{}, "v4")
})
}
func TestNumberValidations(t *testing.T) {
assertValidators(t, reflect.TypeOf(0), []struct{ name, tag string }{
{"gte_lte", "gte=18,lte=60"},
{"gt_lt", "gt=18,lt=60"},
{"eq", "eq=18"},
{"ne", "ne=18"},
{"oneof", "oneof=18 19 20"},
{"min_max", "min=18,max=60"},
{"len", "len=18"},
})
t.Run("bad tag panics", func(t *testing.T) {
type Bad struct {
Age int `validate:"bad=18"`
}
assert.Panics(t, func() { StructToZodSchema(Bad{}) })
})
t.Run("non-numeric arg panics", func(t *testing.T) {
tags := []string{"gt", "gte", "lt", "lte", "min", "max", "eq", "ne", "len"}
for _, tag := range tags {
t.Run(tag, func(t *testing.T) {
assert.Panics(t, func() {
st := reflect.StructOf([]reflect.StructField{{
Name: "V",
Type: reflect.TypeOf(0),
Tag: reflect.StructTag(fmt.Sprintf(`validate:"%s=abc" json:"v"`, tag)),
}})
StructToZodSchema(reflect.New(st).Elem().Interface())
})
})
}
t.Run("oneof", func(t *testing.T) {
assert.Panics(t, func() {
st := reflect.StructOf([]reflect.StructField{{
Name: "V",
Type: reflect.TypeOf(0),
Tag: reflect.StructTag(`validate:"oneof=1 abc 3" json:"v"`),
}})
StructToZodSchema(reflect.New(st).Elem().Interface())
})
})
})
t.Run("float args are accepted", func(t *testing.T) {
type S struct {
V float64 `validate:"gt=1.5,lt=9.9"`
}
assert.NotPanics(t, func() { StructToZodSchema(S{}) })
})
}
func TestInterfaceAny(t *testing.T) {
type User struct {
Name string
Metadata interface{}
}
assertSchema(t, User{})
}
func TestInterfacePointerAny(t *testing.T) {
type User struct {
Name string
Metadata *interface{}
}
assertSchema(t, User{})
}
func TestInterfaceEmptyAny(t *testing.T) {
type User struct {
Name string
Metadata interface{} `json:",omitempty"`
}
assertSchema(t, User{})
}
func TestInterfacePointerEmptyAny(t *testing.T) {
type User struct {
Name string
Metadata *interface{} `json:",omitempty"`
}
assertSchema(t, User{})
}
func TestMapStringToString(t *testing.T) {
type User struct {
Name string
Metadata map[string]string
}
assertSchema(t, User{})
}
func TestMapStringToInterface(t *testing.T) {
type User struct {
Name string
Metadata map[string]interface{}
}
assertSchema(t, User{})
}
func TestMapWithStruct(t *testing.T) {
type PostWithMetaData struct {
Title string
}
type User struct {
MapWithStruct map[string]PostWithMetaData
}
assertSchema(t, User{})
}
func TestMapWithValidations(t *testing.T) {
assertValidators(t, reflect.TypeOf(map[string]string{}), []struct{ name, tag string }{
{"required", "required"},
{"min", "min=1"},
{"max", "max=1"},
{"len", "len=1"},
{"minmax", "min=1,max=2"},
{"eq", "eq=1"},
{"ne", "ne=1"},
{"gt", "gt=1"},
{"gte", "gte=1"},
{"lt", "lt=1"},
{"lte", "lte=1"},
{"dive1", "dive,min=2"},
})
t.Run("dive_nested", func(t *testing.T) {
assertValidators(t, reflect.TypeOf([]map[string]string{}), []struct{ name, tag string }{
{"dive2", "required,dive,min=2,dive,min=3"},
{"dive3", "required,dive,min=2,dive,keys,min=3,endkeys,max=4"},
})
})
t.Run("bad tag panics", func(t *testing.T) {
type Bad struct {
Map map[string]string `validate:"bad=1"`
}
assert.Panics(t, func() { StructToZodSchema(Bad{}) })
})
t.Run("non-integer args panic", func(t *testing.T) {
tags := []string{"min", "max", "len", "eq", "ne", "gt", "gte", "lt", "lte"}
for _, tag := range tags {
t.Run(tag, func(t *testing.T) {
assert.Panics(t, func() {
st := reflect.StructOf([]reflect.StructField{{
Name: "M",
Type: reflect.TypeOf(map[string]string{}),
Tag: reflect.StructTag(fmt.Sprintf(`validate:"%s=abc" json:"m"`, tag)),
}})
StructToZodSchema(reflect.New(st).Elem().Interface())
})
})
}
})
}
func TestMapWithNonStringKey(t *testing.T) {
type Map1 struct {
Name string
Metadata map[int]string
}
type Map2 struct {
Name string
Metadata map[time.Time]string
}
type Map3 struct {
Name string
Metadata map[float64]string
}
t.Run("int_key", func(t *testing.T) {
assertSchema(t, Map1{})
})
t.Run("time_key", func(t *testing.T) {
assertSchema(t, Map2{})
})
t.Run("float_key", func(t *testing.T) {
assertSchema(t, Map3{})
})
}
func TestMapWithEnumKey(t *testing.T) {
type Payload struct {
Metadata map[string]string `validate:"dive,keys,oneof=draft published,endkeys"`
}
assertSchema(t, Payload{}, "v3", "v4")
}
func TestGetValidateKeys(t *testing.T) {
assert.Equal(t, "min=3", getValidateKeys("dive,keys,min=3,endkeys,max=4"))
assert.Equal(t, "min=3,max=5", getValidateKeys("dive,keys,min=3,max=5,endkeys,max=4"))
assert.Equal(t, "min=3", getValidateKeys("dive,keys,min=3,endkeys"))
assert.Equal(t, "min=3,max=5", getValidateKeys("dive,keys,min=3,max=5,endkeys"))
assert.Equal(t, "", getValidateKeys("dive,keys,endkeys,max=4"))
assert.Equal(t, "", getValidateKeys("dive,max=4"))
assert.Equal(t, "min=3", getValidateKeys("dive,keys,min=3,endkeys,max=4,dive,keys,min=3,endkeys,max=4"))
assert.Equal(t, "min=3,max=5", getValidateKeys("dive,keys,min=3,max=5,endkeys,max=4,dive,keys,min=3,max=5,endkeys,max=4"))
assert.Equal(t, "min=3", getValidateKeys("dive,keys,min=3,endkeys,dive,keys,min=3,endkeys"))
assert.Equal(t, "min=3,max=5", getValidateKeys("dive,keys,min=3,max=5,endkeys,dive,keys,min=3,max=5,endkeys"))
assert.Equal(t, "", getValidateKeys("dive,keys,endkeys,max=4,dive,keys,endkeys,max=4"))
assert.Equal(t, "min=3", getValidateKeys("min=2,dive,keys,min=3,endkeys,max=4"))
}
func TestGetValidateValues(t *testing.T) {
assert.Equal(t, "max=4", getValidateValues("dive,keys,min=3,endkeys,max=4"))
assert.Equal(t, "max=4", getValidateValues("dive,keys,min=3,max=5,endkeys,max=4"))
assert.Equal(t, "", getValidateValues("dive,keys,min=3,endkeys"))
assert.Equal(t, "", getValidateValues("dive,keys,min=3,max=5,endkeys"))
assert.Equal(t, "max=4", getValidateValues("dive,keys,endkeys,max=4"))
assert.Equal(t, "max=4", getValidateValues("dive,keys,min=3,endkeys,max=4,dive,keys,min=3,endkeys,max=4"))
assert.Equal(t, "min=3,max=4", getValidateValues("dive,keys,min=3,max=5,endkeys,min=3,max=4,dive,keys,min=3,max=5,endkeys,max=4"))
assert.Equal(t, "", getValidateValues("dive,keys,min=3,endkeys,dive,keys,min=3,endkeys"))
assert.Equal(t, "", getValidateValues("dive,keys,min=3,max=5,endkeys,dive,keys,min=3,max=5,endkeys"))
assert.Equal(t, "max=4", getValidateValues("dive,keys,endkeys,max=4,dive,keys,endkeys,max=4"))
assert.Equal(t, "min=3", getValidateValues("min=2,dive,min=3"))
assert.Equal(t, "min=3,max=4", getValidateValues("dive,min=3,max=4,dive,min=4,max=5"))
assert.Equal(t, "max=4", getValidateValues("min=2,dive,keys,min=3,endkeys,max=4"))
t.Run("dive keys without endkeys panics", func(t *testing.T) {
assert.Panics(t, func() { getValidateValues("dive,keys,min=3") })
})
t.Run("bare dive returns empty", func(t *testing.T) {
assert.Equal(t, "", getValidateValues("dive"))
})
}
func TestGetValidateCurrent(t *testing.T) {
assert.Equal(t, "required", getValidateCurrent("required,dive,min=2,dive,min=3"))
assert.Equal(t, "", getValidateCurrent("dive,min=2,dive,min=3,max=4"))
assert.Equal(t, "min=2,max=3", getValidateCurrent("min=2,max=3,dive,min=2,dive,min=3,max=4"))
}
func TestStructTime(t *testing.T) {
type User struct {
Name string
When time.Time
}
assertSchema(t, User{})
}
func TestTimeWithRequired(t *testing.T) {
type User struct {
When time.Time `validate:"required"`
}
assertSchema(t, User{})
}
func TestDuration(t *testing.T) {
type User struct {
HowLong time.Duration
}
assertSchema(t, User{})
}
// Wrapper mimics a generic optional type like 4d63.com/optional.Optional[T].
// The custom handler resolves the inner type via ConvertType(t.Elem(), ...).
type Wrapper[T any] struct{ Value T }
func TestCustomTypes(t *testing.T) {
t.Run("custom type mapped to string", func(t *testing.T) {
type Decimal struct {
Value int
Exponent int
}
type User struct {
Name string
Money Decimal
}
customTypes := map[string]CustomFn{
"github.com/hypersequent/zen.Decimal": func(c *Converter, t reflect.Type, validate string, i int) string {
return "z.string()"
},
}
v3c := NewConverterWithOpts(WithCustomTypes(customTypes), WithZodV3())
v4c := NewConverterWithOpts(WithCustomTypes(customTypes))
v3out := v3c.Convert(User{})
v4out := v4c.Convert(User{})
assert.Equal(t, v3out, v4out)
goldenAssert(t, v4out, "")
})
t.Run("custom type resolves inner generic type", func(t *testing.T) {
type Profile struct {
Bio string
}
type User struct {
MaybeName Wrapper[string]
MaybeAge Wrapper[int]
MaybeHeight Wrapper[float64]
MaybeProfile Wrapper[Profile]
}
customTypes := map[string]CustomFn{
"github.com/hypersequent/zen.Wrapper": func(c *Converter, t reflect.Type, validate string, i int) string {
return fmt.Sprintf("%s.optional().nullish()", c.ConvertType(t.Field(0).Type, validate, i))
},
}
v3c := NewConverterWithOpts(WithCustomTypes(customTypes), WithZodV3())
v4c := NewConverterWithOpts(WithCustomTypes(customTypes))
v3out := v3c.Convert(User{})
v4out := v4c.Convert(User{})
assert.Equal(t, v3out, v4out)
goldenAssert(t, v4out, "")
})
t.Run("custom type with nullable control", func(t *testing.T) {
type User struct {
Name string
Email *Wrapper[string]
}
customTypes := map[string]CustomFn{
"github.com/hypersequent/zen.Wrapper": func(c *Converter, t reflect.Type, validate string, i int) string {
return fmt.Sprintf("%s.optional()", c.ConvertType(t.Field(0).Type, validate, i))
},
}
v3c := NewConverterWithOpts(WithCustomTypes(customTypes), WithZodV3())
v4c := NewConverterWithOpts(WithCustomTypes(customTypes))
v3out := v3c.Convert(User{})
v4out := v4c.Convert(User{})
assert.Equal(t, v3out, v4out)
goldenAssert(t, v4out, "")
})
}
func TestWithIgnoreTags(t *testing.T) {
type User struct {
Name string `validate:"required,customtag=value"`
}
t.Run("panics on unknown tag", func(t *testing.T) {
assert.Panics(t, func() { StructToZodSchema(User{}) })
})
t.Run("ignores specified tag", func(t *testing.T) {
assert.NotPanics(t, func() {
StructToZodSchema(User{}, WithIgnoreTags("customtag"))
})
goldenAssert(t, StructToZodSchema(User{}, WithIgnoreTags("customtag")), "")
})
}
func TestEverything(t *testing.T) {
// The order matters PostWithMetaData needs to be declared after post otherwise it will raise a
// `Block-scoped variable 'Post' used before its declaration.` typescript error.
type Post struct {
Title string
}
type PostWithMetaData struct {
Title string
Post Post
}
type User struct {
Name string
Nickname *string // pointers become optional
Age int
Height float64
OldPostWithMetaData PostWithMetaData
Tags []string
TagsOptional []string `json:",omitempty"` // slices with omitempty cannot be null
TagsOptionalNullable *[]string `json:",omitempty"` // pointers to slices with omitempty can be null or undefined
Favourites []struct { // nested structs are kept inline
Name string
}
Posts []Post // external structs are emitted as separate exports
Post Post `json:",omitempty"` // this tag is ignored because structs don't have an empty value
PostOptional *Post `json:",omitempty"` // single struct pointers with omitempty cannot be null