From 7ee47cbc48e13f9c4ca1fde42298025ce6f10223 Mon Sep 17 00:00:00 2001 From: Suhas Karanth Date: Sun, 27 Aug 2017 10:14:44 +0530 Subject: [PATCH] test(binding): Add test for registering custom validation --- binding/validate_test.go | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/binding/validate_test.go b/binding/validate_test.go index cbcb389d..523e1298 100644 --- a/binding/validate_test.go +++ b/binding/validate_test.go @@ -6,9 +6,12 @@ package binding import ( "bytes" + "reflect" "testing" "time" + validator "gopkg.in/go-playground/validator.v8" + "github.com/stretchr/testify/assert" ) @@ -190,3 +193,42 @@ func TestValidatePrimitives(t *testing.T) { assert.NoError(t, validate(&str)) assert.Equal(t, str, "value") } + +// structCustomValidation is a helper struct we use to check that +// custom validation can be registered on it. +// The `notone` binding directive is for custom validation and registered later. +type structCustomValidation struct { + Integer int `binding:"notone"` +} + +// notOne is a custom validator meant to be used with `validator.v8` library. +// The method signature for `v9` is significantly different and this function +// would need to be changed for tests to pass after upgrade. +// See https://github.com/gin-gonic/gin/pull/1015. +func notOne( + v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, + field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string, +) bool { + if val, ok := field.Interface().(int); ok { + return val != 1 + } + return false +} + +func TestRegisterValidation(t *testing.T) { + // This validates that the function `notOne` matches + // the expected function signature by `defaultValidator` + // and by extension the validator library. + err := Validator.RegisterValidation("notone", notOne) + // Check that we can register custom validation without error + assert.Nil(t, err) + + // Create an instance which will fail validation + withOne := structCustomValidation{Integer: 1} + errs := validate(withOne) + + // Check that we got back non-nil errs + assert.NotNil(t, errs) + // Check that the error matches expactation + assert.Error(t, errs, "", "", "notone") +}