helpers_test.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /*
  2. Copyright 2014 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 util
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "strings"
  19. "syscall"
  20. "testing"
  21. corev1 "k8s.io/api/core/v1"
  22. apiequality "k8s.io/apimachinery/pkg/api/equality"
  23. "k8s.io/apimachinery/pkg/api/errors"
  24. "k8s.io/apimachinery/pkg/api/meta"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/runtime"
  27. "k8s.io/apimachinery/pkg/runtime/schema"
  28. "k8s.io/apimachinery/pkg/util/diff"
  29. "k8s.io/apimachinery/pkg/util/validation/field"
  30. "k8s.io/kubernetes/pkg/kubectl/scheme"
  31. "k8s.io/utils/exec"
  32. )
  33. func TestMerge(t *testing.T) {
  34. tests := []struct {
  35. obj runtime.Object
  36. fragment string
  37. expected runtime.Object
  38. expectErr bool
  39. }{
  40. {
  41. obj: &corev1.Pod{
  42. ObjectMeta: metav1.ObjectMeta{
  43. Name: "foo",
  44. },
  45. },
  46. fragment: fmt.Sprintf(`{ "apiVersion": "%s" }`, "v1"),
  47. expected: &corev1.Pod{
  48. TypeMeta: metav1.TypeMeta{
  49. Kind: "Pod",
  50. APIVersion: "v1",
  51. },
  52. ObjectMeta: metav1.ObjectMeta{
  53. Name: "foo",
  54. },
  55. Spec: corev1.PodSpec{},
  56. },
  57. },
  58. /* TODO: uncomment this test once Merge is updated to use
  59. strategic-merge-patch. See #8449.
  60. {
  61. obj: &corev1.Pod{
  62. ObjectMeta: metav1.ObjectMeta{
  63. Name: "foo",
  64. },
  65. Spec: corev1.PodSpec{
  66. Containers: []corev1.Container{
  67. corev1.Container{
  68. Name: "c1",
  69. Image: "red-image",
  70. },
  71. corev1.Container{
  72. Name: "c2",
  73. Image: "blue-image",
  74. },
  75. },
  76. },
  77. },
  78. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "containers": [ { "name": "c1", "image": "green-image" } ] } }`, schema.GroupVersion{Group:"", Version: "v1"}.String()),
  79. expected: &corev1.Pod{
  80. ObjectMeta: metav1.ObjectMeta{
  81. Name: "foo",
  82. },
  83. Spec: corev1.PodSpec{
  84. Containers: []corev1.Container{
  85. corev1.Container{
  86. Name: "c1",
  87. Image: "green-image",
  88. },
  89. corev1.Container{
  90. Name: "c2",
  91. Image: "blue-image",
  92. },
  93. },
  94. },
  95. },
  96. }, */
  97. {
  98. obj: &corev1.Pod{
  99. ObjectMeta: metav1.ObjectMeta{
  100. Name: "foo",
  101. },
  102. },
  103. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "volumes": [ {"name": "v1"}, {"name": "v2"} ] } }`, "v1"),
  104. expected: &corev1.Pod{
  105. TypeMeta: metav1.TypeMeta{
  106. Kind: "Pod",
  107. APIVersion: "v1",
  108. },
  109. ObjectMeta: metav1.ObjectMeta{
  110. Name: "foo",
  111. },
  112. Spec: corev1.PodSpec{
  113. Volumes: []corev1.Volume{
  114. {
  115. Name: "v1",
  116. },
  117. {
  118. Name: "v2",
  119. },
  120. },
  121. },
  122. },
  123. },
  124. {
  125. obj: &corev1.Pod{},
  126. fragment: "invalid json",
  127. expected: &corev1.Pod{},
  128. expectErr: true,
  129. },
  130. {
  131. obj: &corev1.Service{},
  132. fragment: `{ "apiVersion": "badVersion" }`,
  133. expectErr: true,
  134. },
  135. {
  136. obj: &corev1.Service{
  137. Spec: corev1.ServiceSpec{},
  138. },
  139. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "ports": [ { "port": 0 } ] } }`, "v1"),
  140. expected: &corev1.Service{
  141. TypeMeta: metav1.TypeMeta{
  142. Kind: "Service",
  143. APIVersion: "v1",
  144. },
  145. Spec: corev1.ServiceSpec{
  146. Ports: []corev1.ServicePort{
  147. {
  148. Port: 0,
  149. },
  150. },
  151. },
  152. },
  153. },
  154. {
  155. obj: &corev1.Service{
  156. Spec: corev1.ServiceSpec{
  157. Selector: map[string]string{
  158. "version": "v1",
  159. },
  160. },
  161. },
  162. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "selector": { "version": "v2" } } }`, "v1"),
  163. expected: &corev1.Service{
  164. TypeMeta: metav1.TypeMeta{
  165. Kind: "Service",
  166. APIVersion: "v1",
  167. },
  168. Spec: corev1.ServiceSpec{
  169. Selector: map[string]string{
  170. "version": "v2",
  171. },
  172. },
  173. },
  174. },
  175. }
  176. codec := runtime.NewCodec(scheme.DefaultJSONEncoder(),
  177. scheme.Codecs.UniversalDecoder(scheme.Scheme.PrioritizedVersionsAllGroups()...))
  178. for i, test := range tests {
  179. out, err := Merge(codec, test.obj, test.fragment)
  180. if !test.expectErr {
  181. if err != nil {
  182. t.Errorf("testcase[%d], unexpected error: %v", i, err)
  183. } else if !apiequality.Semantic.DeepEqual(test.expected, out) {
  184. t.Errorf("\n\ntestcase[%d]\nexpected:\n%s", i, diff.ObjectReflectDiff(test.expected, out))
  185. }
  186. }
  187. if test.expectErr && err == nil {
  188. t.Errorf("testcase[%d], unexpected non-error", i)
  189. }
  190. }
  191. }
  192. type checkErrTestCase struct {
  193. err error
  194. expectedErr string
  195. expectedCode int
  196. }
  197. func TestCheckInvalidErr(t *testing.T) {
  198. testCheckError(t, []checkErrTestCase{
  199. {
  200. errors.NewInvalid(corev1.SchemeGroupVersion.WithKind("Invalid1").GroupKind(), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field"), "single", "details")}),
  201. "The Invalid1 \"invalidation\" is invalid: field: Invalid value: \"single\": details\n",
  202. DefaultErrorExitCode,
  203. },
  204. {
  205. errors.NewInvalid(corev1.SchemeGroupVersion.WithKind("Invalid2").GroupKind(), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field1"), "multi1", "details"), field.Invalid(field.NewPath("field2"), "multi2", "details")}),
  206. "The Invalid2 \"invalidation\" is invalid: \n* field1: Invalid value: \"multi1\": details\n* field2: Invalid value: \"multi2\": details\n",
  207. DefaultErrorExitCode,
  208. },
  209. {
  210. errors.NewInvalid(corev1.SchemeGroupVersion.WithKind("Invalid3").GroupKind(), "invalidation", field.ErrorList{}),
  211. "The Invalid3 \"invalidation\" is invalid",
  212. DefaultErrorExitCode,
  213. },
  214. {
  215. errors.NewInvalid(corev1.SchemeGroupVersion.WithKind("Invalid4").GroupKind(), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field4"), "multi4", "details"), field.Invalid(field.NewPath("field4"), "multi4", "details")}),
  216. "The Invalid4 \"invalidation\" is invalid: field4: Invalid value: \"multi4\": details\n",
  217. DefaultErrorExitCode,
  218. },
  219. })
  220. }
  221. func TestCheckNoResourceMatchError(t *testing.T) {
  222. testCheckError(t, []checkErrTestCase{
  223. {
  224. &meta.NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
  225. `the server doesn't have a resource type "foo"`,
  226. DefaultErrorExitCode,
  227. },
  228. {
  229. &meta.NoResourceMatchError{PartialResource: schema.GroupVersionResource{Version: "theversion", Resource: "foo"}},
  230. `the server doesn't have a resource type "foo" in version "theversion"`,
  231. DefaultErrorExitCode,
  232. },
  233. {
  234. &meta.NoResourceMatchError{PartialResource: schema.GroupVersionResource{Group: "thegroup", Version: "theversion", Resource: "foo"}},
  235. `the server doesn't have a resource type "foo" in group "thegroup" and version "theversion"`,
  236. DefaultErrorExitCode,
  237. },
  238. {
  239. &meta.NoResourceMatchError{PartialResource: schema.GroupVersionResource{Group: "thegroup", Resource: "foo"}},
  240. `the server doesn't have a resource type "foo" in group "thegroup"`,
  241. DefaultErrorExitCode,
  242. },
  243. })
  244. }
  245. func TestCheckExitError(t *testing.T) {
  246. testCheckError(t, []checkErrTestCase{
  247. {
  248. exec.CodeExitError{Err: fmt.Errorf("pod foo/bar terminated"), Code: 42},
  249. "pod foo/bar terminated",
  250. 42,
  251. },
  252. })
  253. }
  254. func testCheckError(t *testing.T, tests []checkErrTestCase) {
  255. var errReturned string
  256. var codeReturned int
  257. errHandle := func(err string, code int) {
  258. errReturned = err
  259. codeReturned = code
  260. }
  261. for _, test := range tests {
  262. checkErr(test.err, errHandle)
  263. if errReturned != test.expectedErr {
  264. t.Fatalf("Got: %s, expected: %s", errReturned, test.expectedErr)
  265. }
  266. if codeReturned != test.expectedCode {
  267. t.Fatalf("Got: %d, expected: %d", codeReturned, test.expectedCode)
  268. }
  269. }
  270. }
  271. func TestDumpReaderToFile(t *testing.T) {
  272. testString := "TEST STRING"
  273. tempFile, err := ioutil.TempFile("", "hlpers_test_dump_")
  274. if err != nil {
  275. t.Errorf("unexpected error setting up a temporary file %v", err)
  276. }
  277. defer syscall.Unlink(tempFile.Name())
  278. defer tempFile.Close()
  279. defer func() {
  280. if !t.Failed() {
  281. os.Remove(tempFile.Name())
  282. }
  283. }()
  284. err = DumpReaderToFile(strings.NewReader(testString), tempFile.Name())
  285. if err != nil {
  286. t.Errorf("error in DumpReaderToFile: %v", err)
  287. }
  288. data, err := ioutil.ReadFile(tempFile.Name())
  289. if err != nil {
  290. t.Errorf("error when reading %s: %v", tempFile.Name(), err)
  291. }
  292. stringData := string(data)
  293. if stringData != testString {
  294. t.Fatalf("Wrong file content %s != %s", testString, stringData)
  295. }
  296. }