util_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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 pod
  14. import (
  15. "reflect"
  16. "strings"
  17. "testing"
  18. "time"
  19. "github.com/stretchr/testify/assert"
  20. "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/util/intstr"
  23. "k8s.io/apimachinery/pkg/util/sets"
  24. "k8s.io/apimachinery/pkg/util/validation/field"
  25. )
  26. func TestFindPort(t *testing.T) {
  27. testCases := []struct {
  28. name string
  29. containers []v1.Container
  30. port intstr.IntOrString
  31. expected int
  32. pass bool
  33. }{{
  34. name: "valid int, no ports",
  35. containers: []v1.Container{{}},
  36. port: intstr.FromInt(93),
  37. expected: 93,
  38. pass: true,
  39. }, {
  40. name: "valid int, with ports",
  41. containers: []v1.Container{{Ports: []v1.ContainerPort{{
  42. Name: "",
  43. ContainerPort: 11,
  44. Protocol: "TCP",
  45. }, {
  46. Name: "p",
  47. ContainerPort: 22,
  48. Protocol: "TCP",
  49. }}}},
  50. port: intstr.FromInt(93),
  51. expected: 93,
  52. pass: true,
  53. }, {
  54. name: "valid str, no ports",
  55. containers: []v1.Container{{}},
  56. port: intstr.FromString("p"),
  57. expected: 0,
  58. pass: false,
  59. }, {
  60. name: "valid str, one ctr with ports",
  61. containers: []v1.Container{{Ports: []v1.ContainerPort{{
  62. Name: "",
  63. ContainerPort: 11,
  64. Protocol: "UDP",
  65. }, {
  66. Name: "p",
  67. ContainerPort: 22,
  68. Protocol: "TCP",
  69. }, {
  70. Name: "q",
  71. ContainerPort: 33,
  72. Protocol: "TCP",
  73. }}}},
  74. port: intstr.FromString("q"),
  75. expected: 33,
  76. pass: true,
  77. }, {
  78. name: "valid str, two ctr with ports",
  79. containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
  80. Name: "",
  81. ContainerPort: 11,
  82. Protocol: "UDP",
  83. }, {
  84. Name: "p",
  85. ContainerPort: 22,
  86. Protocol: "TCP",
  87. }, {
  88. Name: "q",
  89. ContainerPort: 33,
  90. Protocol: "TCP",
  91. }}}},
  92. port: intstr.FromString("q"),
  93. expected: 33,
  94. pass: true,
  95. }, {
  96. name: "valid str, two ctr with same port",
  97. containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
  98. Name: "",
  99. ContainerPort: 11,
  100. Protocol: "UDP",
  101. }, {
  102. Name: "p",
  103. ContainerPort: 22,
  104. Protocol: "TCP",
  105. }, {
  106. Name: "q",
  107. ContainerPort: 22,
  108. Protocol: "TCP",
  109. }}}},
  110. port: intstr.FromString("q"),
  111. expected: 22,
  112. pass: true,
  113. }, {
  114. name: "valid str, invalid protocol",
  115. containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
  116. Name: "a",
  117. ContainerPort: 11,
  118. Protocol: "snmp",
  119. },
  120. }}},
  121. port: intstr.FromString("a"),
  122. expected: 0,
  123. pass: false,
  124. }, {
  125. name: "valid hostPort",
  126. containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
  127. Name: "a",
  128. ContainerPort: 11,
  129. HostPort: 81,
  130. Protocol: "TCP",
  131. },
  132. }}},
  133. port: intstr.FromString("a"),
  134. expected: 11,
  135. pass: true,
  136. },
  137. {
  138. name: "invalid hostPort",
  139. containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
  140. Name: "a",
  141. ContainerPort: 11,
  142. HostPort: -1,
  143. Protocol: "TCP",
  144. },
  145. }}},
  146. port: intstr.FromString("a"),
  147. expected: 11,
  148. pass: true,
  149. //this should fail but passes.
  150. },
  151. {
  152. name: "invalid ContainerPort",
  153. containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
  154. Name: "a",
  155. ContainerPort: -1,
  156. Protocol: "TCP",
  157. },
  158. }}},
  159. port: intstr.FromString("a"),
  160. expected: -1,
  161. pass: true,
  162. //this should fail but passes
  163. },
  164. {
  165. name: "HostIP Address",
  166. containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
  167. Name: "a",
  168. ContainerPort: 11,
  169. HostIP: "192.168.1.1",
  170. Protocol: "TCP",
  171. },
  172. }}},
  173. port: intstr.FromString("a"),
  174. expected: 11,
  175. pass: true,
  176. },
  177. }
  178. for _, tc := range testCases {
  179. port, err := FindPort(&v1.Pod{Spec: v1.PodSpec{Containers: tc.containers}},
  180. &v1.ServicePort{Protocol: "TCP", TargetPort: tc.port})
  181. if err != nil && tc.pass {
  182. t.Errorf("unexpected error for %s: %v", tc.name, err)
  183. }
  184. if err == nil && !tc.pass {
  185. t.Errorf("unexpected non-error for %s: %d", tc.name, port)
  186. }
  187. if port != tc.expected {
  188. t.Errorf("wrong result for %s: expected %d, got %d", tc.name, tc.expected, port)
  189. }
  190. }
  191. }
  192. func TestPodSecrets(t *testing.T) {
  193. // Stub containing all possible secret references in a pod.
  194. // The names of the referenced secrets match struct paths detected by reflection.
  195. pod := &v1.Pod{
  196. Spec: v1.PodSpec{
  197. Containers: []v1.Container{{
  198. EnvFrom: []v1.EnvFromSource{{
  199. SecretRef: &v1.SecretEnvSource{
  200. LocalObjectReference: v1.LocalObjectReference{
  201. Name: "Spec.Containers[*].EnvFrom[*].SecretRef"}}}},
  202. Env: []v1.EnvVar{{
  203. ValueFrom: &v1.EnvVarSource{
  204. SecretKeyRef: &v1.SecretKeySelector{
  205. LocalObjectReference: v1.LocalObjectReference{
  206. Name: "Spec.Containers[*].Env[*].ValueFrom.SecretKeyRef"}}}}}}},
  207. ImagePullSecrets: []v1.LocalObjectReference{{
  208. Name: "Spec.ImagePullSecrets"}},
  209. InitContainers: []v1.Container{{
  210. EnvFrom: []v1.EnvFromSource{{
  211. SecretRef: &v1.SecretEnvSource{
  212. LocalObjectReference: v1.LocalObjectReference{
  213. Name: "Spec.InitContainers[*].EnvFrom[*].SecretRef"}}}},
  214. Env: []v1.EnvVar{{
  215. ValueFrom: &v1.EnvVarSource{
  216. SecretKeyRef: &v1.SecretKeySelector{
  217. LocalObjectReference: v1.LocalObjectReference{
  218. Name: "Spec.InitContainers[*].Env[*].ValueFrom.SecretKeyRef"}}}}}}},
  219. Volumes: []v1.Volume{{
  220. VolumeSource: v1.VolumeSource{
  221. AzureFile: &v1.AzureFileVolumeSource{
  222. SecretName: "Spec.Volumes[*].VolumeSource.AzureFile.SecretName"}}}, {
  223. VolumeSource: v1.VolumeSource{
  224. CephFS: &v1.CephFSVolumeSource{
  225. SecretRef: &v1.LocalObjectReference{
  226. Name: "Spec.Volumes[*].VolumeSource.CephFS.SecretRef"}}}}, {
  227. VolumeSource: v1.VolumeSource{
  228. Cinder: &v1.CinderVolumeSource{
  229. SecretRef: &v1.LocalObjectReference{
  230. Name: "Spec.Volumes[*].VolumeSource.Cinder.SecretRef"}}}}, {
  231. VolumeSource: v1.VolumeSource{
  232. FlexVolume: &v1.FlexVolumeSource{
  233. SecretRef: &v1.LocalObjectReference{
  234. Name: "Spec.Volumes[*].VolumeSource.FlexVolume.SecretRef"}}}}, {
  235. VolumeSource: v1.VolumeSource{
  236. Projected: &v1.ProjectedVolumeSource{
  237. Sources: []v1.VolumeProjection{{
  238. Secret: &v1.SecretProjection{
  239. LocalObjectReference: v1.LocalObjectReference{
  240. Name: "Spec.Volumes[*].VolumeSource.Projected.Sources[*].Secret"}}}}}}}, {
  241. VolumeSource: v1.VolumeSource{
  242. RBD: &v1.RBDVolumeSource{
  243. SecretRef: &v1.LocalObjectReference{
  244. Name: "Spec.Volumes[*].VolumeSource.RBD.SecretRef"}}}}, {
  245. VolumeSource: v1.VolumeSource{
  246. Secret: &v1.SecretVolumeSource{
  247. SecretName: "Spec.Volumes[*].VolumeSource.Secret.SecretName"}}}, {
  248. VolumeSource: v1.VolumeSource{
  249. Secret: &v1.SecretVolumeSource{
  250. SecretName: "Spec.Volumes[*].VolumeSource.Secret"}}}, {
  251. VolumeSource: v1.VolumeSource{
  252. ScaleIO: &v1.ScaleIOVolumeSource{
  253. SecretRef: &v1.LocalObjectReference{
  254. Name: "Spec.Volumes[*].VolumeSource.ScaleIO.SecretRef"}}}}, {
  255. VolumeSource: v1.VolumeSource{
  256. ISCSI: &v1.ISCSIVolumeSource{
  257. SecretRef: &v1.LocalObjectReference{
  258. Name: "Spec.Volumes[*].VolumeSource.ISCSI.SecretRef"}}}}, {
  259. VolumeSource: v1.VolumeSource{
  260. StorageOS: &v1.StorageOSVolumeSource{
  261. SecretRef: &v1.LocalObjectReference{
  262. Name: "Spec.Volumes[*].VolumeSource.StorageOS.SecretRef"}}}}, {
  263. VolumeSource: v1.VolumeSource{
  264. CSI: &v1.CSIVolumeSource{
  265. NodePublishSecretRef: &v1.LocalObjectReference{
  266. Name: "Spec.Volumes[*].VolumeSource.CSI.NodePublishSecretRef"}}}}},
  267. },
  268. }
  269. extractedNames := sets.NewString()
  270. VisitPodSecretNames(pod, func(name string) bool {
  271. extractedNames.Insert(name)
  272. return true
  273. })
  274. // excludedSecretPaths holds struct paths to fields with "secret" in the name that are not actually references to secret API objects
  275. excludedSecretPaths := sets.NewString(
  276. "Spec.Volumes[*].VolumeSource.CephFS.SecretFile",
  277. )
  278. // expectedSecretPaths holds struct paths to fields with "secret" in the name that are references to secret API objects.
  279. // every path here should be represented as an example in the Pod stub above, with the secret name set to the path.
  280. expectedSecretPaths := sets.NewString(
  281. "Spec.Containers[*].EnvFrom[*].SecretRef",
  282. "Spec.Containers[*].Env[*].ValueFrom.SecretKeyRef",
  283. "Spec.ImagePullSecrets",
  284. "Spec.InitContainers[*].EnvFrom[*].SecretRef",
  285. "Spec.InitContainers[*].Env[*].ValueFrom.SecretKeyRef",
  286. "Spec.Volumes[*].VolumeSource.AzureFile.SecretName",
  287. "Spec.Volumes[*].VolumeSource.CephFS.SecretRef",
  288. "Spec.Volumes[*].VolumeSource.Cinder.SecretRef",
  289. "Spec.Volumes[*].VolumeSource.FlexVolume.SecretRef",
  290. "Spec.Volumes[*].VolumeSource.Projected.Sources[*].Secret",
  291. "Spec.Volumes[*].VolumeSource.RBD.SecretRef",
  292. "Spec.Volumes[*].VolumeSource.Secret",
  293. "Spec.Volumes[*].VolumeSource.Secret.SecretName",
  294. "Spec.Volumes[*].VolumeSource.ScaleIO.SecretRef",
  295. "Spec.Volumes[*].VolumeSource.ISCSI.SecretRef",
  296. "Spec.Volumes[*].VolumeSource.StorageOS.SecretRef",
  297. "Spec.Volumes[*].VolumeSource.CSI.NodePublishSecretRef",
  298. )
  299. secretPaths := collectResourcePaths(t, "secret", nil, "", reflect.TypeOf(&v1.Pod{}))
  300. secretPaths = secretPaths.Difference(excludedSecretPaths)
  301. if missingPaths := expectedSecretPaths.Difference(secretPaths); len(missingPaths) > 0 {
  302. t.Logf("Missing expected secret paths:\n%s", strings.Join(missingPaths.List(), "\n"))
  303. t.Error("Missing expected secret paths. Verify VisitPodSecretNames() is correctly finding the missing paths, then correct expectedSecretPaths")
  304. }
  305. if extraPaths := secretPaths.Difference(expectedSecretPaths); len(extraPaths) > 0 {
  306. t.Logf("Extra secret paths:\n%s", strings.Join(extraPaths.List(), "\n"))
  307. t.Error("Extra fields with 'secret' in the name found. Verify VisitPodSecretNames() is including these fields if appropriate, then correct expectedSecretPaths")
  308. }
  309. if missingNames := expectedSecretPaths.Difference(extractedNames); len(missingNames) > 0 {
  310. t.Logf("Missing expected secret names:\n%s", strings.Join(missingNames.List(), "\n"))
  311. t.Error("Missing expected secret names. Verify the pod stub above includes these references, then verify VisitPodSecretNames() is correctly finding the missing names")
  312. }
  313. if extraNames := extractedNames.Difference(expectedSecretPaths); len(extraNames) > 0 {
  314. t.Logf("Extra secret names:\n%s", strings.Join(extraNames.List(), "\n"))
  315. t.Error("Extra secret names extracted. Verify VisitPodSecretNames() is correctly extracting secret names")
  316. }
  317. }
  318. // collectResourcePaths traverses the object, computing all the struct paths that lead to fields with resourcename in the name.
  319. func collectResourcePaths(t *testing.T, resourcename string, path *field.Path, name string, tp reflect.Type) sets.String {
  320. resourcename = strings.ToLower(resourcename)
  321. resourcePaths := sets.NewString()
  322. if tp.Kind() == reflect.Ptr {
  323. resourcePaths.Insert(collectResourcePaths(t, resourcename, path, name, tp.Elem()).List()...)
  324. return resourcePaths
  325. }
  326. if strings.Contains(strings.ToLower(name), resourcename) {
  327. resourcePaths.Insert(path.String())
  328. }
  329. switch tp.Kind() {
  330. case reflect.Ptr:
  331. resourcePaths.Insert(collectResourcePaths(t, resourcename, path, name, tp.Elem()).List()...)
  332. case reflect.Struct:
  333. // ObjectMeta is generic and therefore should never have a field with a specific resource's name;
  334. // it contains cycles so it's easiest to just skip it.
  335. if name == "ObjectMeta" {
  336. break
  337. }
  338. for i := 0; i < tp.NumField(); i++ {
  339. field := tp.Field(i)
  340. resourcePaths.Insert(collectResourcePaths(t, resourcename, path.Child(field.Name), field.Name, field.Type).List()...)
  341. }
  342. case reflect.Interface:
  343. t.Errorf("cannot find %s fields in interface{} field %s", resourcename, path.String())
  344. case reflect.Map:
  345. resourcePaths.Insert(collectResourcePaths(t, resourcename, path.Key("*"), "", tp.Elem()).List()...)
  346. case reflect.Slice:
  347. resourcePaths.Insert(collectResourcePaths(t, resourcename, path.Key("*"), "", tp.Elem()).List()...)
  348. default:
  349. // all primitive types
  350. }
  351. return resourcePaths
  352. }
  353. func TestPodConfigmaps(t *testing.T) {
  354. // Stub containing all possible ConfigMap references in a pod.
  355. // The names of the referenced ConfigMaps match struct paths detected by reflection.
  356. pod := &v1.Pod{
  357. Spec: v1.PodSpec{
  358. Containers: []v1.Container{{
  359. EnvFrom: []v1.EnvFromSource{{
  360. ConfigMapRef: &v1.ConfigMapEnvSource{
  361. LocalObjectReference: v1.LocalObjectReference{
  362. Name: "Spec.Containers[*].EnvFrom[*].ConfigMapRef"}}}},
  363. Env: []v1.EnvVar{{
  364. ValueFrom: &v1.EnvVarSource{
  365. ConfigMapKeyRef: &v1.ConfigMapKeySelector{
  366. LocalObjectReference: v1.LocalObjectReference{
  367. Name: "Spec.Containers[*].Env[*].ValueFrom.ConfigMapKeyRef"}}}}}}},
  368. InitContainers: []v1.Container{{
  369. EnvFrom: []v1.EnvFromSource{{
  370. ConfigMapRef: &v1.ConfigMapEnvSource{
  371. LocalObjectReference: v1.LocalObjectReference{
  372. Name: "Spec.InitContainers[*].EnvFrom[*].ConfigMapRef"}}}},
  373. Env: []v1.EnvVar{{
  374. ValueFrom: &v1.EnvVarSource{
  375. ConfigMapKeyRef: &v1.ConfigMapKeySelector{
  376. LocalObjectReference: v1.LocalObjectReference{
  377. Name: "Spec.InitContainers[*].Env[*].ValueFrom.ConfigMapKeyRef"}}}}}}},
  378. Volumes: []v1.Volume{{
  379. VolumeSource: v1.VolumeSource{
  380. Projected: &v1.ProjectedVolumeSource{
  381. Sources: []v1.VolumeProjection{{
  382. ConfigMap: &v1.ConfigMapProjection{
  383. LocalObjectReference: v1.LocalObjectReference{
  384. Name: "Spec.Volumes[*].VolumeSource.Projected.Sources[*].ConfigMap"}}}}}}}, {
  385. VolumeSource: v1.VolumeSource{
  386. ConfigMap: &v1.ConfigMapVolumeSource{
  387. LocalObjectReference: v1.LocalObjectReference{
  388. Name: "Spec.Volumes[*].VolumeSource.ConfigMap"}}}}},
  389. },
  390. }
  391. extractedNames := sets.NewString()
  392. VisitPodConfigmapNames(pod, func(name string) bool {
  393. extractedNames.Insert(name)
  394. return true
  395. })
  396. // expectedPaths holds struct paths to fields with "ConfigMap" in the name that are references to ConfigMap API objects.
  397. // every path here should be represented as an example in the Pod stub above, with the ConfigMap name set to the path.
  398. expectedPaths := sets.NewString(
  399. "Spec.Containers[*].EnvFrom[*].ConfigMapRef",
  400. "Spec.Containers[*].Env[*].ValueFrom.ConfigMapKeyRef",
  401. "Spec.InitContainers[*].EnvFrom[*].ConfigMapRef",
  402. "Spec.InitContainers[*].Env[*].ValueFrom.ConfigMapKeyRef",
  403. "Spec.Volumes[*].VolumeSource.Projected.Sources[*].ConfigMap",
  404. "Spec.Volumes[*].VolumeSource.ConfigMap",
  405. )
  406. collectPaths := collectResourcePaths(t, "ConfigMap", nil, "", reflect.TypeOf(&v1.Pod{}))
  407. if missingPaths := expectedPaths.Difference(collectPaths); len(missingPaths) > 0 {
  408. t.Logf("Missing expected paths:\n%s", strings.Join(missingPaths.List(), "\n"))
  409. t.Error("Missing expected paths. Verify VisitPodConfigmapNames() is correctly finding the missing paths, then correct expectedPaths")
  410. }
  411. if extraPaths := collectPaths.Difference(expectedPaths); len(extraPaths) > 0 {
  412. t.Logf("Extra paths:\n%s", strings.Join(extraPaths.List(), "\n"))
  413. t.Error("Extra fields with resource in the name found. Verify VisitPodConfigmapNames() is including these fields if appropriate, then correct expectedPaths")
  414. }
  415. if missingNames := expectedPaths.Difference(extractedNames); len(missingNames) > 0 {
  416. t.Logf("Missing expected names:\n%s", strings.Join(missingNames.List(), "\n"))
  417. t.Error("Missing expected names. Verify the pod stub above includes these references, then verify VisitPodConfigmapNames() is correctly finding the missing names")
  418. }
  419. if extraNames := extractedNames.Difference(expectedPaths); len(extraNames) > 0 {
  420. t.Logf("Extra names:\n%s", strings.Join(extraNames.List(), "\n"))
  421. t.Error("Extra names extracted. Verify VisitPodConfigmapNames() is correctly extracting resource names")
  422. }
  423. }
  424. func newPod(now metav1.Time, ready bool, beforeSec int) *v1.Pod {
  425. conditionStatus := v1.ConditionFalse
  426. if ready {
  427. conditionStatus = v1.ConditionTrue
  428. }
  429. return &v1.Pod{
  430. Status: v1.PodStatus{
  431. Conditions: []v1.PodCondition{
  432. {
  433. Type: v1.PodReady,
  434. LastTransitionTime: metav1.NewTime(now.Time.Add(-1 * time.Duration(beforeSec) * time.Second)),
  435. Status: conditionStatus,
  436. },
  437. },
  438. },
  439. }
  440. }
  441. func TestIsPodAvailable(t *testing.T) {
  442. now := metav1.Now()
  443. tests := []struct {
  444. pod *v1.Pod
  445. minReadySeconds int32
  446. expected bool
  447. }{
  448. {
  449. pod: newPod(now, false, 0),
  450. minReadySeconds: 0,
  451. expected: false,
  452. },
  453. {
  454. pod: newPod(now, true, 0),
  455. minReadySeconds: 1,
  456. expected: false,
  457. },
  458. {
  459. pod: newPod(now, true, 0),
  460. minReadySeconds: 0,
  461. expected: true,
  462. },
  463. {
  464. pod: newPod(now, true, 51),
  465. minReadySeconds: 50,
  466. expected: true,
  467. },
  468. }
  469. for i, test := range tests {
  470. isAvailable := IsPodAvailable(test.pod, test.minReadySeconds, now)
  471. if isAvailable != test.expected {
  472. t.Errorf("[tc #%d] expected available pod: %t, got: %t", i, test.expected, isAvailable)
  473. }
  474. }
  475. }
  476. func TestGetContainerStatus(t *testing.T) {
  477. type ExpectedStruct struct {
  478. status v1.ContainerStatus
  479. exists bool
  480. }
  481. tests := []struct {
  482. status []v1.ContainerStatus
  483. name string
  484. expected ExpectedStruct
  485. desc string
  486. }{
  487. {
  488. status: []v1.ContainerStatus{{Name: "test1", Ready: false, Image: "image1"}, {Name: "test2", Ready: true, Image: "image1"}},
  489. name: "test1",
  490. expected: ExpectedStruct{status: v1.ContainerStatus{Name: "test1", Ready: false, Image: "image1"}, exists: true},
  491. desc: "retrieve ContainerStatus with Name=\"test1\"",
  492. },
  493. {
  494. status: []v1.ContainerStatus{{Name: "test2", Ready: false, Image: "image2"}},
  495. name: "test1",
  496. expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false},
  497. desc: "no matching ContainerStatus with Name=\"test1\"",
  498. },
  499. {
  500. status: []v1.ContainerStatus{{Name: "test3", Ready: false, Image: "image3"}},
  501. name: "",
  502. expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false},
  503. desc: "retrieve an empty ContainerStatus with container name empty",
  504. },
  505. {
  506. status: nil,
  507. name: "",
  508. expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false},
  509. desc: "retrieve an empty ContainerStatus with status nil",
  510. },
  511. }
  512. for _, test := range tests {
  513. resultStatus, exists := GetContainerStatus(test.status, test.name)
  514. assert.Equal(t, test.expected.status, resultStatus, "GetContainerStatus: "+test.desc)
  515. assert.Equal(t, test.expected.exists, exists, "GetContainerStatus: "+test.desc)
  516. resultStatus = GetExistingContainerStatus(test.status, test.name)
  517. assert.Equal(t, test.expected.status, resultStatus, "GetExistingContainerStatus: "+test.desc)
  518. }
  519. }
  520. func TestUpdatePodCondition(t *testing.T) {
  521. time := metav1.Now()
  522. podStatus := v1.PodStatus{
  523. Conditions: []v1.PodCondition{
  524. {
  525. Type: v1.PodReady,
  526. Status: v1.ConditionTrue,
  527. Reason: "successfully",
  528. Message: "sync pod successfully",
  529. LastProbeTime: time,
  530. LastTransitionTime: metav1.NewTime(time.Add(1000)),
  531. },
  532. },
  533. }
  534. tests := []struct {
  535. status *v1.PodStatus
  536. conditions v1.PodCondition
  537. expected bool
  538. desc string
  539. }{
  540. {
  541. status: &podStatus,
  542. conditions: v1.PodCondition{
  543. Type: v1.PodReady,
  544. Status: v1.ConditionTrue,
  545. Reason: "successfully",
  546. Message: "sync pod successfully",
  547. LastProbeTime: time,
  548. LastTransitionTime: metav1.NewTime(time.Add(1000))},
  549. expected: false,
  550. desc: "all equal, no update",
  551. },
  552. {
  553. status: &podStatus,
  554. conditions: v1.PodCondition{
  555. Type: v1.PodScheduled,
  556. Status: v1.ConditionTrue,
  557. Reason: "successfully",
  558. Message: "sync pod successfully",
  559. LastProbeTime: time,
  560. LastTransitionTime: metav1.NewTime(time.Add(1000))},
  561. expected: true,
  562. desc: "not equal Type, should get updated",
  563. },
  564. {
  565. status: &podStatus,
  566. conditions: v1.PodCondition{
  567. Type: v1.PodReady,
  568. Status: v1.ConditionFalse,
  569. Reason: "successfully",
  570. Message: "sync pod successfully",
  571. LastProbeTime: time,
  572. LastTransitionTime: metav1.NewTime(time.Add(1000))},
  573. expected: true,
  574. desc: "not equal Status, should get updated",
  575. },
  576. }
  577. for _, test := range tests {
  578. resultStatus := UpdatePodCondition(test.status, &test.conditions)
  579. assert.Equal(t, test.expected, resultStatus, test.desc)
  580. }
  581. }