mutations_test.go 2.0 KB

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