Repository navigation
Expand file tree
/
Copy pathvalidate_test.go
More file actions
807 lines (679 loc) · 17.4 KB
/
Copy pathvalidate_test.go
File metadata and controls
807 lines (679 loc) · 17.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
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
package result
import (
"errors"
"fmt"
"strings"
"testing"
)
// ============================================================================
// MultiError Tests
// ============================================================================
func TestMultiError_Error_NoErrors(t *testing.T) {
me := MultiError{Errors: []error{}}
if me.Error() != "no errors" {
t.Errorf("MultiError.Error() = %q, want %q", me.Error(), "no errors")
}
}
func TestMultiError_Error_SingleError(t *testing.T) {
me := MultiError{Errors: []error{errors.New("single error")}}
if me.Error() != "single error" {
t.Errorf("MultiError.Error() = %q, want %q", me.Error(), "single error")
}
}
func TestMultiError_Error_MultipleErrors(t *testing.T) {
me := MultiError{Errors: []error{
errors.New("error 1"),
errors.New("error 2"),
errors.New("error 3"),
}}
msg := me.Error()
if !strings.Contains(msg, "3 validation errors") {
t.Errorf("MultiError.Error() should contain count")
}
if !strings.Contains(msg, "error 1") || !strings.Contains(msg, "error 2") || !strings.Contains(msg, "error 3") {
t.Errorf("MultiError.Error() should contain all error messages")
}
}
func TestMultiError_Unwrap(t *testing.T) {
err1 := errors.New("first error")
me := MultiError{Errors: []error{err1, errors.New("second error")}}
unwrapped := me.Unwrap()
if !errors.Is(unwrapped, err1) {
t.Error("MultiError.Unwrap() should return first error")
}
}
// ============================================================================
// ValidateAll Tests
// ============================================================================
func TestValidateAll_AllSucceed(t *testing.T) {
result := ValidateAll(
Ok(1),
Ok(2),
Ok(3),
)
values := AssertOk(t, result)
if len(values) != 3 {
t.Fatalf("Expected 3 values, got %d", len(values))
}
for i, v := range values {
if v != i+1 {
t.Errorf("Value %d = %v, want %v", i, v, i+1)
}
}
}
func TestValidateAll_OneFails(t *testing.T) {
result := ValidateAll(
Ok(1),
Err[int](errors.New("error 2")),
Ok(3),
)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 1 {
t.Errorf("Expected 1 error, got %d", len(me.Errors))
}
}
func TestValidateAll_MultipleFail(t *testing.T) {
result := ValidateAll(
Err[int](errors.New("error 1")),
Ok(2),
Err[int](errors.New("error 3")),
)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 2 {
t.Errorf("Expected 2 errors, got %d", len(me.Errors))
}
}
func TestValidateAll_AllFail(t *testing.T) {
result := ValidateAll(
Err[int](errors.New("error 1")),
Err[int](errors.New("error 2")),
Err[int](errors.New("error 3")),
)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 3 {
t.Errorf("Expected 3 errors, got %d", len(me.Errors))
}
}
// ============================================================================
// ValidateAllMap Tests
// ============================================================================
func TestValidateAllMap_AllSucceed(t *testing.T) {
values, errs := ValidateAllMap(
Ok(1),
Ok(2),
Ok(3),
)
if len(values) != 3 {
t.Errorf("Expected 3 values, got %d", len(values))
}
if len(errs) != 0 {
t.Errorf("Expected 0 errors, got %d", len(errs))
}
}
func TestValidateAllMap_SomeFail(t *testing.T) {
values, errs := ValidateAllMap(
Ok(1),
Err[int](errors.New("error 2")),
Ok(3),
)
if len(values) != 2 {
t.Errorf("Expected 2 values, got %d", len(values))
}
if len(errs) != 1 {
t.Errorf("Expected 1 error, got %d", len(errs))
}
}
// ============================================================================
// ValidateRules Tests
// ============================================================================
func TestValidateRules_AllPass(t *testing.T) {
result := ValidateRules(
10,
func(n int) error {
if n < 0 {
return errors.New("must be positive")
}
return nil
},
func(n int) error {
if n > 100 {
return errors.New("must be <= 100")
}
return nil
},
)
value := AssertOk(t, result)
if value != 10 {
t.Errorf("ValidateRules() = %v, want 10", value)
}
}
func TestValidateRules_FirstFails(t *testing.T) {
result := ValidateRules(
-5,
func(n int) error {
if n < 0 {
return errors.New("must be positive")
}
return nil
},
func(n int) error {
if n > 100 {
return errors.New("must be <= 100")
}
return nil
},
)
AssertErr(t, result)
AssertErrContains(t, result, "must be positive")
}
func TestValidateRules_SecondFails(t *testing.T) {
result := ValidateRules(
150,
func(n int) error {
if n < 0 {
return errors.New("must be positive")
}
return nil
},
func(n int) error {
if n > 100 {
return errors.New("must be <= 100")
}
return nil
},
)
AssertErr(t, result)
AssertErrContains(t, result, "must be <= 100")
}
// ============================================================================
// ValidateAllRules Tests
// ============================================================================
func TestValidateAllRules_AllPass(t *testing.T) {
result := ValidateAllRules(
10,
func(n int) error {
if n < 0 {
return errors.New("must be positive")
}
return nil
},
func(n int) error {
if n > 100 {
return errors.New("must be <= 100")
}
return nil
},
)
value := AssertOk(t, result)
if value != 10 {
t.Errorf("ValidateAllRules() = %v, want 10", value)
}
}
func TestValidateAllRules_MultipleFail(t *testing.T) {
result := ValidateAllRules(
-5,
func(n int) error {
if n < 0 {
return errors.New("must be positive")
}
return nil
},
func(n int) error {
if n%2 != 0 {
return errors.New("must be even")
}
return nil
},
)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 2 {
t.Errorf("Expected 2 errors, got %d", len(me.Errors))
}
}
// ============================================================================
// ValidateField Tests
// ============================================================================
func TestValidateField_Ok(t *testing.T) {
result := ValidateField("email", Ok("test@example.com"))
value := AssertOk(t, result)
if value != "test@example.com" {
t.Errorf("ValidateField() = %v, want test@example.com", value)
}
}
func TestValidateField_Err(t *testing.T) {
result := ValidateField("email", Err[string](errors.New("invalid format")))
err := AssertErr(t, result)
op := OpOf(err)
if !strings.Contains(op, "field.email") {
t.Errorf("Error op should contain field name: %v", op)
}
}
// ============================================================================
// ValidateStruct Tests
// ============================================================================
func TestValidateStruct_AllFieldsValid(t *testing.T) {
result := ValidateStruct(
ValidateField("email", Ok("test@example.com")),
ValidateField("username", Ok("testuser")),
ValidateField("password", Ok("secretpass")),
)
AssertOk(t, result)
}
func TestValidateStruct_OneFieldInvalid(t *testing.T) {
result := ValidateStruct(
ValidateField("email", Ok("test@example.com")),
ValidateField("username", Err[string](errors.New("too short"))),
ValidateField("password", Ok("secretpass")),
)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 1 {
t.Errorf("Expected 1 error, got %d", len(me.Errors))
}
}
func TestValidateStruct_MultipleFieldsInvalid(t *testing.T) {
result := ValidateStruct(
ValidateField("email", Err[string](errors.New("invalid format"))),
ValidateField("username", Err[string](errors.New("too short"))),
ValidateField("password", Ok("secretpass")),
)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 2 {
t.Errorf("Expected 2 errors, got %d", len(me.Errors))
}
}
// ============================================================================
// ValidateMap Tests
// ============================================================================
func TestValidateMap_AllValid(t *testing.T) {
items := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
result := ValidateMap(items, func(key string, value int) error {
if value < 0 {
return fmt.Errorf("%s must be positive", key)
}
return nil
})
validated := AssertOk(t, result)
if len(validated) != 3 {
t.Errorf("Expected 3 items, got %d", len(validated))
}
}
func TestValidateMap_SomeInvalid(t *testing.T) {
items := map[string]int{
"a": 1,
"b": -2,
"c": 3,
}
result := ValidateMap(items, func(key string, value int) error {
if value < 0 {
return fmt.Errorf("must be positive")
}
return nil
})
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 1 {
t.Errorf("Expected 1 error, got %d", len(me.Errors))
}
}
// ============================================================================
// ValidateSlice Tests
// ============================================================================
func TestValidateSlice_AllValid(t *testing.T) {
items := []int{1, 2, 3, 4, 5}
result := ValidateSlice(items, func(n int) error {
if n < 0 {
return errors.New("must be positive")
}
return nil
})
validated := AssertOk(t, result)
if len(validated) != 5 {
t.Errorf("Expected 5 items, got %d", len(validated))
}
}
func TestValidateSlice_SomeInvalid(t *testing.T) {
items := []int{1, -2, 3, -4, 5}
result := ValidateSlice(items, func(n int) error {
if n < 0 {
return errors.New("must be positive")
}
return nil
})
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 2 {
t.Errorf("Expected 2 errors, got %d", len(me.Errors))
}
// Check that error messages include index
for _, e := range me.Errors {
if !strings.Contains(e.Error(), "index") {
t.Errorf("Error should include index: %v", e)
}
}
}
// ============================================================================
// ValidateSliceResults Tests
// ============================================================================
func TestValidateSliceResults_AllValid(t *testing.T) {
results := []Result[int]{
Ok(1),
Ok(2),
Ok(3),
}
result := ValidateSliceResults(results)
values := AssertOk(t, result)
if len(values) != 3 {
t.Errorf("Expected 3 values, got %d", len(values))
}
}
func TestValidateSliceResults_SomeInvalid(t *testing.T) {
results := []Result[int]{
Ok(1),
Err[int](errors.New("error at index 1")),
Ok(3),
Err[int](errors.New("error at index 3")),
}
result := ValidateSliceResults(results)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 2 {
t.Errorf("Expected 2 errors, got %d", len(me.Errors))
}
}
// ============================================================================
// Integration Tests
// ============================================================================
func TestValidation_IntegrationFlow(t *testing.T) {
// Simulate validating a user registration form
type UserInput struct {
Email string
Username string
Password string
Age int
}
input := UserInput{
Email: "test@example.com",
Username: "testuser",
Password: "secret123",
Age: 25,
}
// Validate all fields
result := ValidateStruct(
ValidateField("email", ValidateRules(
input.Email,
func(email string) error {
if email == "" {
return errors.New("cannot be empty")
}
if !strings.Contains(email, "@") {
return errors.New("invalid format")
}
return nil
},
)),
ValidateField("username", ValidateRules(
input.Username,
func(username string) error {
if len(username) < 3 {
return errors.New("too short")
}
if len(username) > 20 {
return errors.New("too long")
}
return nil
},
)),
ValidateField("password", ValidateRules(
input.Password,
func(password string) error {
if len(password) < 8 {
return errors.New("too short")
}
return nil
},
)),
ValidateField("age", ValidateRules(
input.Age,
func(age int) error {
if age < 18 {
return errors.New("must be 18 or older")
}
return nil
},
)),
)
AssertOk(t, result)
}
func TestValidation_IntegrationFlow_MultipleErrors(t *testing.T) {
type UserInput struct {
Email string
Username string
Password string
}
input := UserInput{
Email: "invalid-email",
Username: "ab",
Password: "short",
}
// Validate all fields and collect all errors
result := ValidateStruct(
ValidateField("email", ValidateRules(
input.Email,
func(email string) error {
if !strings.Contains(email, "@") {
return errors.New("invalid format")
}
return nil
},
)),
ValidateField("username", ValidateRules(
input.Username,
func(username string) error {
if len(username) < 3 {
return errors.New("too short")
}
return nil
},
)),
ValidateField("password", ValidateRules(
input.Password,
func(password string) error {
if len(password) < 8 {
return errors.New("too short")
}
return nil
},
)),
)
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
// All three fields should have failed
if len(me.Errors) != 3 {
t.Errorf("Expected 3 errors, got %d", len(me.Errors))
}
// Check that errors contain field names
errStr := err.Error()
if !strings.Contains(errStr, "email") {
t.Error("Error should contain 'email'")
}
if !strings.Contains(errStr, "username") {
t.Error("Error should contain 'username'")
}
if !strings.Contains(errStr, "password") {
t.Error("Error should contain 'password'")
}
}
func TestValidateAllRules_ComplexValidation(t *testing.T) {
type Email string
email := Email("test@example.com")
result := ValidateAllRules(
email,
func(e Email) error {
if !strings.Contains(string(e), "@") {
return errors.New("must contain @")
}
return nil
},
func(e Email) error {
if len(e) > 254 {
return errors.New("exceeds max length")
}
return nil
},
func(e Email) error {
if strings.HasPrefix(string(e), ".") {
return errors.New("cannot start with dot")
}
return nil
},
func(e Email) error {
parts := strings.Split(string(e), "@")
if len(parts) != 2 {
return errors.New("invalid format")
}
if len(parts[0]) == 0 || len(parts[1]) == 0 {
return errors.New("empty local or domain part")
}
return nil
},
)
AssertOk(t, result)
}
func TestValidateMap_WithComplexTypes(t *testing.T) {
type Config struct {
Host string
Port int
}
configs := map[string]Config{
"primary": {Host: "localhost", Port: 8080},
"backup": {Host: "backup.example.com", Port: 8081},
"invalid": {Host: "", Port: -1},
}
result := ValidateMap(configs, func(name string, cfg Config) error {
if cfg.Host == "" {
return fmt.Errorf("host cannot be empty")
}
if cfg.Port < 0 || cfg.Port > 65535 {
return fmt.Errorf("invalid port")
}
return nil
})
err := AssertErr(t, result)
var me MultiError
if !errors.As(err, &me) {
t.Fatal("Error should be MultiError")
}
if len(me.Errors) != 1 {
t.Errorf("Expected 1 error, got %d", len(me.Errors))
}
// Error should mention the "invalid" config
if !strings.Contains(err.Error(), "invalid") {
t.Errorf("Error should mention the invalid config: %v", err)
}
}
func TestValidateSlice_EarlyExit(t *testing.T) {
// ValidateSlice collects all errors, not early exit
items := []int{1, 2, -3, 4, -5}
errorCount := 0
result := ValidateSlice(items, func(n int) error {
if n < 0 {
errorCount++
return errors.New("negative")
}
return nil
})
AssertErr(t, result)
// Should have validated all items despite errors
if errorCount != 2 {
t.Errorf("Expected to validate all items (2 errors), got %d errors", errorCount)
}
}
func TestValidateAllMap_PreservesOrder(t *testing.T) {
results := []Result[int]{
Ok(1),
Err[int](errors.New("error 2")),
Ok(3),
Err[int](errors.New("error 4")),
Ok(5),
}
values, errs := ValidateAllMap(results...)
// Values should be in order
if len(values) != 3 {
t.Fatalf("Expected 3 values, got %d", len(values))
}
if values[0] != 1 || values[1] != 3 || values[2] != 5 {
t.Errorf("Values not in correct order: %v", values)
}
// Errors should be collected
if len(errs) != 2 {
t.Fatalf("Expected 2 errors, got %d", len(errs))
}
}
func TestMultiError_NestedErrors(t *testing.T) {
innerErr1 := errors.New("inner error 1")
innerErr2 := errors.New("inner error 2")
me := MultiError{
Errors: []error{
fmt.Errorf("outer error 1: %w", innerErr1),
fmt.Errorf("outer error 2: %w", innerErr2),
},
}
// Check that inner errors are accessible
if !errors.Is(me.Unwrap(), innerErr1) {
t.Error("MultiError should unwrap to first inner error")
}
}
func TestValidateRules_EmptyRules(t *testing.T) {
result := ValidateRules(42)
value := AssertOk(t, result)
if value != 42 {
t.Errorf("ValidateRules with no rules should return value unchanged")
}
}
func TestValidateAllRules_EmptyRules(t *testing.T) {
result := ValidateAllRules(42)
value := AssertOk(t, result)
if value != 42 {
t.Errorf("ValidateAllRules with no rules should return value unchanged")
}
}