Skip to content
Myr

validate_test.go

This file

Path

binding/validate_test.go

253 lines · 6.0 KiB · Go

Last changed by

ci(golangci-lint): update configuration and fix lint issues (#4247)Flc゛before adoptionc4287b1

History of this file

Take it

1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package binding67import (8	"bytes"9	"testing"10	"time"1112	"github.com/go-playground/validator/v10"13	"github.com/stretchr/testify/assert"14	"github.com/stretchr/testify/require"15)1617type testInterface interface {18	String() string19}2021type substructNoValidation struct {22	IString string23	IInt    int24}2526type mapNoValidationSub map[string]substructNoValidation2728type structNoValidationValues struct {29	substructNoValidation3031	Boolean bool3233	Uinteger   uint34	Integer    int35	Integer8   int836	Integer16  int1637	Integer32  int3238	Integer64  int6439	Uinteger8  uint840	Uinteger16 uint1641	Uinteger32 uint3242	Uinteger64 uint644344	Float32 float3245	Float64 float644647	String string4849	Date time.Time5051	Struct        substructNoValidation52	InlinedStruct struct {53		String  []string54		Integer int55	}5657	IntSlice           []int58	IntPointerSlice    []*int59	StructPointerSlice []*substructNoValidation60	StructSlice        []substructNoValidation61	InterfaceSlice     []testInterface6263	UniversalInterface any64	CustomInterface    testInterface6566	FloatMap  map[string]float3267	StructMap mapNoValidationSub68}6970func createNoValidationValues() structNoValidationValues {71	integer := 172	s := structNoValidationValues{73		Boolean:            true,74		Uinteger:           1 << 29,75		Integer:            -10000,76		Integer8:           120,77		Integer16:          -20000,78		Integer32:          1 << 29,79		Integer64:          1 << 61,80		Uinteger8:          250,81		Uinteger16:         50000,82		Uinteger32:         1 << 31,83		Uinteger64:         1 << 62,84		Float32:            123.456,85		Float64:            123.456789,86		String:             "text",87		Date:               time.Time{},88		CustomInterface:    &bytes.Buffer{},89		Struct:             substructNoValidation{},90		IntSlice:           []int{-3, -2, 1, 0, 1, 2, 3},91		IntPointerSlice:    []*int{&integer},92		StructSlice:        []substructNoValidation{},93		UniversalInterface: 1.2,94		FloatMap: map[string]float32{95			"foo": 1.23,96			"bar": 232.323,97		},98		StructMap: mapNoValidationSub{99			"foo": substructNoValidation{},100			"bar": substructNoValidation{},101		},102		// StructPointerSlice []noValidationSub103		// InterfaceSlice     []testInterface104	}105	s.InlinedStruct.Integer = 1000106	s.InlinedStruct.String = []string{"first", "second"}107	s.IString = "substring"108	s.IInt = 987654109	return s110}111112func TestValidateNoValidationValues(t *testing.T) {113	origin := createNoValidationValues()114	test := createNoValidationValues()115	empty := structNoValidationValues{}116117	require.NoError(t, validate(test))118	require.NoError(t, validate(&test))119	require.NoError(t, validate(empty))120	require.NoError(t, validate(&empty))121122	assert.Equal(t, origin, test)123}124125type structNoValidationPointer struct {126	substructNoValidation127128	Boolean bool129130	Uinteger   *uint131	Integer    *int132	Integer8   *int8133	Integer16  *int16134	Integer32  *int32135	Integer64  *int64136	Uinteger8  *uint8137	Uinteger16 *uint16138	Uinteger32 *uint32139	Uinteger64 *uint64140141	Float32 *float32142	Float64 *float64143144	String *string145146	Date *time.Time147148	Struct *substructNoValidation149150	IntSlice           *[]int151	IntPointerSlice    *[]*int152	StructPointerSlice *[]*substructNoValidation153	StructSlice        *[]substructNoValidation154	InterfaceSlice     *[]testInterface155156	FloatMap  *map[string]float32157	StructMap *mapNoValidationSub158}159160func TestValidateNoValidationPointers(t *testing.T) {161	// origin := createNoValidation_values()162	// test := createNoValidation_values()163	empty := structNoValidationPointer{}164165	// assert.Nil(t, validate(test))166	// assert.Nil(t, validate(&test))167	require.NoError(t, validate(empty))168	require.NoError(t, validate(&empty))169170	// assert.Equal(t, origin, test)171}172173type Object map[string]any174175func TestValidatePrimitives(t *testing.T) {176	obj := Object{"foo": "bar", "bar": 1}177	require.NoError(t, validate(obj))178	require.NoError(t, validate(&obj))179	assert.Equal(t, Object{"foo": "bar", "bar": 1}, obj)180181	obj2 := []Object{{"foo": "bar", "bar": 1}, {"foo": "bar", "bar": 1}}182	require.NoError(t, validate(obj2))183	require.NoError(t, validate(&obj2))184185	nu := 10186	require.NoError(t, validate(nu))187	require.NoError(t, validate(&nu))188	assert.Equal(t, 10, nu)189190	str := "value"191	require.NoError(t, validate(str))192	require.NoError(t, validate(&str))193	assert.Equal(t, "value", str)194}195196type structModifyValidation struct {197	Integer int198}199200func toZero(sl validator.StructLevel) {201	s := sl.Top().Interface().(*structModifyValidation)202	s.Integer = 0203}204205func TestValidateAndModifyStruct(t *testing.T) {206	// This validates that pointers to structs are passed to the validator207	// giving us the ability to modify the struct being validated.208	engine, ok := Validator.Engine().(*validator.Validate)209	assert.True(t, ok)210211	engine.RegisterStructValidation(toZero, structModifyValidation{})212213	s := structModifyValidation{Integer: 1}214	errs := validate(&s)215216	require.NoError(t, errs)217	assert.Equal(t, structModifyValidation{Integer: 0}, s)218}219220// structCustomValidation is a helper struct we use to check that221// custom validation can be registered on it.222// The `notone` binding directive is for custom validation and registered later.223type structCustomValidation struct {224	Integer int `binding:"notone"`225}226227func notOne(f1 validator.FieldLevel) bool {228	if val, ok := f1.Field().Interface().(int); ok {229		return val != 1230	}231	return false232}233234func TestValidatorEngine(t *testing.T) {235	// This validates that the function `notOne` matches236	// the expected function signature by `defaultValidator`237	// and by extension the validator library.238	engine, ok := Validator.Engine().(*validator.Validate)239	assert.True(t, ok)240241	err := engine.RegisterValidation("notone", notOne)242	// Check that we can register custom validation without error243	require.NoError(t, err)244245	// Create an instance which will fail validation246	withOne := structCustomValidation{Integer: 1}247	errs := validate(withOne)248249	// Check that we got back non-nil errs250	require.Error(t, errs)251	// Check that the error matches expectation252	require.Error(t, errs, "notone")253}