github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/vdutil/rule_test.go (about) 1 package vdutil 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 ) 12 13 func TestValidationError(t *testing.T) { 14 var vdErr *ValidationError 15 err := fmt.Errorf("with message: %w", &ValidationError{Name: "testVar", Err: errors.New("test error")}) 16 ok := errors.As(err, &vdErr) 17 assert.True(t, ok) 18 assert.NotNil(t, vdErr) 19 assert.Equal(t, err.Error(), "with message: testVar: test error") 20 assert.Equal(t, vdErr.Error(), "testVar: test error") 21 } 22 23 func TestValidate(t *testing.T) { 24 ctx := context.Background() 25 got1, err := Validate(ctx, 26 GreaterThanZero("var1", "10", true), 27 LessThanOrEqual("var2", 100, 200), 28 ) 29 require.NotNil(t, err) 30 assert.Equal(t, err.Error(), "var2: value 200 > 100") 31 assert.EqualValues(t, 10, got1.Data.GetInt("var1")) 32 assert.True(t, got1.IsValidationError) 33 34 got2, err := Validate(ctx, 35 GreaterThanZero("var1", 10, false), 36 LessThanOrEqual("var2", 100, 100), 37 ParseStrsToInt64Slice("var3", []string{"123", "456", "789"}), 38 ) 39 require.Nil(t, err) 40 assert.Equal(t, []int64{123, 456, 789}, got2.Data.GetSlice("var3")) 41 assert.False(t, got2.IsValidationError) 42 43 got3, err := Validate(ctx, 44 RuleFunc(func(ctx context.Context, result *Result) (any, error) { 45 return nil, errors.New("internal error") 46 })) 47 require.NotNil(t, err) 48 require.False(t, got3.IsValidationError) 49 } 50 51 func TestUseResult(t *testing.T) { 52 ctx := context.Background() 53 got1, err := Validate(ctx, GreaterThanZero("var1", "10", true)) 54 require.Nil(t, err) 55 require.NotNil(t, got1) 56 57 got2, err := Validate(ctx, UseResult(got1), 58 GreaterThanZero("var2", "20", true)) 59 require.Nil(t, err) 60 require.NotNil(t, got2) 61 assert.Equal(t, got1, got2) 62 assert.Equal(t, 10, got2.Data.GetInt("var1")) 63 assert.Equal(t, int64(20), got2.Data.GetInt64("var2")) 64 }