compatibility_tester.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compat
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "reflect"
  18. "regexp"
  19. "strconv"
  20. "strings"
  21. "testing"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apimachinery/pkg/runtime/schema"
  24. "k8s.io/apimachinery/pkg/util/validation/field"
  25. "k8s.io/kubernetes/pkg/api/legacyscheme"
  26. )
  27. // TestCompatibility reencodes the input using the codec for the given
  28. // version and checks for the presence of the expected keys and absent
  29. // keys in the resulting JSON.
  30. // Based on: https://github.com/openshift/origin/blob/master/pkg/api/compatibility_test.go
  31. func TestCompatibility(
  32. t *testing.T,
  33. version schema.GroupVersion,
  34. input []byte,
  35. validator func(obj runtime.Object) field.ErrorList,
  36. expectedKeys map[string]string,
  37. absentKeys []string,
  38. ) {
  39. // Decode
  40. codec := legacyscheme.Codecs.LegacyCodec(version)
  41. obj, err := runtime.Decode(codec, input)
  42. if err != nil {
  43. t.Fatalf("Unexpected error: %v", err)
  44. }
  45. // Validate
  46. errs := validator(obj)
  47. if len(errs) != 0 {
  48. t.Fatalf("Unexpected validation errors: %v", errs)
  49. }
  50. // Encode
  51. output, err := runtime.Encode(codec, obj)
  52. if err != nil {
  53. t.Fatalf("Unexpected error: %v", err)
  54. }
  55. // Validate old and new fields are encoded
  56. generic := map[string]interface{}{}
  57. if err := json.Unmarshal(output, &generic); err != nil {
  58. t.Fatalf("Unexpected error: %v", err)
  59. }
  60. for k, expectedValue := range expectedKeys {
  61. keys := strings.Split(k, ".")
  62. if actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok {
  63. t.Errorf("Unexpected error for %s: %v", k, err)
  64. } else if !reflect.DeepEqual(expectedValue, fmt.Sprintf("%v", actualValue)) {
  65. t.Errorf("Unexpected value for %v: expected %v, got %v", k, expectedValue, actualValue)
  66. }
  67. }
  68. for _, absentKey := range absentKeys {
  69. keys := strings.Split(absentKey, ".")
  70. actualValue, ok, err := getJSONValue(generic, keys...)
  71. if err == nil || ok {
  72. t.Errorf("Unexpected value found for key %s: %v", absentKey, actualValue)
  73. }
  74. }
  75. if t.Failed() {
  76. data, err := json.MarshalIndent(obj, "", " ")
  77. if err != nil {
  78. t.Log(err)
  79. } else {
  80. t.Log(string(data))
  81. }
  82. t.Logf("2: Encoded value: %v", string(output))
  83. }
  84. }
  85. func getJSONValue(data map[string]interface{}, keys ...string) (interface{}, bool, error) {
  86. // No keys, current value is it
  87. if len(keys) == 0 {
  88. return data, true, nil
  89. }
  90. // Get the key (and optional index)
  91. key := keys[0]
  92. index := -1
  93. if matches := regexp.MustCompile(`^(.*)\[(\d+)\]$`).FindStringSubmatch(key); len(matches) > 0 {
  94. key = matches[1]
  95. index, _ = strconv.Atoi(matches[2])
  96. }
  97. // Look up the value
  98. value, ok := data[key]
  99. if !ok {
  100. return nil, false, fmt.Errorf("No key %s found", key)
  101. }
  102. // Get the indexed value if an index is specified
  103. if index >= 0 {
  104. valueSlice, ok := value.([]interface{})
  105. if !ok {
  106. return nil, false, fmt.Errorf("Key %s did not hold a slice", key)
  107. }
  108. if index >= len(valueSlice) {
  109. return nil, false, fmt.Errorf("Index %d out of bounds for slice at key: %v", index, key)
  110. }
  111. value = valueSlice[index]
  112. }
  113. if len(keys) == 1 {
  114. return value, true, nil
  115. }
  116. childData, ok := value.(map[string]interface{})
  117. if !ok {
  118. return nil, false, fmt.Errorf("Key %s did not hold a map", keys[0])
  119. }
  120. return getJSONValue(childData, keys[1:]...)
  121. }