Skip to content

Commit

Permalink
Add unit tests for field validation
Browse files Browse the repository at this point in the history
  • Loading branch information
alesr committed Feb 9, 2025
1 parent 03cf411 commit 876aff9
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 1 deletion.
2 changes: 1 addition & 1 deletion template_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type ValidationError struct {
}

func (e *ValidationError) Error() string {
return fmt.Sprintf("template '%s' validation error: %s - %v", e.TemplateName, e.FieldPath, e.Err)
return fmt.Sprintf("template '%s' validation error: '%s' - '%s'", e.TemplateName, e.FieldPath, e.Err)
}

// validateTemplateFields analyzes template content and validates
Expand Down
104 changes: 104 additions & 0 deletions template_validator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package templator

import (
"errors"
"reflect"
"testing"

"github.com/stretchr/testify/assert"
)

func TestValidator_Error(t *testing.T) {
t.Parallel()

validatorError := ValidationError{
TemplateName: "dummy-template-name",
FieldPath: "dummy-file-path",
Err: errors.New("dummy-error"),
}

got := validatorError.Error()

assert.Equal(t, "template 'dummy-template-name' validation error: 'dummy-file-path' - 'dummy-error'", got)
}

func TestUniqueFields(t *testing.T) {
t.Parallel()

testCases := []struct {
name string
givenFields []string
expect []string
}{
{
name: "unique fields",
givenFields: []string{"foo", "bar"},
expect: []string{"foo", "bar"},
},
{
name: "duplicated fields",
givenFields: []string{"foo", "bar", "foo"},
expect: []string{"foo", "bar"},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got := uniqueFields(tc.givenFields)

assert.ElementsMatch(t, tc.expect, got)
})
}
}

func Test_validateField(t *testing.T) {
t.Parallel()

type testStruct struct {
testField string
}

testCases := []struct {
name string
typ reflect.Type
fieldPath string
wantErr bool
}{
{
name: "nil type",
typ: nil,
fieldPath: "testField",
wantErr: true,
},
{
name: "non-struct type",
typ: reflect.TypeOf(""),
fieldPath: "testField",
wantErr: true,
},
{
name: "field is a struct",
typ: reflect.TypeOf(testStruct{}),
fieldPath: "testField",
wantErr: false,
},
{
name: "field is a pointer",
typ: reflect.TypeOf(&testStruct{}),
fieldPath: "testField",
wantErr: false,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := validateField(tc.typ, tc.fieldPath)

if tc.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}

0 comments on commit 876aff9

Please sign in to comment.