util_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package util
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. )
  6. type testCloudConfig struct {
  7. Hostname string `yaml:"hostname,omitempty"`
  8. Key1 string `yaml:"key1,omitempty"`
  9. Key2 string `yaml:"key2,omitempty"`
  10. }
  11. func TestConvertMergesLeftIntoRight(t *testing.T) {
  12. assert := require.New(t)
  13. cc0 := testCloudConfig{Key1: "k1v0", Key2: "k2v0"}
  14. cc1 := map[interface{}]interface{}{"key1": "k1value1", "hostname": "somehost"}
  15. Convert(cc1, &cc0)
  16. expected := testCloudConfig{Hostname: "somehost", Key1: "k1value1", Key2: "k2v0"}
  17. assert.Equal(expected, cc0)
  18. }
  19. func NoTestCopyPointer(t *testing.T) {
  20. assert := require.New(t)
  21. testCCpt := &testCloudConfig{}
  22. m0 := map[string]interface{}{"a": testCCpt, "b": testCCpt}
  23. m1 := Copy(m0).(map[string]interface{})
  24. m1["a"].(*testCloudConfig).Hostname = "somehost"
  25. assert.Equal("", m0["a"].(*testCloudConfig).Hostname)
  26. assert.Equal("somehost", m1["a"].(*testCloudConfig).Hostname)
  27. assert.Equal("", m1["b"].(*testCloudConfig).Hostname)
  28. }
  29. func TestMapCopy(t *testing.T) {
  30. assert := require.New(t)
  31. m0 := map[interface{}]interface{}{"a": 1, "b": map[interface{}]interface{}{"c": 3}, "d": "4"}
  32. m1 := MapCopy(m0)
  33. assert.Equal(m0, m1)
  34. delete(m0, "a")
  35. assert.Equal(len(m1), len(m0)+1)
  36. b0 := m0["b"].(map[interface{}]interface{})
  37. b1 := m1["b"].(map[interface{}]interface{})
  38. b1["e"] = "queer"
  39. assert.Equal(len(b1), len(b0)+1)
  40. }
  41. func TestSliceCopy(t *testing.T) {
  42. assert := require.New(t)
  43. m0 := []interface{}{1, map[interface{}]interface{}{"c": 3}, "4"}
  44. m1 := SliceCopy(m0)
  45. assert.Equal(m0, m1)
  46. m0 = m0[1:]
  47. assert.Equal(len(m1), len(m0)+1)
  48. b0 := m0[0].(map[interface{}]interface{})
  49. b1 := m1[1].(map[interface{}]interface{})
  50. b1["e"] = "queer"
  51. assert.Equal(len(b1), len(b0)+1)
  52. }
  53. func TestMerge(t *testing.T) {
  54. assert := require.New(t)
  55. m0 := map[interface{}]interface{}{
  56. "a": 1,
  57. "b": map[interface{}]interface{}{"c": 3},
  58. "d": "4",
  59. "f": []interface{}{1, 2, 3},
  60. }
  61. m1 := MapCopy(m0)
  62. m1["e"] = "added"
  63. m1["d"] = "replaced"
  64. m1["f"] = []interface{}{2, 3, 4}
  65. delete(m0, "a")
  66. b1 := m1["b"].(map[interface{}]interface{})
  67. delete(b1, "c")
  68. expected := map[interface{}]interface{}{
  69. "a": 1,
  70. "b": map[interface{}]interface{}{"c": 3},
  71. "d": "replaced",
  72. "e": "added",
  73. "f": []interface{}{2, 3, 4},
  74. }
  75. assert.Equal(expected, Merge(m0, m1))
  76. }