unstructured_test.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. Copyright 2017 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 testing
  14. import (
  15. "math/rand"
  16. "reflect"
  17. "sort"
  18. "testing"
  19. fuzz "github.com/google/gofuzz"
  20. jsoniter "github.com/json-iterator/go"
  21. v1 "k8s.io/api/core/v1"
  22. "k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
  23. apiequality "k8s.io/apimachinery/pkg/api/equality"
  24. "k8s.io/apimachinery/pkg/api/meta"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. metaunstruct "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  27. "k8s.io/apimachinery/pkg/runtime"
  28. "k8s.io/apimachinery/pkg/runtime/schema"
  29. "k8s.io/apimachinery/pkg/util/diff"
  30. "k8s.io/apimachinery/pkg/util/json"
  31. "k8s.io/kubernetes/pkg/api/legacyscheme"
  32. "k8s.io/kubernetes/pkg/api/testapi"
  33. api "k8s.io/kubernetes/pkg/apis/core"
  34. )
  35. func doRoundTrip(t *testing.T, internalVersion schema.GroupVersion, externalVersion schema.GroupVersion, kind string) {
  36. // We do fuzzing on the internal version of the object, and only then
  37. // convert to the external version. This is because custom fuzzing
  38. // function are only supported for internal objects.
  39. internalObj, err := legacyscheme.Scheme.New(internalVersion.WithKind(kind))
  40. if err != nil {
  41. t.Fatalf("Couldn't create internal object %v: %v", kind, err)
  42. }
  43. seed := rand.Int63()
  44. fuzzer.FuzzerFor(FuzzerFuncs, rand.NewSource(seed), legacyscheme.Codecs).
  45. // We are explicitly overwriting custom fuzzing functions, to ensure
  46. // that InitContainers and their statuses are not generated. This is
  47. // because in thise test we are simply doing json operations, in which
  48. // those disappear.
  49. Funcs(
  50. func(s *api.PodSpec, c fuzz.Continue) {
  51. c.FuzzNoCustom(s)
  52. s.InitContainers = nil
  53. },
  54. func(s *api.PodStatus, c fuzz.Continue) {
  55. c.FuzzNoCustom(s)
  56. s.InitContainerStatuses = nil
  57. },
  58. ).Fuzz(internalObj)
  59. item, err := legacyscheme.Scheme.New(externalVersion.WithKind(kind))
  60. if err != nil {
  61. t.Fatalf("Couldn't create external object %v: %v", kind, err)
  62. }
  63. if err := legacyscheme.Scheme.Convert(internalObj, item, nil); err != nil {
  64. t.Fatalf("Conversion for %v failed: %v", kind, err)
  65. }
  66. data, err := json.Marshal(item)
  67. if err != nil {
  68. t.Errorf("Error when marshaling object: %v", err)
  69. return
  70. }
  71. unstr := make(map[string]interface{})
  72. err = json.Unmarshal(data, &unstr)
  73. if err != nil {
  74. t.Errorf("Error when unmarshaling to unstructured: %v", err)
  75. return
  76. }
  77. data, err = json.Marshal(unstr)
  78. if err != nil {
  79. t.Errorf("Error when marshaling unstructured: %v", err)
  80. return
  81. }
  82. unmarshalledObj := reflect.New(reflect.TypeOf(item).Elem()).Interface()
  83. err = json.Unmarshal(data, &unmarshalledObj)
  84. if err != nil {
  85. t.Errorf("Error when unmarshaling to object: %v", err)
  86. return
  87. }
  88. if !apiequality.Semantic.DeepEqual(item, unmarshalledObj) {
  89. t.Errorf("Object changed during JSON operations, diff: %v", diff.ObjectReflectDiff(item, unmarshalledObj))
  90. return
  91. }
  92. newUnstr, err := runtime.DefaultUnstructuredConverter.ToUnstructured(item)
  93. if err != nil {
  94. t.Errorf("ToUnstructured failed: %v", err)
  95. return
  96. }
  97. newObj := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
  98. err = runtime.DefaultUnstructuredConverter.FromUnstructured(newUnstr, newObj)
  99. if err != nil {
  100. t.Errorf("FromUnstructured failed: %v", err)
  101. return
  102. }
  103. if !apiequality.Semantic.DeepEqual(item, newObj) {
  104. t.Errorf("Object changed, diff: %v", diff.ObjectReflectDiff(item, newObj))
  105. }
  106. }
  107. func TestRoundTrip(t *testing.T) {
  108. for groupKey, group := range testapi.Groups {
  109. for kind := range legacyscheme.Scheme.KnownTypes(*group.GroupVersion()) {
  110. if nonRoundTrippableTypes.Has(kind) {
  111. continue
  112. }
  113. t.Logf("Testing: %v in %v", kind, groupKey)
  114. for i := 0; i < 50; i++ {
  115. doRoundTrip(t, schema.GroupVersion{Group: groupKey, Version: runtime.APIVersionInternal}, *group.GroupVersion(), kind)
  116. if t.Failed() {
  117. break
  118. }
  119. }
  120. }
  121. }
  122. }
  123. func TestRoundTripWithEmptyCreationTimestamp(t *testing.T) {
  124. for groupKey, group := range testapi.Groups {
  125. for kind := range legacyscheme.Scheme.KnownTypes(*group.GroupVersion()) {
  126. if nonRoundTrippableTypes.Has(kind) {
  127. continue
  128. }
  129. item, err := legacyscheme.Scheme.New(group.GroupVersion().WithKind(kind))
  130. if err != nil {
  131. t.Fatalf("Couldn't create external object %v: %v", kind, err)
  132. }
  133. t.Logf("Testing: %v in %v", kind, groupKey)
  134. unstrBody, err := runtime.DefaultUnstructuredConverter.ToUnstructured(item)
  135. if err != nil {
  136. t.Fatalf("ToUnstructured failed: %v", err)
  137. }
  138. unstructObj := &metaunstruct.Unstructured{}
  139. unstructObj.Object = unstrBody
  140. if meta, err := meta.Accessor(unstructObj); err == nil {
  141. meta.SetCreationTimestamp(metav1.Time{})
  142. } else {
  143. t.Fatalf("Unable to set creation timestamp: %v", err)
  144. }
  145. // attempt to re-convert unstructured object - conversion should not fail
  146. // based on empty metadata fields, such as creationTimestamp
  147. newObj := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
  148. err = runtime.DefaultUnstructuredConverter.FromUnstructured(unstructObj.Object, newObj)
  149. if err != nil {
  150. t.Fatalf("FromUnstructured failed: %v", err)
  151. }
  152. }
  153. }
  154. }
  155. func BenchmarkToUnstructured(b *testing.B) {
  156. items := benchmarkItems(b)
  157. size := len(items)
  158. convertor := runtime.DefaultUnstructuredConverter
  159. b.ResetTimer()
  160. for i := 0; i < b.N; i++ {
  161. unstr, err := convertor.ToUnstructured(&items[i%size])
  162. if err != nil || unstr == nil {
  163. b.Fatalf("unexpected error: %v", err)
  164. }
  165. }
  166. b.StopTimer()
  167. }
  168. func BenchmarkFromUnstructured(b *testing.B) {
  169. items := benchmarkItems(b)
  170. convertor := runtime.DefaultUnstructuredConverter
  171. var unstr []map[string]interface{}
  172. for i := range items {
  173. item, err := convertor.ToUnstructured(&items[i])
  174. if err != nil || item == nil {
  175. b.Fatalf("unexpected error: %v", err)
  176. }
  177. unstr = append(unstr, item)
  178. }
  179. size := len(items)
  180. b.ResetTimer()
  181. for i := 0; i < b.N; i++ {
  182. obj := v1.Pod{}
  183. if err := convertor.FromUnstructured(unstr[i%size], &obj); err != nil {
  184. b.Fatalf("unexpected error: %v", err)
  185. }
  186. }
  187. b.StopTimer()
  188. }
  189. func BenchmarkToUnstructuredViaJSON(b *testing.B) {
  190. items := benchmarkItems(b)
  191. var data [][]byte
  192. for i := range items {
  193. item, err := json.Marshal(&items[i])
  194. if err != nil {
  195. b.Fatalf("unexpected error: %v", err)
  196. }
  197. data = append(data, item)
  198. }
  199. size := len(items)
  200. b.ResetTimer()
  201. for i := 0; i < b.N; i++ {
  202. unstr := map[string]interface{}{}
  203. if err := json.Unmarshal(data[i%size], &unstr); err != nil {
  204. b.Fatalf("unexpected error: %v", err)
  205. }
  206. }
  207. b.StopTimer()
  208. }
  209. func BenchmarkFromUnstructuredViaJSON(b *testing.B) {
  210. items := benchmarkItems(b)
  211. var unstr []map[string]interface{}
  212. for i := range items {
  213. data, err := json.Marshal(&items[i])
  214. if err != nil {
  215. b.Fatalf("unexpected error: %v", err)
  216. }
  217. item := map[string]interface{}{}
  218. if err := json.Unmarshal(data, &item); err != nil {
  219. b.Fatalf("unexpected error: %v", err)
  220. }
  221. unstr = append(unstr, item)
  222. }
  223. size := len(items)
  224. b.ResetTimer()
  225. for i := 0; i < b.N; i++ {
  226. item, err := json.Marshal(unstr[i%size])
  227. if err != nil {
  228. b.Fatalf("unexpected error: %v", err)
  229. }
  230. obj := v1.Pod{}
  231. if err := json.Unmarshal(item, &obj); err != nil {
  232. b.Fatalf("unexpected error: %v", err)
  233. }
  234. }
  235. b.StopTimer()
  236. }
  237. func BenchmarkToUnstructuredViaJSONIter(b *testing.B) {
  238. items := benchmarkItems(b)
  239. size := len(items)
  240. var keys []string
  241. for k := range jsonIterConfig {
  242. keys = append(keys, k)
  243. }
  244. sort.Strings(keys)
  245. for _, name := range keys {
  246. c := jsonIterConfig[name]
  247. b.Run(name, func(b *testing.B) {
  248. b.ResetTimer()
  249. for i := 0; i < b.N; i++ {
  250. data, err := c.Marshal(&items[i%size])
  251. if err != nil {
  252. b.Fatalf("unexpected error: %v", err)
  253. }
  254. unstr := map[string]interface{}{}
  255. if err := c.Unmarshal(data, &unstr); err != nil {
  256. b.Fatalf("unexpected error: %v", err)
  257. }
  258. }
  259. b.StopTimer()
  260. })
  261. }
  262. }
  263. var jsonIterConfig = map[string]jsoniter.API{
  264. "default": jsoniter.ConfigDefault,
  265. "fastest": jsoniter.ConfigFastest,
  266. "compat": jsoniter.ConfigCompatibleWithStandardLibrary,
  267. }
  268. func BenchmarkFromUnstructuredViaJSONIter(b *testing.B) {
  269. items := benchmarkItems(b)
  270. var unstr []map[string]interface{}
  271. for i := range items {
  272. data, err := jsoniter.Marshal(&items[i])
  273. if err != nil {
  274. b.Fatalf("unexpected error: %v", err)
  275. }
  276. item := map[string]interface{}{}
  277. if err := json.Unmarshal(data, &item); err != nil {
  278. b.Fatalf("unexpected error: %v", err)
  279. }
  280. unstr = append(unstr, item)
  281. }
  282. size := len(items)
  283. var keys []string
  284. for k := range jsonIterConfig {
  285. keys = append(keys, k)
  286. }
  287. sort.Strings(keys)
  288. for _, name := range keys {
  289. c := jsonIterConfig[name]
  290. b.Run(name, func(b *testing.B) {
  291. b.ResetTimer()
  292. for i := 0; i < b.N; i++ {
  293. item, err := c.Marshal(unstr[i%size])
  294. if err != nil {
  295. b.Fatalf("unexpected error: %v", err)
  296. }
  297. obj := v1.Pod{}
  298. if err := c.Unmarshal(item, &obj); err != nil {
  299. b.Fatalf("unexpected error: %v", err)
  300. }
  301. }
  302. b.StopTimer()
  303. })
  304. }
  305. }