compatibility_tester.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. "os"
  18. "reflect"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "testing"
  23. "k8s.io/kubernetes/pkg/api"
  24. "k8s.io/kubernetes/pkg/api/unversioned"
  25. "k8s.io/kubernetes/pkg/kubectl"
  26. "k8s.io/kubernetes/pkg/runtime"
  27. "k8s.io/kubernetes/pkg/util/validation/field"
  28. )
  29. // Based on: https://github.com/openshift/origin/blob/master/pkg/api/compatibility_test.go
  30. //
  31. // TestCompatibility reencodes the input using the codec for the given
  32. // version and checks for the presence of the expected keys and absent
  33. // keys in the resulting JSON.
  34. func TestCompatibility(
  35. t *testing.T,
  36. version unversioned.GroupVersion,
  37. input []byte,
  38. validator func(obj runtime.Object) field.ErrorList,
  39. expectedKeys map[string]string,
  40. absentKeys []string,
  41. ) {
  42. // Decode
  43. codec := api.Codecs.LegacyCodec(version)
  44. obj, err := runtime.Decode(codec, input)
  45. if err != nil {
  46. t.Fatalf("Unexpected error: %v", err)
  47. }
  48. // Validate
  49. errs := validator(obj)
  50. if len(errs) != 0 {
  51. t.Fatalf("Unexpected validation errors: %v", errs)
  52. }
  53. // Encode
  54. output, err := runtime.Encode(codec, obj)
  55. if err != nil {
  56. t.Fatalf("Unexpected error: %v", err)
  57. }
  58. // Validate old and new fields are encoded
  59. generic := map[string]interface{}{}
  60. if err := json.Unmarshal(output, &generic); err != nil {
  61. t.Fatalf("Unexpected error: %v", err)
  62. }
  63. hasError := false
  64. for k, expectedValue := range expectedKeys {
  65. keys := strings.Split(k, ".")
  66. if actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok {
  67. t.Errorf("Unexpected error for %s: %v", k, err)
  68. hasError = true
  69. } else if !reflect.DeepEqual(expectedValue, fmt.Sprintf("%v", actualValue)) {
  70. hasError = true
  71. t.Errorf("Unexpected value for %v: expected %v, got %v", k, expectedValue, actualValue)
  72. }
  73. }
  74. for _, absentKey := range absentKeys {
  75. keys := strings.Split(absentKey, ".")
  76. actualValue, ok, err := getJSONValue(generic, keys...)
  77. if err == nil || ok {
  78. t.Errorf("Unexpected value found for key %s: %v", absentKey, actualValue)
  79. hasError = true
  80. }
  81. }
  82. if hasError {
  83. printer := new(kubectl.JSONPrinter)
  84. printer.PrintObj(obj, os.Stdout)
  85. t.Logf("2: Encoded value: %#v", string(output))
  86. }
  87. }
  88. func getJSONValue(data map[string]interface{}, keys ...string) (interface{}, bool, error) {
  89. // No keys, current value is it
  90. if len(keys) == 0 {
  91. return data, true, nil
  92. }
  93. // Get the key (and optional index)
  94. key := keys[0]
  95. index := -1
  96. if matches := regexp.MustCompile(`^(.*)\[(\d+)\]$`).FindStringSubmatch(key); len(matches) > 0 {
  97. key = matches[1]
  98. index, _ = strconv.Atoi(matches[2])
  99. }
  100. // Look up the value
  101. value, ok := data[key]
  102. if !ok {
  103. return nil, false, fmt.Errorf("No key %s found", key)
  104. }
  105. // Get the indexed value if an index is specified
  106. if index >= 0 {
  107. valueSlice, ok := value.([]interface{})
  108. if !ok {
  109. return nil, false, fmt.Errorf("Key %s did not hold a slice", key)
  110. }
  111. if index >= len(valueSlice) {
  112. return nil, false, fmt.Errorf("Index %d out of bounds for slice at key: %v", index, key)
  113. }
  114. value = valueSlice[index]
  115. }
  116. if len(keys) == 1 {
  117. return value, true, nil
  118. }
  119. childData, ok := value.(map[string]interface{})
  120. if !ok {
  121. return nil, false, fmt.Errorf("Key %s did not hold a map", keys[0])
  122. }
  123. return getJSONValue(childData, keys[1:]...)
  124. }