contract_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. // Copyright (C) 2020 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package contract
  7. import (
  8. "reflect"
  9. "testing"
  10. )
  11. type PtrStruct struct {
  12. A string `since:"2"`
  13. B map[string]int `since:"3"`
  14. }
  15. type Nested struct {
  16. A float32 `since:"4"`
  17. B [4]int `since:"5"`
  18. C bool `since:"1"`
  19. }
  20. type TestStruct struct {
  21. A int
  22. B map[string]string `since:"1"`
  23. C []string `since:"2"`
  24. Nested Nested `since:"3"`
  25. Ptr *PtrStruct `since:"2"`
  26. }
  27. func testValue() TestStruct {
  28. return TestStruct{
  29. A: 1,
  30. B: map[string]string{
  31. "foo": "bar",
  32. },
  33. C: []string{"a", "b"},
  34. Nested: Nested{
  35. A: 0.10,
  36. B: [4]int{1, 2, 3, 4},
  37. C: true,
  38. },
  39. Ptr: &PtrStruct{
  40. A: "value",
  41. B: map[string]int{
  42. "x": 1,
  43. "b": 2,
  44. },
  45. },
  46. }
  47. }
  48. func TestClean(t *testing.T) {
  49. expect(t, 0, TestStruct{})
  50. expect(t, 1, TestStruct{
  51. // A unset, since it does not have "since"
  52. B: map[string]string{
  53. "foo": "bar",
  54. },
  55. })
  56. expect(t, 2, TestStruct{
  57. // A unset, since it does not have "since"
  58. B: map[string]string{
  59. "foo": "bar",
  60. },
  61. C: []string{"a", "b"},
  62. Ptr: &PtrStruct{
  63. A: "value",
  64. },
  65. })
  66. expect(t, 3, TestStruct{
  67. // A unset, since it does not have "since"
  68. B: map[string]string{
  69. "foo": "bar",
  70. },
  71. C: []string{"a", "b"},
  72. Nested: Nested{
  73. C: true,
  74. },
  75. Ptr: &PtrStruct{
  76. A: "value",
  77. B: map[string]int{
  78. "x": 1,
  79. "b": 2,
  80. },
  81. },
  82. })
  83. expect(t, 4, TestStruct{
  84. // A unset, since it does not have "since"
  85. B: map[string]string{
  86. "foo": "bar",
  87. },
  88. C: []string{"a", "b"},
  89. Nested: Nested{
  90. A: 0.10,
  91. C: true,
  92. },
  93. Ptr: &PtrStruct{
  94. A: "value",
  95. B: map[string]int{
  96. "x": 1,
  97. "b": 2,
  98. },
  99. },
  100. })
  101. x := testValue()
  102. x.A = 0
  103. expect(t, 5, x)
  104. expect(t, 6, x)
  105. }
  106. func expect(t *testing.T, since int, b interface{}) {
  107. t.Helper()
  108. x := testValue()
  109. if err := clear(&x, since); err != nil {
  110. t.Fatal(err.Error())
  111. }
  112. if !reflect.DeepEqual(x, b) {
  113. t.Errorf("%#v != %#v", x, b)
  114. }
  115. }