utils_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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 staticpod
  14. import (
  15. "io/ioutil"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. "sort"
  20. "strconv"
  21. "testing"
  22. "github.com/lithammer/dedent"
  23. v1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  26. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  27. testutil "k8s.io/kubernetes/cmd/kubeadm/test"
  28. )
  29. func TestComponentResources(t *testing.T) {
  30. a := ComponentResources("250m")
  31. if a.Requests == nil {
  32. t.Errorf(
  33. "failed componentResources, return value was nil",
  34. )
  35. }
  36. }
  37. func TestGetAPIServerProbeAddress(t *testing.T) {
  38. tests := []struct {
  39. desc string
  40. endpoint *kubeadmapi.APIEndpoint
  41. expected string
  42. }{
  43. {
  44. desc: "nil endpoint returns 127.0.0.1",
  45. expected: "127.0.0.1",
  46. },
  47. {
  48. desc: "empty AdvertiseAddress endpoint returns 127.0.0.1",
  49. endpoint: &kubeadmapi.APIEndpoint{},
  50. expected: "127.0.0.1",
  51. },
  52. {
  53. desc: "filled in AdvertiseAddress endpoint returns it",
  54. endpoint: &kubeadmapi.APIEndpoint{
  55. AdvertiseAddress: "10.10.10.10",
  56. },
  57. expected: "10.10.10.10",
  58. },
  59. {
  60. desc: "filled in ipv6 AdvertiseAddress endpoint returns it",
  61. endpoint: &kubeadmapi.APIEndpoint{
  62. AdvertiseAddress: "2001:abcd:bcda::1",
  63. },
  64. expected: "2001:abcd:bcda::1",
  65. },
  66. {
  67. desc: "filled in 0.0.0.0 AdvertiseAddress endpoint returns empty",
  68. endpoint: &kubeadmapi.APIEndpoint{
  69. AdvertiseAddress: "0.0.0.0",
  70. },
  71. expected: "",
  72. },
  73. {
  74. desc: "filled in :: AdvertiseAddress endpoint returns empty",
  75. endpoint: &kubeadmapi.APIEndpoint{
  76. AdvertiseAddress: "::",
  77. },
  78. expected: "",
  79. },
  80. }
  81. for _, test := range tests {
  82. t.Run(test.desc, func(t *testing.T) {
  83. actual := GetAPIServerProbeAddress(test.endpoint)
  84. if actual != test.expected {
  85. t.Errorf("Unexpected result from GetAPIServerProbeAddress:\n\texpected: %s\n\tactual: %s", test.expected, actual)
  86. }
  87. })
  88. }
  89. }
  90. func TestGetControllerManagerProbeAddress(t *testing.T) {
  91. tests := []struct {
  92. desc string
  93. cfg *kubeadmapi.ClusterConfiguration
  94. expected string
  95. }{
  96. {
  97. desc: "no controller manager extra args leads to 127.0.0.1 being used",
  98. cfg: &kubeadmapi.ClusterConfiguration{
  99. ControllerManager: kubeadmapi.ControlPlaneComponent{
  100. ExtraArgs: map[string]string{},
  101. },
  102. },
  103. expected: "127.0.0.1",
  104. },
  105. {
  106. desc: "setting controller manager extra address arg to something acknowledges it",
  107. cfg: &kubeadmapi.ClusterConfiguration{
  108. ControllerManager: kubeadmapi.ControlPlaneComponent{
  109. ExtraArgs: map[string]string{
  110. kubeControllerManagerBindAddressArg: "10.10.10.10",
  111. },
  112. },
  113. },
  114. expected: "10.10.10.10",
  115. },
  116. {
  117. desc: "setting controller manager extra ipv6 address arg to something acknowledges it",
  118. cfg: &kubeadmapi.ClusterConfiguration{
  119. ControllerManager: kubeadmapi.ControlPlaneComponent{
  120. ExtraArgs: map[string]string{
  121. kubeControllerManagerBindAddressArg: "2001:abcd:bcda::1",
  122. },
  123. },
  124. },
  125. expected: "2001:abcd:bcda::1",
  126. },
  127. {
  128. desc: "setting controller manager extra address arg to 0.0.0.0 returns empty",
  129. cfg: &kubeadmapi.ClusterConfiguration{
  130. ControllerManager: kubeadmapi.ControlPlaneComponent{
  131. ExtraArgs: map[string]string{
  132. kubeControllerManagerBindAddressArg: "0.0.0.0",
  133. },
  134. },
  135. },
  136. expected: "",
  137. },
  138. {
  139. desc: "setting controller manager extra ipv6 address arg to :: returns empty",
  140. cfg: &kubeadmapi.ClusterConfiguration{
  141. ControllerManager: kubeadmapi.ControlPlaneComponent{
  142. ExtraArgs: map[string]string{
  143. kubeControllerManagerBindAddressArg: "::",
  144. },
  145. },
  146. },
  147. expected: "",
  148. },
  149. }
  150. for _, test := range tests {
  151. t.Run(test.desc, func(t *testing.T) {
  152. actual := GetControllerManagerProbeAddress(test.cfg)
  153. if actual != test.expected {
  154. t.Errorf("Unexpected result from GetControllerManagerProbeAddress:\n\texpected: %s\n\tactual: %s", test.expected, actual)
  155. }
  156. })
  157. }
  158. }
  159. func TestGetSchedulerProbeAddress(t *testing.T) {
  160. tests := []struct {
  161. desc string
  162. cfg *kubeadmapi.ClusterConfiguration
  163. expected string
  164. }{
  165. {
  166. desc: "no scheduler extra args leads to 127.0.0.1 being used",
  167. cfg: &kubeadmapi.ClusterConfiguration{
  168. Scheduler: kubeadmapi.ControlPlaneComponent{
  169. ExtraArgs: map[string]string{},
  170. },
  171. },
  172. expected: "127.0.0.1",
  173. },
  174. {
  175. desc: "setting scheduler extra address arg to something acknowledges it",
  176. cfg: &kubeadmapi.ClusterConfiguration{
  177. Scheduler: kubeadmapi.ControlPlaneComponent{
  178. ExtraArgs: map[string]string{
  179. kubeSchedulerBindAddressArg: "10.10.10.10",
  180. },
  181. },
  182. },
  183. expected: "10.10.10.10",
  184. },
  185. {
  186. desc: "setting scheduler extra ipv6 address arg to something acknowledges it",
  187. cfg: &kubeadmapi.ClusterConfiguration{
  188. Scheduler: kubeadmapi.ControlPlaneComponent{
  189. ExtraArgs: map[string]string{
  190. kubeSchedulerBindAddressArg: "2001:abcd:bcda::1",
  191. },
  192. },
  193. },
  194. expected: "2001:abcd:bcda::1",
  195. },
  196. {
  197. desc: "setting scheduler extra ipv6 address arg to 0.0.0.0 returns empty",
  198. cfg: &kubeadmapi.ClusterConfiguration{
  199. Scheduler: kubeadmapi.ControlPlaneComponent{
  200. ExtraArgs: map[string]string{
  201. kubeSchedulerBindAddressArg: "0.0.0.0",
  202. },
  203. },
  204. },
  205. expected: "",
  206. },
  207. {
  208. desc: "setting scheduler extra ipv6 address arg to :: returns empty",
  209. cfg: &kubeadmapi.ClusterConfiguration{
  210. Scheduler: kubeadmapi.ControlPlaneComponent{
  211. ExtraArgs: map[string]string{
  212. kubeSchedulerBindAddressArg: "::",
  213. },
  214. },
  215. },
  216. expected: "",
  217. },
  218. }
  219. for _, test := range tests {
  220. t.Run(test.desc, func(t *testing.T) {
  221. actual := GetSchedulerProbeAddress(test.cfg)
  222. if actual != test.expected {
  223. t.Errorf("Unexpected result from GetSchedulerProbeAddress:\n\texpected: %s\n\tactual: %s", test.expected, actual)
  224. }
  225. })
  226. }
  227. }
  228. func TestGetEtcdProbeEndpoint(t *testing.T) {
  229. var tests = []struct {
  230. name string
  231. cfg *kubeadmapi.Etcd
  232. isIPv6 bool
  233. expectedHostname string
  234. expectedPort int
  235. expectedScheme v1.URIScheme
  236. }{
  237. {
  238. name: "etcd probe URL from two URLs",
  239. cfg: &kubeadmapi.Etcd{
  240. Local: &kubeadmapi.LocalEtcd{
  241. ExtraArgs: map[string]string{
  242. "listen-metrics-urls": "https://1.2.3.4:1234,https://4.3.2.1:2381"},
  243. },
  244. },
  245. isIPv6: false,
  246. expectedHostname: "1.2.3.4",
  247. expectedPort: 1234,
  248. expectedScheme: v1.URISchemeHTTPS,
  249. },
  250. {
  251. name: "etcd probe URL with HTTP scheme",
  252. cfg: &kubeadmapi.Etcd{
  253. Local: &kubeadmapi.LocalEtcd{
  254. ExtraArgs: map[string]string{
  255. "listen-metrics-urls": "http://1.2.3.4:1234"},
  256. },
  257. },
  258. isIPv6: false,
  259. expectedHostname: "1.2.3.4",
  260. expectedPort: 1234,
  261. expectedScheme: v1.URISchemeHTTP,
  262. },
  263. {
  264. name: "etcd probe URL without scheme should result in defaults",
  265. cfg: &kubeadmapi.Etcd{
  266. Local: &kubeadmapi.LocalEtcd{
  267. ExtraArgs: map[string]string{
  268. "listen-metrics-urls": "1.2.3.4"},
  269. },
  270. },
  271. isIPv6: false,
  272. expectedHostname: "127.0.0.1",
  273. expectedPort: kubeadmconstants.EtcdMetricsPort,
  274. expectedScheme: v1.URISchemeHTTP,
  275. },
  276. {
  277. name: "etcd probe URL without port",
  278. cfg: &kubeadmapi.Etcd{
  279. Local: &kubeadmapi.LocalEtcd{
  280. ExtraArgs: map[string]string{
  281. "listen-metrics-urls": "https://1.2.3.4"},
  282. },
  283. },
  284. isIPv6: false,
  285. expectedHostname: "1.2.3.4",
  286. expectedPort: kubeadmconstants.EtcdMetricsPort,
  287. expectedScheme: v1.URISchemeHTTPS,
  288. },
  289. {
  290. name: "etcd probe URL from two IPv6 URLs",
  291. cfg: &kubeadmapi.Etcd{
  292. Local: &kubeadmapi.LocalEtcd{
  293. ExtraArgs: map[string]string{
  294. "listen-metrics-urls": "https://[2001:abcd:bcda::1]:1234,https://[2001:abcd:bcda::2]:2381"},
  295. },
  296. },
  297. isIPv6: true,
  298. expectedHostname: "2001:abcd:bcda::1",
  299. expectedPort: 1234,
  300. expectedScheme: v1.URISchemeHTTPS,
  301. },
  302. {
  303. name: "etcd probe localhost IPv6 URL with HTTP scheme",
  304. cfg: &kubeadmapi.Etcd{
  305. Local: &kubeadmapi.LocalEtcd{
  306. ExtraArgs: map[string]string{
  307. "listen-metrics-urls": "http://[::1]:1234"},
  308. },
  309. },
  310. isIPv6: true,
  311. expectedHostname: "::1",
  312. expectedPort: 1234,
  313. expectedScheme: v1.URISchemeHTTP,
  314. },
  315. {
  316. name: "etcd probe IPv6 URL with HTTP scheme",
  317. cfg: &kubeadmapi.Etcd{
  318. Local: &kubeadmapi.LocalEtcd{
  319. ExtraArgs: map[string]string{
  320. "listen-metrics-urls": "http://[2001:abcd:bcda::1]:1234"},
  321. },
  322. },
  323. isIPv6: true,
  324. expectedHostname: "2001:abcd:bcda::1",
  325. expectedPort: 1234,
  326. expectedScheme: v1.URISchemeHTTP,
  327. },
  328. {
  329. name: "etcd probe IPv6 URL without port",
  330. cfg: &kubeadmapi.Etcd{
  331. Local: &kubeadmapi.LocalEtcd{
  332. ExtraArgs: map[string]string{
  333. "listen-metrics-urls": "https://[2001:abcd:bcda::1]"},
  334. },
  335. },
  336. isIPv6: true,
  337. expectedHostname: "2001:abcd:bcda::1",
  338. expectedPort: kubeadmconstants.EtcdMetricsPort,
  339. expectedScheme: v1.URISchemeHTTPS,
  340. },
  341. {
  342. name: "etcd probe URL from defaults",
  343. cfg: &kubeadmapi.Etcd{
  344. Local: &kubeadmapi.LocalEtcd{},
  345. },
  346. isIPv6: false,
  347. expectedHostname: "127.0.0.1",
  348. expectedPort: kubeadmconstants.EtcdMetricsPort,
  349. expectedScheme: v1.URISchemeHTTP,
  350. },
  351. {
  352. name: "etcd probe URL from defaults if IPv6",
  353. cfg: &kubeadmapi.Etcd{
  354. Local: &kubeadmapi.LocalEtcd{},
  355. },
  356. isIPv6: true,
  357. expectedHostname: "::1",
  358. expectedPort: kubeadmconstants.EtcdMetricsPort,
  359. expectedScheme: v1.URISchemeHTTP,
  360. },
  361. }
  362. for _, rt := range tests {
  363. t.Run(rt.name, func(t *testing.T) {
  364. hostname, port, scheme := GetEtcdProbeEndpoint(rt.cfg, rt.isIPv6)
  365. if hostname != rt.expectedHostname {
  366. t.Errorf("%q test case failed:\n\texpected hostname: %s\n\tgot: %s",
  367. rt.name, rt.expectedHostname, hostname)
  368. }
  369. if port != rt.expectedPort {
  370. t.Errorf("%q test case failed:\n\texpected port: %d\n\tgot: %d",
  371. rt.name, rt.expectedPort, port)
  372. }
  373. if scheme != rt.expectedScheme {
  374. t.Errorf("%q test case failed:\n\texpected scheme: %v\n\tgot: %v",
  375. rt.name, rt.expectedScheme, scheme)
  376. }
  377. })
  378. }
  379. }
  380. func TestComponentPod(t *testing.T) {
  381. var tests = []struct {
  382. name string
  383. expected v1.Pod
  384. }{
  385. {
  386. name: "foo",
  387. expected: v1.Pod{
  388. TypeMeta: metav1.TypeMeta{
  389. APIVersion: "v1",
  390. Kind: "Pod",
  391. },
  392. ObjectMeta: metav1.ObjectMeta{
  393. Name: "foo",
  394. Namespace: "kube-system",
  395. Labels: map[string]string{"component": "foo", "tier": "control-plane"},
  396. },
  397. Spec: v1.PodSpec{
  398. Containers: []v1.Container{
  399. {
  400. Name: "foo",
  401. },
  402. },
  403. PriorityClassName: "system-cluster-critical",
  404. HostNetwork: true,
  405. Volumes: []v1.Volume{},
  406. },
  407. },
  408. },
  409. }
  410. for _, rt := range tests {
  411. t.Run(rt.name, func(t *testing.T) {
  412. c := v1.Container{Name: rt.name}
  413. actual := ComponentPod(c, map[string]v1.Volume{}, nil)
  414. if !reflect.DeepEqual(rt.expected, actual) {
  415. t.Errorf(
  416. "failed componentPod:\n\texpected: %v\n\t actual: %v",
  417. rt.expected,
  418. actual,
  419. )
  420. }
  421. })
  422. }
  423. }
  424. func TestNewVolume(t *testing.T) {
  425. hostPathDirectoryOrCreate := v1.HostPathDirectoryOrCreate
  426. var tests = []struct {
  427. name string
  428. path string
  429. expected v1.Volume
  430. pathType *v1.HostPathType
  431. }{
  432. {
  433. name: "foo",
  434. path: "/etc/foo",
  435. expected: v1.Volume{
  436. Name: "foo",
  437. VolumeSource: v1.VolumeSource{
  438. HostPath: &v1.HostPathVolumeSource{
  439. Path: "/etc/foo",
  440. Type: &hostPathDirectoryOrCreate,
  441. },
  442. },
  443. },
  444. pathType: &hostPathDirectoryOrCreate,
  445. },
  446. }
  447. for _, rt := range tests {
  448. t.Run(rt.name, func(t *testing.T) {
  449. actual := NewVolume(rt.name, rt.path, rt.pathType)
  450. if !reflect.DeepEqual(actual, rt.expected) {
  451. t.Errorf(
  452. "failed newVolume:\n\texpected: %v\n\t actual: %v",
  453. rt.expected,
  454. actual,
  455. )
  456. }
  457. })
  458. }
  459. }
  460. func TestNewVolumeMount(t *testing.T) {
  461. var tests = []struct {
  462. name string
  463. path string
  464. ro bool
  465. expected v1.VolumeMount
  466. }{
  467. {
  468. name: "foo",
  469. path: "/etc/foo",
  470. ro: false,
  471. expected: v1.VolumeMount{
  472. Name: "foo",
  473. MountPath: "/etc/foo",
  474. ReadOnly: false,
  475. },
  476. },
  477. {
  478. name: "bar",
  479. path: "/etc/foo/bar",
  480. ro: true,
  481. expected: v1.VolumeMount{
  482. Name: "bar",
  483. MountPath: "/etc/foo/bar",
  484. ReadOnly: true,
  485. },
  486. },
  487. }
  488. for _, rt := range tests {
  489. t.Run(rt.name, func(t *testing.T) {
  490. actual := NewVolumeMount(rt.name, rt.path, rt.ro)
  491. if !reflect.DeepEqual(actual, rt.expected) {
  492. t.Errorf(
  493. "failed newVolumeMount:\n\texpected: %v\n\t actual: %v",
  494. rt.expected,
  495. actual,
  496. )
  497. }
  498. })
  499. }
  500. }
  501. func TestVolumeMapToSlice(t *testing.T) {
  502. testVolumes := map[string]v1.Volume{
  503. "foo": {
  504. Name: "foo",
  505. },
  506. "bar": {
  507. Name: "bar",
  508. },
  509. }
  510. volumeSlice := VolumeMapToSlice(testVolumes)
  511. if len(volumeSlice) != 2 {
  512. t.Errorf("Expected slice length of 1, got %d", len(volumeSlice))
  513. }
  514. if volumeSlice[0].Name != "bar" {
  515. t.Errorf("Expected first volume name \"bar\", got %s", volumeSlice[0].Name)
  516. }
  517. if volumeSlice[1].Name != "foo" {
  518. t.Errorf("Expected second volume name \"foo\", got %s", volumeSlice[1].Name)
  519. }
  520. }
  521. func TestVolumeMountMapToSlice(t *testing.T) {
  522. testVolumeMounts := map[string]v1.VolumeMount{
  523. "foo": {
  524. Name: "foo",
  525. },
  526. "bar": {
  527. Name: "bar",
  528. },
  529. }
  530. volumeMountSlice := VolumeMountMapToSlice(testVolumeMounts)
  531. if len(volumeMountSlice) != 2 {
  532. t.Errorf("Expected slice length of 1, got %d", len(volumeMountSlice))
  533. }
  534. if volumeMountSlice[0].Name != "bar" {
  535. t.Errorf("Expected first volume mount name \"bar\", got %s", volumeMountSlice[0].Name)
  536. }
  537. if volumeMountSlice[1].Name != "foo" {
  538. t.Errorf("Expected second volume name \"foo\", got %s", volumeMountSlice[1].Name)
  539. }
  540. }
  541. func TestGetExtraParameters(t *testing.T) {
  542. var tests = []struct {
  543. name string
  544. overrides map[string]string
  545. defaults map[string]string
  546. expected []string
  547. }{
  548. {
  549. name: "with admission-control default NamespaceLifecycle",
  550. overrides: map[string]string{
  551. "admission-control": "NamespaceLifecycle,LimitRanger",
  552. },
  553. defaults: map[string]string{
  554. "admission-control": "NamespaceLifecycle",
  555. "insecure-bind-address": "127.0.0.1",
  556. "allow-privileged": "true",
  557. },
  558. expected: []string{
  559. "--admission-control=NamespaceLifecycle,LimitRanger",
  560. "--insecure-bind-address=127.0.0.1",
  561. "--allow-privileged=true",
  562. },
  563. },
  564. {
  565. name: "without admission-control default",
  566. overrides: map[string]string{
  567. "admission-control": "NamespaceLifecycle,LimitRanger",
  568. },
  569. defaults: map[string]string{
  570. "insecure-bind-address": "127.0.0.1",
  571. "allow-privileged": "true",
  572. },
  573. expected: []string{
  574. "--admission-control=NamespaceLifecycle,LimitRanger",
  575. "--insecure-bind-address=127.0.0.1",
  576. "--allow-privileged=true",
  577. },
  578. },
  579. }
  580. for _, rt := range tests {
  581. t.Run(rt.name, func(t *testing.T) {
  582. actual := GetExtraParameters(rt.overrides, rt.defaults)
  583. sort.Strings(actual)
  584. sort.Strings(rt.expected)
  585. if !reflect.DeepEqual(actual, rt.expected) {
  586. t.Errorf("failed getExtraParameters:\nexpected:\n%v\nsaw:\n%v", rt.expected, actual)
  587. }
  588. })
  589. }
  590. }
  591. const (
  592. validPod = `
  593. apiVersion: v1
  594. kind: Pod
  595. metadata:
  596. labels:
  597. component: etcd
  598. tier: control-plane
  599. name: etcd
  600. namespace: kube-system
  601. spec:
  602. containers:
  603. - image: gcr.io/google_containers/etcd-amd64:3.1.11
  604. status: {}
  605. `
  606. invalidPod = `---{ broken yaml @@@`
  607. )
  608. func TestReadStaticPodFromDisk(t *testing.T) {
  609. tests := []struct {
  610. description string
  611. podYaml string
  612. expectErr bool
  613. writeManifest bool
  614. }{
  615. {
  616. description: "valid pod is marshaled",
  617. podYaml: validPod,
  618. writeManifest: true,
  619. expectErr: false,
  620. },
  621. {
  622. description: "invalid pod fails to unmarshal",
  623. podYaml: invalidPod,
  624. writeManifest: true,
  625. expectErr: true,
  626. },
  627. {
  628. description: "non-existent file returns error",
  629. podYaml: ``,
  630. writeManifest: false,
  631. expectErr: true,
  632. },
  633. }
  634. for _, rt := range tests {
  635. t.Run(rt.description, func(t *testing.T) {
  636. tmpdir := testutil.SetupTempDir(t)
  637. defer os.RemoveAll(tmpdir)
  638. manifestPath := filepath.Join(tmpdir, "pod.yaml")
  639. if rt.writeManifest {
  640. err := ioutil.WriteFile(manifestPath, []byte(rt.podYaml), 0644)
  641. if err != nil {
  642. t.Fatalf("Failed to write pod manifest\n%s\n\tfatal error: %v", rt.description, err)
  643. }
  644. }
  645. _, actualErr := ReadStaticPodFromDisk(manifestPath)
  646. if (actualErr != nil) != rt.expectErr {
  647. t.Errorf(
  648. "ReadStaticPodFromDisk failed\n%s\n\texpected error: %t\n\tgot: %t\n\tactual error: %v",
  649. rt.description,
  650. rt.expectErr,
  651. (actualErr != nil),
  652. actualErr,
  653. )
  654. }
  655. })
  656. }
  657. }
  658. func TestManifestFilesAreEqual(t *testing.T) {
  659. var tests = []struct {
  660. description string
  661. podYamls []string
  662. expectedResult bool
  663. expectErr bool
  664. }{
  665. {
  666. description: "manifests are equal",
  667. podYamls: []string{validPod, validPod},
  668. expectedResult: true,
  669. expectErr: false,
  670. },
  671. {
  672. description: "manifests are not equal",
  673. podYamls: []string{validPod, validPod + "\n"},
  674. expectedResult: false,
  675. expectErr: false,
  676. },
  677. {
  678. description: "first manifest doesn't exist",
  679. podYamls: []string{validPod, ""},
  680. expectedResult: false,
  681. expectErr: true,
  682. },
  683. {
  684. description: "second manifest doesn't exist",
  685. podYamls: []string{"", validPod},
  686. expectedResult: false,
  687. expectErr: true,
  688. },
  689. }
  690. for _, rt := range tests {
  691. t.Run(rt.description, func(t *testing.T) {
  692. tmpdir := testutil.SetupTempDir(t)
  693. defer os.RemoveAll(tmpdir)
  694. // write 2 manifests
  695. for i := 0; i < 2; i++ {
  696. if rt.podYamls[i] != "" {
  697. manifestPath := filepath.Join(tmpdir, strconv.Itoa(i)+".yaml")
  698. err := ioutil.WriteFile(manifestPath, []byte(rt.podYamls[i]), 0644)
  699. if err != nil {
  700. t.Fatalf("Failed to write manifest file\n%s\n\tfatal error: %v", rt.description, err)
  701. }
  702. }
  703. }
  704. // compare them
  705. result, actualErr := ManifestFilesAreEqual(filepath.Join(tmpdir, "0.yaml"), filepath.Join(tmpdir, "1.yaml"))
  706. if result != rt.expectedResult {
  707. t.Errorf(
  708. "ManifestFilesAreEqual failed\n%s\nexpected result: %t\nactual result: %t",
  709. rt.description,
  710. rt.expectedResult,
  711. result,
  712. )
  713. }
  714. if (actualErr != nil) != rt.expectErr {
  715. t.Errorf(
  716. "ManifestFilesAreEqual failed\n%s\n\texpected error: %t\n\tgot: %t\n\tactual error: %v",
  717. rt.description,
  718. rt.expectErr,
  719. (actualErr != nil),
  720. actualErr,
  721. )
  722. }
  723. })
  724. }
  725. }
  726. func TestKustomizeStaticPod(t *testing.T) {
  727. // Create temp folder for the test case
  728. tmpdir := testutil.SetupTempDir(t)
  729. defer os.RemoveAll(tmpdir)
  730. patchString := dedent.Dedent(`
  731. apiVersion: v1
  732. kind: Pod
  733. metadata:
  734. name: kube-apiserver
  735. namespace: kube-system
  736. annotations:
  737. kustomize: patch for kube-apiserver
  738. `)
  739. err := ioutil.WriteFile(filepath.Join(tmpdir, "patch.yaml"), []byte(patchString), 0644)
  740. if err != nil {
  741. t.Fatalf("WriteFile returned unexpected error: %v", err)
  742. }
  743. pod := &v1.Pod{
  744. TypeMeta: metav1.TypeMeta{
  745. APIVersion: "v1",
  746. Kind: "Pod",
  747. },
  748. ObjectMeta: metav1.ObjectMeta{
  749. Name: "kube-apiserver",
  750. Namespace: "kube-system",
  751. },
  752. }
  753. kpod, err := KustomizeStaticPod(pod, tmpdir)
  754. if err != nil {
  755. t.Errorf("KustomizeStaticPod returned unexpected error: %v", err)
  756. }
  757. if _, ok := kpod.ObjectMeta.Annotations["kustomize"]; !ok {
  758. t.Error("Kustomize did not apply patches corresponding to the resource")
  759. }
  760. }