|
1 | 1 | package validation
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "strings" |
4 | 7 | "testing"
|
5 | 8 | )
|
6 | 9 |
|
@@ -37,3 +40,35 @@ func TestEach(t *testing.T) {
|
37 | 40 | assertError(t, test.err, err, test.tag)
|
38 | 41 | }
|
39 | 42 | }
|
| 43 | + |
| 44 | +func TestEachWithContext(t *testing.T) { |
| 45 | + rule := Each(WithContext(func(ctx context.Context, value interface{}) error { |
| 46 | + if !strings.Contains(value.(string), ctx.Value("contains").(string)) { |
| 47 | + return errors.New("unexpected value") |
| 48 | + } |
| 49 | + return nil |
| 50 | + })) |
| 51 | + ctx1 := context.WithValue(context.Background(), "contains", "abc") |
| 52 | + ctx2 := context.WithValue(context.Background(), "contains", "xyz") |
| 53 | + |
| 54 | + tests := []struct { |
| 55 | + tag string |
| 56 | + value interface{} |
| 57 | + ctx context.Context |
| 58 | + err string |
| 59 | + }{ |
| 60 | + {"t1.1", map[string]string{"key": "abc"}, ctx1, ""}, |
| 61 | + {"t1.2", map[string]string{"key": "abc"}, ctx2, "key: unexpected value."}, |
| 62 | + {"t1.3", map[string]string{"key": "xyz"}, ctx1, "key: unexpected value."}, |
| 63 | + {"t1.4", map[string]string{"key": "xyz"}, ctx2, ""}, |
| 64 | + {"t1.5", []string{"abc"}, ctx1, ""}, |
| 65 | + {"t1.6", []string{"abc"}, ctx2, "0: unexpected value."}, |
| 66 | + {"t1.7", []string{"xyz"}, ctx1, "0: unexpected value."}, |
| 67 | + {"t1.8", []string{"xyz"}, ctx2, ""}, |
| 68 | + } |
| 69 | + |
| 70 | + for _, test := range tests { |
| 71 | + err := ValidateWithContext(test.ctx, test.value, rule) |
| 72 | + assertError(t, test.err, err, test.tag) |
| 73 | + } |
| 74 | +} |
0 commit comments