|
| 1 | +package templator |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "reflect" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | +) |
| 10 | + |
| 11 | +func TestValidator_Error(t *testing.T) { |
| 12 | + t.Parallel() |
| 13 | + |
| 14 | + validatorError := ValidationError{ |
| 15 | + TemplateName: "dummy-template-name", |
| 16 | + FieldPath: "dummy-file-path", |
| 17 | + Err: errors.New("dummy-error"), |
| 18 | + } |
| 19 | + |
| 20 | + got := validatorError.Error() |
| 21 | + |
| 22 | + assert.Equal(t, "template 'dummy-template-name' validation error: 'dummy-file-path' - 'dummy-error'", got) |
| 23 | +} |
| 24 | + |
| 25 | +func TestUniqueFields(t *testing.T) { |
| 26 | + t.Parallel() |
| 27 | + |
| 28 | + testCases := []struct { |
| 29 | + name string |
| 30 | + givenFields []string |
| 31 | + expect []string |
| 32 | + }{ |
| 33 | + { |
| 34 | + name: "unique fields", |
| 35 | + givenFields: []string{"foo", "bar"}, |
| 36 | + expect: []string{"foo", "bar"}, |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "duplicated fields", |
| 40 | + givenFields: []string{"foo", "bar", "foo"}, |
| 41 | + expect: []string{"foo", "bar"}, |
| 42 | + }, |
| 43 | + } |
| 44 | + |
| 45 | + for _, tc := range testCases { |
| 46 | + t.Run(tc.name, func(t *testing.T) { |
| 47 | + got := uniqueFields(tc.givenFields) |
| 48 | + |
| 49 | + assert.ElementsMatch(t, tc.expect, got) |
| 50 | + }) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +func Test_validateField(t *testing.T) { |
| 55 | + t.Parallel() |
| 56 | + |
| 57 | + type testStruct struct { |
| 58 | + testField string |
| 59 | + } |
| 60 | + |
| 61 | + testCases := []struct { |
| 62 | + name string |
| 63 | + typ reflect.Type |
| 64 | + fieldPath string |
| 65 | + wantErr bool |
| 66 | + }{ |
| 67 | + { |
| 68 | + name: "nil type", |
| 69 | + typ: nil, |
| 70 | + fieldPath: "testField", |
| 71 | + wantErr: true, |
| 72 | + }, |
| 73 | + { |
| 74 | + name: "non-struct type", |
| 75 | + typ: reflect.TypeOf(""), |
| 76 | + fieldPath: "testField", |
| 77 | + wantErr: true, |
| 78 | + }, |
| 79 | + { |
| 80 | + name: "field is a struct", |
| 81 | + typ: reflect.TypeOf(testStruct{}), |
| 82 | + fieldPath: "testField", |
| 83 | + wantErr: false, |
| 84 | + }, |
| 85 | + { |
| 86 | + name: "field is a pointer", |
| 87 | + typ: reflect.TypeOf(&testStruct{}), |
| 88 | + fieldPath: "testField", |
| 89 | + wantErr: false, |
| 90 | + }, |
| 91 | + } |
| 92 | + |
| 93 | + for _, tc := range testCases { |
| 94 | + t.Run(tc.name, func(t *testing.T) { |
| 95 | + err := validateField(tc.typ, tc.fieldPath) |
| 96 | + |
| 97 | + if tc.wantErr { |
| 98 | + assert.Error(t, err) |
| 99 | + } else { |
| 100 | + assert.NoError(t, err) |
| 101 | + } |
| 102 | + }) |
| 103 | + } |
| 104 | +} |
0 commit comments