gitee.com/zhongguo168a/gocodes@v0.0.0-20230609140523-e1828349603f/datax/modifyx/modify_test.go (about) 1 package modifyx 2 3 import ( 4 "gitee.com/zhongguo168a/gocodes/datax" 5 "github.com/stretchr/testify/assert" 6 "testing" 7 ) 8 9 var ( 10 root *Root 11 ) 12 13 func initSample() { 14 root = NewRoot(NewSourceWith(map[string]interface{}{ 15 "Int": 1, 16 "Float": 1.0, 17 "Map": map[string]interface{}{ 18 "Int": 1, 19 "Float": 1.0, 20 }, 21 "MapStruct": map[string]interface{}{ 22 "0": map[string]interface{}{ 23 "Int": 1, 24 "Float": 1.0, 25 }, 26 }, 27 "ArrayInt": datax.A{1, 2, 3}, 28 })) 29 } 30 31 type Context struct { 32 } 33 34 func NewModify() (obj *Modify) { 35 obj = &Modify{} 36 return 37 } 38 39 type Modify struct { 40 TestPath string 41 TestValid bool 42 TestFunc func(ctx interface{}, origin interface{}) (last interface{}) 43 } 44 45 func (m *Modify) Path() string { 46 return m.TestPath 47 } 48 49 func (m *Modify) Valid(ctx interface{}) bool { 50 return true 51 } 52 53 func (m *Modify) Value(ctx interface{}, origin interface{}) (last interface{}) { 54 return m.TestFunc(ctx, origin) 55 } 56 57 func TestNewSourceVersion(t *testing.T) { 58 initSample() 59 60 ctx := &Context{} 61 root.RefSetContext(ctx) 62 63 assert.Equal(t, 1, root.RefInt("Int")) 64 root.RefSource().AddModify(&Modify{ 65 TestPath: "/Int", 66 TestFunc: func(ctx interface{}, origin interface{}) (last interface{}) { 67 return origin.(int) + 100 68 }, 69 }) 70 assert.Equal(t, 101, root.RefInt("Int")) 71 72 root.RefSource().AddModify(&Modify{ 73 TestPath: "/Int", 74 TestFunc: func(ctx interface{}, origin interface{}) (last interface{}) { 75 return origin.(int) - 1 76 }, 77 }) 78 assert.Equal(t, 100, root.RefInt("Int")) 79 80 } 81 func TestGetMap(t *testing.T) { 82 initSample() 83 84 getMap := root.RefMap("Map") 85 86 assert.Equal(t, false, getMap.RefIsNil()) 87 assert.Equal(t, 2, getMap.RefLength()) 88 assert.Equal(t, 1, getMap.RefInt("Int")) 89 assert.Equal(t, 1.0, getMap.RefFloat64("Float")) 90 91 assert.Equal(t, 101, getMap.RefInt("Int")) 92 } 93 94 func TestGetMapStruct(t *testing.T) { 95 initSample() 96 97 getObj := root.RefMap("MapStruct") 98 assert.Equal(t, false, getObj.RefIsNil()) 99 100 getObj0 := getObj.RefMap("0") 101 assert.Equal(t, 1, getObj0.RefInt("Int")) 102 assert.Equal(t, 1.0, getObj0.RefFloat64("Float")) 103 104 assert.Equal(t, 101, getObj0.RefInt("Int")) 105 } 106 107 func TestGetArrayInt(t *testing.T) { 108 initSample() 109 obj := root.RefArray("ArrayInt") 110 111 assert.Equal(t, 1, obj.RefInt(0)) 112 assert.Equal(t, 2, obj.RefInt(1)) 113 assert.Equal(t, 3, obj.RefInt(2)) 114 115 assert.Equal(t, 101, obj.RefInt(0)) 116 117 assert.Equal(t, 203, obj.RefInt(2)) 118 }