github.com/yandex/pandora@v0.5.32/core/config/validator_test.go (about)

     1  package config
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  type WithURLString struct {
    11  	URL string `validate:"required,url"`
    12  }
    13  
    14  func TestValidateURL(t *testing.T) {
    15  	require.NoError(t, Validate(&WithURLString{"http://yandex.ru/"}))
    16  
    17  	err := Validate(&WithURLString{"http://yandex.ru/%zz"})
    18  	require.Error(t, err)
    19  
    20  	err = Validate(&WithURLString{})
    21  	assert.Error(t, err)
    22  }
    23  
    24  type Multi struct {
    25  	A int `validate:"min=1"`
    26  	B int `validate:"min=2"`
    27  }
    28  
    29  type Single struct {
    30  	X int `validate:"max=0,min=10"`
    31  }
    32  
    33  type Nested struct {
    34  	A Multi
    35  }
    36  
    37  func TestValidateOK(t *testing.T) {
    38  	assert.NoError(t, Validate(&Multi{1, 2}))
    39  }
    40  
    41  func TestValidateError(t *testing.T) {
    42  	err := Validate(&Multi{0, 2})
    43  	require.Error(t, err)
    44  
    45  	err = Validate(&Multi{0, 0})
    46  	require.Error(t, err)
    47  
    48  	err = Validate(&Single{5})
    49  	assert.Error(t, err)
    50  }
    51  
    52  func TestNestedError(t *testing.T) {
    53  	c := &Nested{
    54  		Multi{0, 0},
    55  	}
    56  	require.Error(t, Validate(c.A))
    57  	err := Validate(c)
    58  	assert.Error(t, err)
    59  }
    60  
    61  func TestValidateUnsupported(t *testing.T) {
    62  	err := Validate(1)
    63  	assert.Error(t, err)
    64  }
    65  
    66  type D struct {
    67  	Val string `validate:"invalidNameXXXXXXX=1"`
    68  }
    69  
    70  func TestValidateInvalidValidatorName(t *testing.T) {
    71  	require.Panics(t, func() {
    72  		_ = Validate(&D{"test"})
    73  	})
    74  }
    75  
    76  func TestCustom(t *testing.T) {
    77  	defer func() {
    78  		defaultValidator = newValidator()
    79  	}()
    80  	type custom struct{ fail bool }
    81  	RegisterCustom(func(h ValidateHandle) {
    82  		if h.Value().(custom).fail {
    83  			h.ReportError("fail", "should be false")
    84  		}
    85  	}, custom{})
    86  	assert.NoError(t, Validate(&custom{fail: false}))
    87  	assert.Error(t, Validate(&custom{fail: true}))
    88  }