helpers_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. "net/http"
  18. "reflect"
  19. "strings"
  20. "syscall"
  21. "testing"
  22. "k8s.io/kubernetes/pkg/api"
  23. "k8s.io/kubernetes/pkg/api/errors"
  24. "k8s.io/kubernetes/pkg/api/meta"
  25. "k8s.io/kubernetes/pkg/api/testapi"
  26. apitesting "k8s.io/kubernetes/pkg/api/testing"
  27. "k8s.io/kubernetes/pkg/api/unversioned"
  28. "k8s.io/kubernetes/pkg/api/v1"
  29. "k8s.io/kubernetes/pkg/apis/extensions"
  30. "k8s.io/kubernetes/pkg/runtime"
  31. uexec "k8s.io/kubernetes/pkg/util/exec"
  32. "k8s.io/kubernetes/pkg/util/validation/field"
  33. )
  34. func TestMerge(t *testing.T) {
  35. grace := int64(30)
  36. tests := []struct {
  37. obj runtime.Object
  38. fragment string
  39. expected runtime.Object
  40. expectErr bool
  41. kind string
  42. }{
  43. {
  44. kind: "Pod",
  45. obj: &api.Pod{
  46. ObjectMeta: api.ObjectMeta{
  47. Name: "foo",
  48. },
  49. },
  50. fragment: fmt.Sprintf(`{ "apiVersion": "%s" }`, testapi.Default.GroupVersion().String()),
  51. expected: &api.Pod{
  52. ObjectMeta: api.ObjectMeta{
  53. Name: "foo",
  54. },
  55. Spec: apitesting.DeepEqualSafePodSpec(),
  56. },
  57. },
  58. /* TODO: uncomment this test once Merge is updated to use
  59. strategic-merge-patch. See #8449.
  60. {
  61. kind: "Pod",
  62. obj: &api.Pod{
  63. ObjectMeta: api.ObjectMeta{
  64. Name: "foo",
  65. },
  66. Spec: api.PodSpec{
  67. Containers: []api.Container{
  68. api.Container{
  69. Name: "c1",
  70. Image: "red-image",
  71. },
  72. api.Container{
  73. Name: "c2",
  74. Image: "blue-image",
  75. },
  76. },
  77. },
  78. },
  79. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "containers": [ { "name": "c1", "image": "green-image" } ] } }`, testapi.Default.GroupVersion().String()),
  80. expected: &api.Pod{
  81. ObjectMeta: api.ObjectMeta{
  82. Name: "foo",
  83. },
  84. Spec: api.PodSpec{
  85. Containers: []api.Container{
  86. api.Container{
  87. Name: "c1",
  88. Image: "green-image",
  89. },
  90. api.Container{
  91. Name: "c2",
  92. Image: "blue-image",
  93. },
  94. },
  95. },
  96. },
  97. }, */
  98. {
  99. kind: "Pod",
  100. obj: &api.Pod{
  101. ObjectMeta: api.ObjectMeta{
  102. Name: "foo",
  103. },
  104. },
  105. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "volumes": [ {"name": "v1"}, {"name": "v2"} ] } }`, testapi.Default.GroupVersion().String()),
  106. expected: &api.Pod{
  107. ObjectMeta: api.ObjectMeta{
  108. Name: "foo",
  109. },
  110. Spec: api.PodSpec{
  111. Volumes: []api.Volume{
  112. {
  113. Name: "v1",
  114. VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}},
  115. },
  116. {
  117. Name: "v2",
  118. VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}},
  119. },
  120. },
  121. RestartPolicy: api.RestartPolicyAlways,
  122. DNSPolicy: api.DNSClusterFirst,
  123. TerminationGracePeriodSeconds: &grace,
  124. SecurityContext: &api.PodSecurityContext{},
  125. },
  126. },
  127. },
  128. {
  129. kind: "Pod",
  130. obj: &api.Pod{},
  131. fragment: "invalid json",
  132. expected: &api.Pod{},
  133. expectErr: true,
  134. },
  135. {
  136. kind: "Service",
  137. obj: &api.Service{},
  138. fragment: `{ "apiVersion": "badVersion" }`,
  139. expectErr: true,
  140. },
  141. {
  142. kind: "Service",
  143. obj: &api.Service{
  144. Spec: api.ServiceSpec{},
  145. },
  146. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "ports": [ { "port": 0 } ] } }`, testapi.Default.GroupVersion().String()),
  147. expected: &api.Service{
  148. Spec: api.ServiceSpec{
  149. SessionAffinity: "None",
  150. Type: api.ServiceTypeClusterIP,
  151. Ports: []api.ServicePort{
  152. {
  153. Protocol: api.ProtocolTCP,
  154. Port: 0,
  155. },
  156. },
  157. },
  158. },
  159. },
  160. {
  161. kind: "Service",
  162. obj: &api.Service{
  163. Spec: api.ServiceSpec{
  164. Selector: map[string]string{
  165. "version": "v1",
  166. },
  167. },
  168. },
  169. fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "selector": { "version": "v2" } } }`, testapi.Default.GroupVersion().String()),
  170. expected: &api.Service{
  171. Spec: api.ServiceSpec{
  172. SessionAffinity: "None",
  173. Type: api.ServiceTypeClusterIP,
  174. Selector: map[string]string{
  175. "version": "v2",
  176. },
  177. },
  178. },
  179. },
  180. }
  181. for i, test := range tests {
  182. out, err := Merge(testapi.Default.Codec(), test.obj, test.fragment, test.kind)
  183. if !test.expectErr {
  184. if err != nil {
  185. t.Errorf("testcase[%d], unexpected error: %v", i, err)
  186. } else if !reflect.DeepEqual(out, test.expected) {
  187. t.Errorf("\n\ntestcase[%d]\nexpected:\n%+v\nsaw:\n%+v", i, test.expected, out)
  188. }
  189. }
  190. if test.expectErr && err == nil {
  191. t.Errorf("testcase[%d], unexpected non-error", i)
  192. }
  193. }
  194. }
  195. type fileHandler struct {
  196. data []byte
  197. }
  198. func (f *fileHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
  199. if req.URL.Path == "/error" {
  200. res.WriteHeader(http.StatusNotFound)
  201. return
  202. }
  203. res.WriteHeader(http.StatusOK)
  204. res.Write(f.data)
  205. }
  206. type checkErrTestCase struct {
  207. err error
  208. expectedErr string
  209. expectedCode int
  210. }
  211. func TestCheckInvalidErr(t *testing.T) {
  212. testCheckError(t, []checkErrTestCase{
  213. {
  214. errors.NewInvalid(api.Kind("Invalid1"), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field"), "single", "details")}),
  215. "The Invalid1 \"invalidation\" is invalid: field: Invalid value: \"single\": details\n",
  216. DefaultErrorExitCode,
  217. },
  218. {
  219. errors.NewInvalid(api.Kind("Invalid2"), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field1"), "multi1", "details"), field.Invalid(field.NewPath("field2"), "multi2", "details")}),
  220. "The Invalid2 \"invalidation\" is invalid: \n* field1: Invalid value: \"multi1\": details\n* field2: Invalid value: \"multi2\": details\n",
  221. DefaultErrorExitCode,
  222. },
  223. {
  224. errors.NewInvalid(api.Kind("Invalid3"), "invalidation", field.ErrorList{}),
  225. "The Invalid3 \"invalidation\" is invalid",
  226. DefaultErrorExitCode,
  227. },
  228. {
  229. errors.NewInvalid(api.Kind("Invalid4"), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field4"), "multi4", "details"), field.Invalid(field.NewPath("field4"), "multi4", "details")}),
  230. "The Invalid4 \"invalidation\" is invalid: field4: Invalid value: \"multi4\": details\n",
  231. DefaultErrorExitCode,
  232. },
  233. })
  234. }
  235. func TestCheckNoResourceMatchError(t *testing.T) {
  236. testCheckError(t, []checkErrTestCase{
  237. {
  238. &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}},
  239. `the server doesn't have a resource type "foo"`,
  240. DefaultErrorExitCode,
  241. },
  242. {
  243. &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Version: "theversion", Resource: "foo"}},
  244. `the server doesn't have a resource type "foo" in version "theversion"`,
  245. DefaultErrorExitCode,
  246. },
  247. {
  248. &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Group: "thegroup", Version: "theversion", Resource: "foo"}},
  249. `the server doesn't have a resource type "foo" in group "thegroup" and version "theversion"`,
  250. DefaultErrorExitCode,
  251. },
  252. {
  253. &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Group: "thegroup", Resource: "foo"}},
  254. `the server doesn't have a resource type "foo" in group "thegroup"`,
  255. DefaultErrorExitCode,
  256. },
  257. })
  258. }
  259. func TestCheckExitError(t *testing.T) {
  260. testCheckError(t, []checkErrTestCase{
  261. {
  262. uexec.CodeExitError{Err: fmt.Errorf("pod foo/bar terminated"), Code: 42},
  263. "",
  264. 42,
  265. },
  266. })
  267. }
  268. func testCheckError(t *testing.T, tests []checkErrTestCase) {
  269. var errReturned string
  270. var codeReturned int
  271. errHandle := func(err string, code int) {
  272. errReturned = err
  273. codeReturned = code
  274. }
  275. for _, test := range tests {
  276. checkErr("", test.err, errHandle)
  277. if errReturned != test.expectedErr {
  278. t.Fatalf("Got: %s, expected: %s", errReturned, test.expectedErr)
  279. }
  280. if codeReturned != test.expectedCode {
  281. t.Fatalf("Got: %d, expected: %d", codeReturned, test.expectedCode)
  282. }
  283. }
  284. }
  285. func TestDumpReaderToFile(t *testing.T) {
  286. testString := "TEST STRING"
  287. tempFile, err := ioutil.TempFile("", "hlpers_test_dump_")
  288. if err != nil {
  289. t.Errorf("unexpected error setting up a temporary file %v", err)
  290. }
  291. defer syscall.Unlink(tempFile.Name())
  292. defer tempFile.Close()
  293. err = DumpReaderToFile(strings.NewReader(testString), tempFile.Name())
  294. if err != nil {
  295. t.Errorf("error in DumpReaderToFile: %v", err)
  296. }
  297. data, err := ioutil.ReadFile(tempFile.Name())
  298. if err != nil {
  299. t.Errorf("error when reading %s: %v", tempFile.Name(), err)
  300. }
  301. stringData := string(data)
  302. if stringData != testString {
  303. t.Fatalf("Wrong file content %s != %s", testString, stringData)
  304. }
  305. }
  306. func TestMaybeConvert(t *testing.T) {
  307. tests := []struct {
  308. input runtime.Object
  309. gv unversioned.GroupVersion
  310. expected runtime.Object
  311. }{
  312. {
  313. input: &api.Pod{
  314. ObjectMeta: api.ObjectMeta{
  315. Name: "foo",
  316. },
  317. },
  318. gv: unversioned.GroupVersion{Group: "", Version: "v1"},
  319. expected: &v1.Pod{
  320. TypeMeta: unversioned.TypeMeta{
  321. APIVersion: "v1",
  322. Kind: "Pod",
  323. },
  324. ObjectMeta: v1.ObjectMeta{
  325. Name: "foo",
  326. },
  327. },
  328. },
  329. {
  330. input: &extensions.ThirdPartyResourceData{
  331. ObjectMeta: api.ObjectMeta{
  332. Name: "foo",
  333. },
  334. Data: []byte("this is some data"),
  335. },
  336. expected: &extensions.ThirdPartyResourceData{
  337. ObjectMeta: api.ObjectMeta{
  338. Name: "foo",
  339. },
  340. Data: []byte("this is some data"),
  341. },
  342. },
  343. }
  344. for _, test := range tests {
  345. obj, err := MaybeConvertObject(test.input, test.gv, testapi.Default.Converter())
  346. if err != nil {
  347. t.Errorf("unexpected error: %v", err)
  348. }
  349. if !reflect.DeepEqual(test.expected, obj) {
  350. t.Errorf("expected:\n%#v\nsaw:\n%#v\n", test.expected, obj)
  351. }
  352. }
  353. }