1package objx_test 2 3import ( 4 "strings" 5 "testing" 6 7 "github.com/stretchr/objx" 8 "github.com/stretchr/testify/assert" 9 "github.com/stretchr/testify/require" 10) 11 12func TestExclude(t *testing.T) { 13 m := objx.Map{ 14 "name": "Mat", 15 "age": 29, 16 "secret": "ABC", 17 } 18 19 excluded := m.Exclude([]string{"secret"}) 20 21 assert.Equal(t, m["name"], excluded["name"]) 22 assert.Equal(t, m["age"], excluded["age"]) 23 assert.False(t, excluded.Has("secret"), "secret should be excluded") 24} 25 26func TestCopy(t *testing.T) { 27 m1 := objx.Map{ 28 "name": "Tyler", 29 "location": "UT", 30 } 31 32 m2 := m1.Copy() 33 require.NotNil(t, m2) 34 m2["name"] = "Mat" 35 36 assert.Equal(t, m1.Get("name").Str(), "Tyler") 37 assert.Equal(t, m2.Get("name").Str(), "Mat") 38 39} 40 41func TestMerge(t *testing.T) { 42 m1 := objx.Map{ 43 "name": "Mat", 44 } 45 m2 := objx.Map{ 46 "name": "Tyler", 47 "location": "UT", 48 } 49 50 merged := m1.Merge(m2) 51 52 assert.Equal(t, merged.Get("name").Str(), m2.Get("name").Str()) 53 assert.Equal(t, merged.Get("location").Str(), m2.Get("location").Str()) 54 assert.Empty(t, m1.Get("location").Str()) 55} 56 57func TestMergeHere(t *testing.T) { 58 m1 := objx.Map{ 59 "name": "Mat", 60 } 61 m2 := objx.Map{ 62 "name": "Tyler", 63 "location": "UT", 64 } 65 66 merged := m1.MergeHere(m2) 67 68 assert.Equal(t, m1, merged, "With MergeHere, it should return the first modified map") 69 assert.Equal(t, merged.Get("name").Str(), m2.Get("name").Str()) 70 assert.Equal(t, merged.Get("location").Str(), m2.Get("location").Str()) 71 assert.Equal(t, merged.Get("location").Str(), m1.Get("location").Str()) 72} 73 74func TestTransform(t *testing.T) { 75 m := objx.Map{ 76 "name": "Mat", 77 "location": "UK", 78 } 79 r := m.Transform(keyToUpper) 80 assert.Equal(t, objx.Map{ 81 "NAME": "Mat", 82 "LOCATION": "UK", 83 }, r) 84} 85 86func TestTransformKeys(t *testing.T) { 87 m := objx.Map{ 88 "a": "1", 89 "b": "2", 90 "c": "3", 91 } 92 mapping := map[string]string{ 93 "a": "d", 94 "b": "e", 95 } 96 r := m.TransformKeys(mapping) 97 assert.Equal(t, objx.Map{ 98 "c": "3", 99 "d": "1", 100 "e": "2", 101 }, r) 102} 103 104func keyToUpper(s string, v interface{}) (string, interface{}) { 105 return strings.ToUpper(s), v 106} 107