describe_test.go 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179
  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 versioned
  14. import (
  15. "bytes"
  16. "fmt"
  17. "reflect"
  18. "regexp"
  19. "strings"
  20. "testing"
  21. "time"
  22. appsv1 "k8s.io/api/apps/v1"
  23. autoscalingv1 "k8s.io/api/autoscaling/v1"
  24. autoscalingv2beta2 "k8s.io/api/autoscaling/v2beta2"
  25. corev1 "k8s.io/api/core/v1"
  26. networkingv1 "k8s.io/api/networking/v1"
  27. policyv1beta1 "k8s.io/api/policy/v1beta1"
  28. storagev1 "k8s.io/api/storage/v1"
  29. apiequality "k8s.io/apimachinery/pkg/api/equality"
  30. "k8s.io/apimachinery/pkg/api/resource"
  31. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  32. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  33. "k8s.io/apimachinery/pkg/util/intstr"
  34. "k8s.io/client-go/kubernetes"
  35. "k8s.io/client-go/kubernetes/fake"
  36. "k8s.io/kubernetes/pkg/kubectl/describe"
  37. utilpointer "k8s.io/utils/pointer"
  38. )
  39. type describeClient struct {
  40. T *testing.T
  41. Namespace string
  42. Err error
  43. kubernetes.Interface
  44. }
  45. func TestDescribePod(t *testing.T) {
  46. deletionTimestamp := metav1.Time{Time: time.Now().UTC().AddDate(-10, 0, 0)}
  47. gracePeriod := int64(1234)
  48. condition1 := corev1.PodConditionType("condition1")
  49. condition2 := corev1.PodConditionType("condition2")
  50. fake := fake.NewSimpleClientset(&corev1.Pod{
  51. ObjectMeta: metav1.ObjectMeta{
  52. Name: "bar",
  53. Namespace: "foo",
  54. DeletionTimestamp: &deletionTimestamp,
  55. DeletionGracePeriodSeconds: &gracePeriod,
  56. },
  57. Spec: corev1.PodSpec{
  58. ReadinessGates: []corev1.PodReadinessGate{
  59. {
  60. ConditionType: condition1,
  61. },
  62. {
  63. ConditionType: condition2,
  64. },
  65. },
  66. },
  67. Status: corev1.PodStatus{
  68. Conditions: []corev1.PodCondition{
  69. {
  70. Type: condition1,
  71. Status: corev1.ConditionTrue,
  72. },
  73. },
  74. },
  75. })
  76. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  77. d := PodDescriber{c}
  78. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  79. if err != nil {
  80. t.Errorf("unexpected error: %v", err)
  81. }
  82. if !strings.Contains(out, "bar") || !strings.Contains(out, "Status:") {
  83. t.Errorf("unexpected out: %s", out)
  84. }
  85. if !strings.Contains(out, "Terminating (lasts 10y)") || !strings.Contains(out, "1234s") {
  86. t.Errorf("unexpected out: %s", out)
  87. }
  88. }
  89. func TestDescribePodNode(t *testing.T) {
  90. fake := fake.NewSimpleClientset(&corev1.Pod{
  91. ObjectMeta: metav1.ObjectMeta{
  92. Name: "bar",
  93. Namespace: "foo",
  94. },
  95. Spec: corev1.PodSpec{
  96. NodeName: "all-in-one",
  97. },
  98. Status: corev1.PodStatus{
  99. HostIP: "127.0.0.1",
  100. NominatedNodeName: "nodeA",
  101. },
  102. })
  103. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  104. d := PodDescriber{c}
  105. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  106. if err != nil {
  107. t.Errorf("unexpected error: %v", err)
  108. }
  109. if !strings.Contains(out, "all-in-one/127.0.0.1") {
  110. t.Errorf("unexpected out: %s", out)
  111. }
  112. if !strings.Contains(out, "nodeA") {
  113. t.Errorf("unexpected out: %s", out)
  114. }
  115. }
  116. func TestDescribePodTolerations(t *testing.T) {
  117. fake := fake.NewSimpleClientset(&corev1.Pod{
  118. ObjectMeta: metav1.ObjectMeta{
  119. Name: "bar",
  120. Namespace: "foo",
  121. },
  122. Spec: corev1.PodSpec{
  123. Tolerations: []corev1.Toleration{
  124. {Key: "key0", Operator: corev1.TolerationOpExists},
  125. {Key: "key1", Value: "value1"},
  126. {Key: "key2", Operator: corev1.TolerationOpEqual, Value: "value2", Effect: corev1.TaintEffectNoSchedule},
  127. {Key: "key3", Value: "value3", Effect: corev1.TaintEffectNoExecute, TolerationSeconds: &[]int64{300}[0]},
  128. {Key: "key4", Effect: corev1.TaintEffectNoExecute, TolerationSeconds: &[]int64{60}[0]},
  129. },
  130. },
  131. })
  132. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  133. d := PodDescriber{c}
  134. out, err := d.Describe("foo", "bar", describe.DescriberSettings{})
  135. if err != nil {
  136. t.Errorf("unexpected error: %v", err)
  137. }
  138. if !strings.Contains(out, "key0\n") ||
  139. !strings.Contains(out, "key1=value1\n") ||
  140. !strings.Contains(out, "key2=value2:NoSchedule\n") ||
  141. !strings.Contains(out, "key3=value3:NoExecute for 300s\n") ||
  142. !strings.Contains(out, "key4:NoExecute for 60s\n") ||
  143. !strings.Contains(out, "Tolerations:") {
  144. t.Errorf("unexpected out:\n%s", out)
  145. }
  146. }
  147. func TestDescribeSecret(t *testing.T) {
  148. fake := fake.NewSimpleClientset(&corev1.Secret{
  149. ObjectMeta: metav1.ObjectMeta{
  150. Name: "bar",
  151. Namespace: "foo",
  152. },
  153. Data: map[string][]byte{
  154. "username": []byte("YWRtaW4="),
  155. "password": []byte("MWYyZDFlMmU2N2Rm"),
  156. },
  157. })
  158. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  159. d := SecretDescriber{c}
  160. out, err := d.Describe("foo", "bar", describe.DescriberSettings{})
  161. if err != nil {
  162. t.Errorf("unexpected error: %v", err)
  163. }
  164. if !strings.Contains(out, "bar") || !strings.Contains(out, "foo") || !strings.Contains(out, "username") || !strings.Contains(out, "8 bytes") || !strings.Contains(out, "password") || !strings.Contains(out, "16 bytes") {
  165. t.Errorf("unexpected out: %s", out)
  166. }
  167. if strings.Contains(out, "YWRtaW4=") || strings.Contains(out, "MWYyZDFlMmU2N2Rm") {
  168. t.Errorf("sensitive data should not be shown, unexpected out: %s", out)
  169. }
  170. }
  171. func TestDescribeNamespace(t *testing.T) {
  172. fake := fake.NewSimpleClientset(&corev1.Namespace{
  173. ObjectMeta: metav1.ObjectMeta{
  174. Name: "myns",
  175. },
  176. })
  177. c := &describeClient{T: t, Namespace: "", Interface: fake}
  178. d := NamespaceDescriber{c}
  179. out, err := d.Describe("", "myns", describe.DescriberSettings{ShowEvents: true})
  180. if err != nil {
  181. t.Errorf("unexpected error: %v", err)
  182. }
  183. if !strings.Contains(out, "myns") {
  184. t.Errorf("unexpected out: %s", out)
  185. }
  186. }
  187. func TestDescribePodPriority(t *testing.T) {
  188. priority := int32(1000)
  189. fake := fake.NewSimpleClientset(&corev1.Pod{
  190. ObjectMeta: metav1.ObjectMeta{
  191. Name: "bar",
  192. },
  193. Spec: corev1.PodSpec{
  194. PriorityClassName: "high-priority",
  195. Priority: &priority,
  196. },
  197. })
  198. c := &describeClient{T: t, Namespace: "", Interface: fake}
  199. d := PodDescriber{c}
  200. out, err := d.Describe("", "bar", describe.DescriberSettings{ShowEvents: true})
  201. if err != nil {
  202. t.Errorf("unexpected error: %v", err)
  203. }
  204. if !strings.Contains(out, "high-priority") || !strings.Contains(out, "1000") {
  205. t.Errorf("unexpected out: %s", out)
  206. }
  207. }
  208. func TestDescribeConfigMap(t *testing.T) {
  209. fake := fake.NewSimpleClientset(&corev1.ConfigMap{
  210. ObjectMeta: metav1.ObjectMeta{
  211. Name: "mycm",
  212. Namespace: "foo",
  213. },
  214. Data: map[string]string{
  215. "key1": "value1",
  216. "key2": "value2",
  217. },
  218. })
  219. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  220. d := ConfigMapDescriber{c}
  221. out, err := d.Describe("foo", "mycm", describe.DescriberSettings{ShowEvents: true})
  222. if err != nil {
  223. t.Errorf("unexpected error: %v", err)
  224. }
  225. if !strings.Contains(out, "foo") || !strings.Contains(out, "mycm") || !strings.Contains(out, "key1") || !strings.Contains(out, "value1") || !strings.Contains(out, "key2") || !strings.Contains(out, "value2") {
  226. t.Errorf("unexpected out: %s", out)
  227. }
  228. }
  229. func TestDescribeLimitRange(t *testing.T) {
  230. fake := fake.NewSimpleClientset(&corev1.LimitRange{
  231. ObjectMeta: metav1.ObjectMeta{
  232. Name: "mylr",
  233. Namespace: "foo",
  234. },
  235. Spec: corev1.LimitRangeSpec{
  236. Limits: []corev1.LimitRangeItem{
  237. {
  238. Type: corev1.LimitTypePod,
  239. Max: getResourceList("100m", "10000Mi"),
  240. Min: getResourceList("5m", "100Mi"),
  241. MaxLimitRequestRatio: getResourceList("10", ""),
  242. },
  243. {
  244. Type: corev1.LimitTypeContainer,
  245. Max: getResourceList("100m", "10000Mi"),
  246. Min: getResourceList("5m", "100Mi"),
  247. Default: getResourceList("50m", "500Mi"),
  248. DefaultRequest: getResourceList("10m", "200Mi"),
  249. MaxLimitRequestRatio: getResourceList("10", ""),
  250. },
  251. {
  252. Type: corev1.LimitTypePersistentVolumeClaim,
  253. Max: getStorageResourceList("10Gi"),
  254. Min: getStorageResourceList("5Gi"),
  255. },
  256. },
  257. },
  258. })
  259. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  260. d := LimitRangeDescriber{c}
  261. out, err := d.Describe("foo", "mylr", describe.DescriberSettings{ShowEvents: true})
  262. if err != nil {
  263. t.Errorf("unexpected error: %v", err)
  264. }
  265. checks := []string{"foo", "mylr", "Pod", "cpu", "5m", "100m", "memory", "100Mi", "10000Mi", "10", "Container", "cpu", "10m", "50m", "200Mi", "500Mi", "PersistentVolumeClaim", "storage", "5Gi", "10Gi"}
  266. for _, check := range checks {
  267. if !strings.Contains(out, check) {
  268. t.Errorf("unexpected out: %s", out)
  269. }
  270. }
  271. }
  272. func getStorageResourceList(storage string) corev1.ResourceList {
  273. res := corev1.ResourceList{}
  274. if storage != "" {
  275. res[corev1.ResourceStorage] = resource.MustParse(storage)
  276. }
  277. return res
  278. }
  279. func getResourceList(cpu, memory string) corev1.ResourceList {
  280. res := corev1.ResourceList{}
  281. if cpu != "" {
  282. res[corev1.ResourceCPU] = resource.MustParse(cpu)
  283. }
  284. if memory != "" {
  285. res[corev1.ResourceMemory] = resource.MustParse(memory)
  286. }
  287. return res
  288. }
  289. func TestDescribeService(t *testing.T) {
  290. testCases := []struct {
  291. name string
  292. service *corev1.Service
  293. expect []string
  294. }{
  295. {
  296. name: "test1",
  297. service: &corev1.Service{
  298. ObjectMeta: metav1.ObjectMeta{
  299. Name: "bar",
  300. Namespace: "foo",
  301. },
  302. Spec: corev1.ServiceSpec{
  303. Type: corev1.ServiceTypeLoadBalancer,
  304. Ports: []corev1.ServicePort{{
  305. Name: "port-tcp",
  306. Port: 8080,
  307. Protocol: corev1.ProtocolTCP,
  308. TargetPort: intstr.FromInt(9527),
  309. NodePort: 31111,
  310. }},
  311. Selector: map[string]string{"blah": "heh"},
  312. ClusterIP: "1.2.3.4",
  313. LoadBalancerIP: "5.6.7.8",
  314. SessionAffinity: "None",
  315. ExternalTrafficPolicy: "Local",
  316. HealthCheckNodePort: 32222,
  317. },
  318. },
  319. expect: []string{
  320. "Name", "bar",
  321. "Namespace", "foo",
  322. "Selector", "blah=heh",
  323. "Type", "LoadBalancer",
  324. "IP", "1.2.3.4",
  325. "Port", "port-tcp", "8080/TCP",
  326. "TargetPort", "9527/TCP",
  327. "NodePort", "port-tcp", "31111/TCP",
  328. "Session Affinity", "None",
  329. "External Traffic Policy", "Local",
  330. "HealthCheck NodePort", "32222",
  331. },
  332. },
  333. {
  334. name: "test2",
  335. service: &corev1.Service{
  336. ObjectMeta: metav1.ObjectMeta{
  337. Name: "bar",
  338. Namespace: "foo",
  339. },
  340. Spec: corev1.ServiceSpec{
  341. Type: corev1.ServiceTypeLoadBalancer,
  342. Ports: []corev1.ServicePort{{
  343. Name: "port-tcp",
  344. Port: 8080,
  345. Protocol: corev1.ProtocolTCP,
  346. TargetPort: intstr.FromString("targetPort"),
  347. NodePort: 31111,
  348. }},
  349. Selector: map[string]string{"blah": "heh"},
  350. ClusterIP: "1.2.3.4",
  351. LoadBalancerIP: "5.6.7.8",
  352. SessionAffinity: "None",
  353. ExternalTrafficPolicy: "Local",
  354. HealthCheckNodePort: 32222,
  355. },
  356. },
  357. expect: []string{
  358. "Name", "bar",
  359. "Namespace", "foo",
  360. "Selector", "blah=heh",
  361. "Type", "LoadBalancer",
  362. "IP", "1.2.3.4",
  363. "Port", "port-tcp", "8080/TCP",
  364. "TargetPort", "targetPort/TCP",
  365. "NodePort", "port-tcp", "31111/TCP",
  366. "Session Affinity", "None",
  367. "External Traffic Policy", "Local",
  368. "HealthCheck NodePort", "32222",
  369. },
  370. },
  371. }
  372. for _, testCase := range testCases {
  373. t.Run(testCase.name, func(t *testing.T) {
  374. fake := fake.NewSimpleClientset(testCase.service)
  375. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  376. d := ServiceDescriber{c}
  377. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  378. if err != nil {
  379. t.Errorf("unexpected error: %v", err)
  380. }
  381. for _, expected := range testCase.expect {
  382. if !strings.Contains(out, expected) {
  383. t.Errorf("expected to find %q in output: %q", expected, out)
  384. }
  385. }
  386. })
  387. }
  388. }
  389. func TestPodDescribeResultsSorted(t *testing.T) {
  390. // Arrange
  391. fake := fake.NewSimpleClientset(
  392. &corev1.EventList{
  393. Items: []corev1.Event{
  394. {
  395. ObjectMeta: metav1.ObjectMeta{Name: "one"},
  396. Source: corev1.EventSource{Component: "kubelet"},
  397. Message: "Item 1",
  398. FirstTimestamp: metav1.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)),
  399. LastTimestamp: metav1.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)),
  400. Count: 1,
  401. Type: corev1.EventTypeNormal,
  402. },
  403. {
  404. ObjectMeta: metav1.ObjectMeta{Name: "two"},
  405. Source: corev1.EventSource{Component: "scheduler"},
  406. Message: "Item 2",
  407. FirstTimestamp: metav1.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)),
  408. LastTimestamp: metav1.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)),
  409. Count: 1,
  410. Type: corev1.EventTypeNormal,
  411. },
  412. {
  413. ObjectMeta: metav1.ObjectMeta{Name: "three"},
  414. Source: corev1.EventSource{Component: "kubelet"},
  415. Message: "Item 3",
  416. FirstTimestamp: metav1.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)),
  417. LastTimestamp: metav1.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)),
  418. Count: 1,
  419. Type: corev1.EventTypeNormal,
  420. },
  421. },
  422. },
  423. &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}},
  424. )
  425. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  426. d := PodDescriber{c}
  427. // Act
  428. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  429. // Assert
  430. if err != nil {
  431. t.Errorf("unexpected error: %v", err)
  432. }
  433. VerifyDatesInOrder(out, "\n" /* rowDelimiter */, "\t" /* columnDelimiter */, t)
  434. }
  435. // VerifyDatesInOrder checks the start of each line for a RFC1123Z date
  436. // and posts error if all subsequent dates are not equal or increasing
  437. func VerifyDatesInOrder(
  438. resultToTest, rowDelimiter, columnDelimiter string, t *testing.T) {
  439. lines := strings.Split(resultToTest, rowDelimiter)
  440. var previousTime time.Time
  441. for _, str := range lines {
  442. columns := strings.Split(str, columnDelimiter)
  443. if len(columns) > 0 {
  444. currentTime, err := time.Parse(time.RFC1123Z, columns[0])
  445. if err == nil {
  446. if previousTime.After(currentTime) {
  447. t.Errorf(
  448. "Output is not sorted by time. %s should be listed after %s. Complete output: %s",
  449. previousTime.Format(time.RFC1123Z),
  450. currentTime.Format(time.RFC1123Z),
  451. resultToTest)
  452. }
  453. previousTime = currentTime
  454. }
  455. }
  456. }
  457. }
  458. func TestDescribeContainers(t *testing.T) {
  459. trueVal := true
  460. testCases := []struct {
  461. container corev1.Container
  462. status corev1.ContainerStatus
  463. expectedElements []string
  464. }{
  465. // Running state.
  466. {
  467. container: corev1.Container{Name: "test", Image: "image"},
  468. status: corev1.ContainerStatus{
  469. Name: "test",
  470. State: corev1.ContainerState{
  471. Running: &corev1.ContainerStateRunning{
  472. StartedAt: metav1.NewTime(time.Now()),
  473. },
  474. },
  475. Ready: true,
  476. RestartCount: 7,
  477. },
  478. expectedElements: []string{"test", "State", "Running", "Ready", "True", "Restart Count", "7", "Image", "image", "Started"},
  479. },
  480. // Waiting state.
  481. {
  482. container: corev1.Container{Name: "test", Image: "image"},
  483. status: corev1.ContainerStatus{
  484. Name: "test",
  485. State: corev1.ContainerState{
  486. Waiting: &corev1.ContainerStateWaiting{
  487. Reason: "potato",
  488. },
  489. },
  490. Ready: true,
  491. RestartCount: 7,
  492. },
  493. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "Reason", "potato"},
  494. },
  495. // Terminated state.
  496. {
  497. container: corev1.Container{Name: "test", Image: "image"},
  498. status: corev1.ContainerStatus{
  499. Name: "test",
  500. State: corev1.ContainerState{
  501. Terminated: &corev1.ContainerStateTerminated{
  502. StartedAt: metav1.NewTime(time.Now()),
  503. FinishedAt: metav1.NewTime(time.Now()),
  504. Reason: "potato",
  505. ExitCode: 2,
  506. },
  507. },
  508. Ready: true,
  509. RestartCount: 7,
  510. },
  511. expectedElements: []string{"test", "State", "Terminated", "Ready", "True", "Restart Count", "7", "Image", "image", "Reason", "potato", "Started", "Finished", "Exit Code", "2"},
  512. },
  513. // Last Terminated
  514. {
  515. container: corev1.Container{Name: "test", Image: "image"},
  516. status: corev1.ContainerStatus{
  517. Name: "test",
  518. State: corev1.ContainerState{
  519. Running: &corev1.ContainerStateRunning{
  520. StartedAt: metav1.NewTime(time.Now()),
  521. },
  522. },
  523. LastTerminationState: corev1.ContainerState{
  524. Terminated: &corev1.ContainerStateTerminated{
  525. StartedAt: metav1.NewTime(time.Now().Add(time.Second * 3)),
  526. FinishedAt: metav1.NewTime(time.Now()),
  527. Reason: "crashing",
  528. ExitCode: 3,
  529. },
  530. },
  531. Ready: true,
  532. RestartCount: 7,
  533. },
  534. expectedElements: []string{"test", "State", "Terminated", "Ready", "True", "Restart Count", "7", "Image", "image", "Started", "Finished", "Exit Code", "2", "crashing", "3"},
  535. },
  536. // No state defaults to waiting.
  537. {
  538. container: corev1.Container{Name: "test", Image: "image"},
  539. status: corev1.ContainerStatus{
  540. Name: "test",
  541. Ready: true,
  542. RestartCount: 7,
  543. },
  544. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image"},
  545. },
  546. // Env
  547. {
  548. container: corev1.Container{Name: "test", Image: "image", Env: []corev1.EnvVar{{Name: "envname", Value: "xyz"}}, EnvFrom: []corev1.EnvFromSource{{ConfigMapRef: &corev1.ConfigMapEnvSource{LocalObjectReference: corev1.LocalObjectReference{Name: "a123"}}}}},
  549. status: corev1.ContainerStatus{
  550. Name: "test",
  551. Ready: true,
  552. RestartCount: 7,
  553. },
  554. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "envname", "xyz", "a123\tConfigMap\tOptional: false"},
  555. },
  556. {
  557. container: corev1.Container{Name: "test", Image: "image", Env: []corev1.EnvVar{{Name: "envname", Value: "xyz"}}, EnvFrom: []corev1.EnvFromSource{{Prefix: "p_", ConfigMapRef: &corev1.ConfigMapEnvSource{LocalObjectReference: corev1.LocalObjectReference{Name: "a123"}}}}},
  558. status: corev1.ContainerStatus{
  559. Name: "test",
  560. Ready: true,
  561. RestartCount: 7,
  562. },
  563. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "envname", "xyz", "a123\tConfigMap with prefix 'p_'\tOptional: false"},
  564. },
  565. {
  566. container: corev1.Container{Name: "test", Image: "image", Env: []corev1.EnvVar{{Name: "envname", Value: "xyz"}}, EnvFrom: []corev1.EnvFromSource{{ConfigMapRef: &corev1.ConfigMapEnvSource{Optional: &trueVal, LocalObjectReference: corev1.LocalObjectReference{Name: "a123"}}}}},
  567. status: corev1.ContainerStatus{
  568. Name: "test",
  569. Ready: true,
  570. RestartCount: 7,
  571. },
  572. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "envname", "xyz", "a123\tConfigMap\tOptional: true"},
  573. },
  574. {
  575. container: corev1.Container{Name: "test", Image: "image", Env: []corev1.EnvVar{{Name: "envname", Value: "xyz"}}, EnvFrom: []corev1.EnvFromSource{{SecretRef: &corev1.SecretEnvSource{LocalObjectReference: corev1.LocalObjectReference{Name: "a123"}, Optional: &trueVal}}}},
  576. status: corev1.ContainerStatus{
  577. Name: "test",
  578. Ready: true,
  579. RestartCount: 7,
  580. },
  581. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "envname", "xyz", "a123\tSecret\tOptional: true"},
  582. },
  583. {
  584. container: corev1.Container{Name: "test", Image: "image", Env: []corev1.EnvVar{{Name: "envname", Value: "xyz"}}, EnvFrom: []corev1.EnvFromSource{{Prefix: "p_", SecretRef: &corev1.SecretEnvSource{LocalObjectReference: corev1.LocalObjectReference{Name: "a123"}}}}},
  585. status: corev1.ContainerStatus{
  586. Name: "test",
  587. Ready: true,
  588. RestartCount: 7,
  589. },
  590. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "envname", "xyz", "a123\tSecret with prefix 'p_'\tOptional: false"},
  591. },
  592. // Command
  593. {
  594. container: corev1.Container{Name: "test", Image: "image", Command: []string{"sleep", "1000"}},
  595. status: corev1.ContainerStatus{
  596. Name: "test",
  597. Ready: true,
  598. RestartCount: 7,
  599. },
  600. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "sleep", "1000"},
  601. },
  602. // Command with newline
  603. {
  604. container: corev1.Container{Name: "test", Image: "image", Command: []string{"sleep", "1000\n2000"}},
  605. status: corev1.ContainerStatus{
  606. Name: "test",
  607. Ready: true,
  608. RestartCount: 7,
  609. },
  610. expectedElements: []string{"1000\n 2000"},
  611. },
  612. // Args
  613. {
  614. container: corev1.Container{Name: "test", Image: "image", Args: []string{"time", "1000"}},
  615. status: corev1.ContainerStatus{
  616. Name: "test",
  617. Ready: true,
  618. RestartCount: 7,
  619. },
  620. expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "time", "1000"},
  621. },
  622. // Args with newline
  623. {
  624. container: corev1.Container{Name: "test", Image: "image", Args: []string{"time", "1000\n2000"}},
  625. status: corev1.ContainerStatus{
  626. Name: "test",
  627. Ready: true,
  628. RestartCount: 7,
  629. },
  630. expectedElements: []string{"1000\n 2000"},
  631. },
  632. // Using limits.
  633. {
  634. container: corev1.Container{
  635. Name: "test",
  636. Image: "image",
  637. Resources: corev1.ResourceRequirements{
  638. Limits: corev1.ResourceList{
  639. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("1000"),
  640. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("4G"),
  641. corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("20G"),
  642. },
  643. },
  644. },
  645. status: corev1.ContainerStatus{
  646. Name: "test",
  647. Ready: true,
  648. RestartCount: 7,
  649. },
  650. expectedElements: []string{"cpu", "1k", "memory", "4G", "storage", "20G"},
  651. },
  652. // Using requests.
  653. {
  654. container: corev1.Container{
  655. Name: "test",
  656. Image: "image",
  657. Resources: corev1.ResourceRequirements{
  658. Requests: corev1.ResourceList{
  659. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("1000"),
  660. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("4G"),
  661. corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("20G"),
  662. },
  663. },
  664. },
  665. expectedElements: []string{"cpu", "1k", "memory", "4G", "storage", "20G"},
  666. },
  667. // volumeMounts read/write
  668. {
  669. container: corev1.Container{
  670. Name: "test",
  671. Image: "image",
  672. VolumeMounts: []corev1.VolumeMount{
  673. {
  674. Name: "mounted-volume",
  675. MountPath: "/opt/",
  676. },
  677. },
  678. },
  679. expectedElements: []string{"mounted-volume", "/opt/", "(rw)"},
  680. },
  681. // volumeMounts readonly
  682. {
  683. container: corev1.Container{
  684. Name: "test",
  685. Image: "image",
  686. VolumeMounts: []corev1.VolumeMount{
  687. {
  688. Name: "mounted-volume",
  689. MountPath: "/opt/",
  690. ReadOnly: true,
  691. },
  692. },
  693. },
  694. expectedElements: []string{"Mounts", "mounted-volume", "/opt/", "(ro)"},
  695. },
  696. // volumeMounts subPath
  697. {
  698. container: corev1.Container{
  699. Name: "test",
  700. Image: "image",
  701. VolumeMounts: []corev1.VolumeMount{
  702. {
  703. Name: "mounted-volume",
  704. MountPath: "/opt/",
  705. SubPath: "foo",
  706. },
  707. },
  708. },
  709. expectedElements: []string{"Mounts", "mounted-volume", "/opt/", "(rw,path=\"foo\")"},
  710. },
  711. // volumeDevices
  712. {
  713. container: corev1.Container{
  714. Name: "test",
  715. Image: "image",
  716. VolumeDevices: []corev1.VolumeDevice{
  717. {
  718. Name: "volume-device",
  719. DevicePath: "/dev/xvda",
  720. },
  721. },
  722. },
  723. expectedElements: []string{"Devices", "volume-device", "/dev/xvda"},
  724. },
  725. }
  726. for i, testCase := range testCases {
  727. t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
  728. out := new(bytes.Buffer)
  729. pod := corev1.Pod{
  730. Spec: corev1.PodSpec{
  731. Containers: []corev1.Container{testCase.container},
  732. },
  733. Status: corev1.PodStatus{
  734. ContainerStatuses: []corev1.ContainerStatus{testCase.status},
  735. },
  736. }
  737. writer := NewPrefixWriter(out)
  738. describeContainers("Containers", pod.Spec.Containers, pod.Status.ContainerStatuses, EnvValueRetriever(&pod), writer, "")
  739. output := out.String()
  740. for _, expected := range testCase.expectedElements {
  741. if !strings.Contains(output, expected) {
  742. t.Errorf("Test case %d: expected to find %q in output: %q", i, expected, output)
  743. }
  744. }
  745. })
  746. }
  747. }
  748. func TestDescribers(t *testing.T) {
  749. first := &corev1.Event{}
  750. second := &corev1.Pod{}
  751. var third *corev1.Pod
  752. testErr := fmt.Errorf("test")
  753. d := Describers{}
  754. d.Add(
  755. func(e *corev1.Event, p *corev1.Pod) (string, error) {
  756. if e != first {
  757. t.Errorf("first argument not equal: %#v", e)
  758. }
  759. if p != second {
  760. t.Errorf("second argument not equal: %#v", p)
  761. }
  762. return "test", testErr
  763. },
  764. )
  765. if out, err := d.DescribeObject(first, second); out != "test" || err != testErr {
  766. t.Errorf("unexpected result: %s %v", out, err)
  767. }
  768. if out, err := d.DescribeObject(first, second, third); out != "" || err == nil {
  769. t.Errorf("unexpected result: %s %v", out, err)
  770. } else {
  771. if noDescriber, ok := err.(describe.ErrNoDescriber); ok {
  772. if !reflect.DeepEqual(noDescriber.Types, []string{"*v1.Event", "*v1.Pod", "*v1.Pod"}) {
  773. t.Errorf("unexpected describer: %v", err)
  774. }
  775. } else {
  776. t.Errorf("unexpected error type: %v", err)
  777. }
  778. }
  779. d.Add(
  780. func(e *corev1.Event) (string, error) {
  781. if e != first {
  782. t.Errorf("first argument not equal: %#v", e)
  783. }
  784. return "simpler", testErr
  785. },
  786. )
  787. if out, err := d.DescribeObject(first); out != "simpler" || err != testErr {
  788. t.Errorf("unexpected result: %s %v", out, err)
  789. }
  790. }
  791. func TestDefaultDescribers(t *testing.T) {
  792. out, err := DefaultObjectDescriber.DescribeObject(&corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}})
  793. if err != nil {
  794. t.Fatalf("unexpected error: %v", err)
  795. }
  796. if !strings.Contains(out, "foo") {
  797. t.Errorf("unexpected output: %s", out)
  798. }
  799. out, err = DefaultObjectDescriber.DescribeObject(&corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "foo"}})
  800. if err != nil {
  801. t.Fatalf("unexpected error: %v", err)
  802. }
  803. if !strings.Contains(out, "foo") {
  804. t.Errorf("unexpected output: %s", out)
  805. }
  806. out, err = DefaultObjectDescriber.DescribeObject(&corev1.ReplicationController{
  807. ObjectMeta: metav1.ObjectMeta{Name: "foo"},
  808. Spec: corev1.ReplicationControllerSpec{Replicas: utilpointer.Int32Ptr(1)},
  809. })
  810. if err != nil {
  811. t.Fatalf("unexpected error: %v", err)
  812. }
  813. if !strings.Contains(out, "foo") {
  814. t.Errorf("unexpected output: %s", out)
  815. }
  816. out, err = DefaultObjectDescriber.DescribeObject(&corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "foo"}})
  817. if err != nil {
  818. t.Fatalf("unexpected error: %v", err)
  819. }
  820. if !strings.Contains(out, "foo") {
  821. t.Errorf("unexpected output: %s", out)
  822. }
  823. }
  824. func TestGetPodsTotalRequests(t *testing.T) {
  825. testCases := []struct {
  826. name string
  827. pods *corev1.PodList
  828. expectedReqs map[corev1.ResourceName]resource.Quantity
  829. }{
  830. {
  831. name: "test1",
  832. pods: &corev1.PodList{
  833. Items: []corev1.Pod{
  834. {
  835. Spec: corev1.PodSpec{
  836. Containers: []corev1.Container{
  837. {
  838. Resources: corev1.ResourceRequirements{
  839. Requests: corev1.ResourceList{
  840. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("1"),
  841. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("300Mi"),
  842. corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("1G"),
  843. },
  844. },
  845. },
  846. {
  847. Resources: corev1.ResourceRequirements{
  848. Requests: corev1.ResourceList{
  849. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("90m"),
  850. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("120Mi"),
  851. corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("200M"),
  852. },
  853. },
  854. },
  855. },
  856. },
  857. },
  858. {
  859. Spec: corev1.PodSpec{
  860. Containers: []corev1.Container{
  861. {
  862. Resources: corev1.ResourceRequirements{
  863. Requests: corev1.ResourceList{
  864. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("60m"),
  865. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("43Mi"),
  866. corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("500M"),
  867. },
  868. },
  869. },
  870. {
  871. Resources: corev1.ResourceRequirements{
  872. Requests: corev1.ResourceList{
  873. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("34m"),
  874. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("83Mi"),
  875. corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("700M"),
  876. },
  877. },
  878. },
  879. },
  880. },
  881. },
  882. },
  883. },
  884. expectedReqs: map[corev1.ResourceName]resource.Quantity{
  885. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("1.184"),
  886. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("546Mi"),
  887. corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("2.4G"),
  888. },
  889. },
  890. }
  891. for _, testCase := range testCases {
  892. t.Run(testCase.name, func(t *testing.T) {
  893. reqs, _ := getPodsTotalRequestsAndLimits(testCase.pods)
  894. if !apiequality.Semantic.DeepEqual(reqs, testCase.expectedReqs) {
  895. t.Errorf("Expected %v, got %v", testCase.expectedReqs, reqs)
  896. }
  897. })
  898. }
  899. }
  900. func TestPersistentVolumeDescriber(t *testing.T) {
  901. block := corev1.PersistentVolumeBlock
  902. file := corev1.PersistentVolumeFilesystem
  903. deletionTimestamp := metav1.Time{Time: time.Now().UTC().AddDate(-10, 0, 0)}
  904. testCases := []struct {
  905. name string
  906. plugin string
  907. pv *corev1.PersistentVolume
  908. expectedElements []string
  909. unexpectedElements []string
  910. }{
  911. {
  912. name: "test0",
  913. plugin: "hostpath",
  914. pv: &corev1.PersistentVolume{
  915. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  916. Spec: corev1.PersistentVolumeSpec{
  917. PersistentVolumeSource: corev1.PersistentVolumeSource{
  918. HostPath: &corev1.HostPathVolumeSource{Type: new(corev1.HostPathType)},
  919. },
  920. },
  921. },
  922. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  923. },
  924. {
  925. name: "test1",
  926. plugin: "gce",
  927. pv: &corev1.PersistentVolume{
  928. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  929. Spec: corev1.PersistentVolumeSpec{
  930. PersistentVolumeSource: corev1.PersistentVolumeSource{
  931. GCEPersistentDisk: &corev1.GCEPersistentDiskVolumeSource{},
  932. },
  933. VolumeMode: &file,
  934. },
  935. },
  936. expectedElements: []string{"VolumeMode", "Filesystem"},
  937. },
  938. {
  939. name: "test2",
  940. plugin: "ebs",
  941. pv: &corev1.PersistentVolume{
  942. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  943. Spec: corev1.PersistentVolumeSpec{
  944. PersistentVolumeSource: corev1.PersistentVolumeSource{
  945. AWSElasticBlockStore: &corev1.AWSElasticBlockStoreVolumeSource{},
  946. },
  947. },
  948. },
  949. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  950. },
  951. {
  952. name: "test3",
  953. plugin: "nfs",
  954. pv: &corev1.PersistentVolume{
  955. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  956. Spec: corev1.PersistentVolumeSpec{
  957. PersistentVolumeSource: corev1.PersistentVolumeSource{
  958. NFS: &corev1.NFSVolumeSource{},
  959. },
  960. },
  961. },
  962. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  963. },
  964. {
  965. name: "test4",
  966. plugin: "iscsi",
  967. pv: &corev1.PersistentVolume{
  968. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  969. Spec: corev1.PersistentVolumeSpec{
  970. PersistentVolumeSource: corev1.PersistentVolumeSource{
  971. ISCSI: &corev1.ISCSIPersistentVolumeSource{},
  972. },
  973. VolumeMode: &block,
  974. },
  975. },
  976. expectedElements: []string{"VolumeMode", "Block"},
  977. },
  978. {
  979. name: "test5",
  980. plugin: "gluster",
  981. pv: &corev1.PersistentVolume{
  982. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  983. Spec: corev1.PersistentVolumeSpec{
  984. PersistentVolumeSource: corev1.PersistentVolumeSource{
  985. Glusterfs: &corev1.GlusterfsPersistentVolumeSource{},
  986. },
  987. },
  988. },
  989. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  990. },
  991. {
  992. name: "test6",
  993. plugin: "rbd",
  994. pv: &corev1.PersistentVolume{
  995. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  996. Spec: corev1.PersistentVolumeSpec{
  997. PersistentVolumeSource: corev1.PersistentVolumeSource{
  998. RBD: &corev1.RBDPersistentVolumeSource{},
  999. },
  1000. },
  1001. },
  1002. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  1003. },
  1004. {
  1005. name: "test7",
  1006. plugin: "quobyte",
  1007. pv: &corev1.PersistentVolume{
  1008. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1009. Spec: corev1.PersistentVolumeSpec{
  1010. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1011. Quobyte: &corev1.QuobyteVolumeSource{},
  1012. },
  1013. },
  1014. },
  1015. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  1016. },
  1017. {
  1018. name: "test8",
  1019. plugin: "cinder",
  1020. pv: &corev1.PersistentVolume{
  1021. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1022. Spec: corev1.PersistentVolumeSpec{
  1023. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1024. Cinder: &corev1.CinderPersistentVolumeSource{},
  1025. },
  1026. },
  1027. },
  1028. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  1029. },
  1030. {
  1031. name: "test9",
  1032. plugin: "fc",
  1033. pv: &corev1.PersistentVolume{
  1034. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1035. Spec: corev1.PersistentVolumeSpec{
  1036. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1037. FC: &corev1.FCVolumeSource{},
  1038. },
  1039. VolumeMode: &block,
  1040. },
  1041. },
  1042. expectedElements: []string{"VolumeMode", "Block"},
  1043. },
  1044. {
  1045. name: "test10",
  1046. plugin: "local",
  1047. pv: &corev1.PersistentVolume{
  1048. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1049. Spec: corev1.PersistentVolumeSpec{
  1050. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1051. Local: &corev1.LocalVolumeSource{},
  1052. },
  1053. },
  1054. },
  1055. expectedElements: []string{"Node Affinity: <none>"},
  1056. unexpectedElements: []string{"Required Terms", "Term "},
  1057. },
  1058. {
  1059. name: "test11",
  1060. plugin: "local",
  1061. pv: &corev1.PersistentVolume{
  1062. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1063. Spec: corev1.PersistentVolumeSpec{
  1064. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1065. Local: &corev1.LocalVolumeSource{},
  1066. },
  1067. NodeAffinity: &corev1.VolumeNodeAffinity{},
  1068. },
  1069. },
  1070. expectedElements: []string{"Node Affinity: <none>"},
  1071. unexpectedElements: []string{"Required Terms", "Term "},
  1072. },
  1073. {
  1074. name: "test12",
  1075. plugin: "local",
  1076. pv: &corev1.PersistentVolume{
  1077. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1078. Spec: corev1.PersistentVolumeSpec{
  1079. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1080. Local: &corev1.LocalVolumeSource{},
  1081. },
  1082. NodeAffinity: &corev1.VolumeNodeAffinity{
  1083. Required: &corev1.NodeSelector{},
  1084. },
  1085. },
  1086. },
  1087. expectedElements: []string{"Node Affinity", "Required Terms: <none>"},
  1088. unexpectedElements: []string{"Term "},
  1089. },
  1090. {
  1091. name: "test13",
  1092. plugin: "local",
  1093. pv: &corev1.PersistentVolume{
  1094. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1095. Spec: corev1.PersistentVolumeSpec{
  1096. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1097. Local: &corev1.LocalVolumeSource{},
  1098. },
  1099. NodeAffinity: &corev1.VolumeNodeAffinity{
  1100. Required: &corev1.NodeSelector{
  1101. NodeSelectorTerms: []corev1.NodeSelectorTerm{
  1102. {
  1103. MatchExpressions: []corev1.NodeSelectorRequirement{},
  1104. },
  1105. {
  1106. MatchExpressions: []corev1.NodeSelectorRequirement{},
  1107. },
  1108. },
  1109. },
  1110. },
  1111. },
  1112. },
  1113. expectedElements: []string{"Node Affinity", "Required Terms", "Term 0", "Term 1"},
  1114. },
  1115. {
  1116. name: "test14",
  1117. plugin: "local",
  1118. pv: &corev1.PersistentVolume{
  1119. ObjectMeta: metav1.ObjectMeta{Name: "bar"},
  1120. Spec: corev1.PersistentVolumeSpec{
  1121. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1122. Local: &corev1.LocalVolumeSource{},
  1123. },
  1124. NodeAffinity: &corev1.VolumeNodeAffinity{
  1125. Required: &corev1.NodeSelector{
  1126. NodeSelectorTerms: []corev1.NodeSelectorTerm{
  1127. {
  1128. MatchExpressions: []corev1.NodeSelectorRequirement{
  1129. {
  1130. Key: "foo",
  1131. Operator: "In",
  1132. Values: []string{"val1", "val2"},
  1133. },
  1134. {
  1135. Key: "foo",
  1136. Operator: "Exists",
  1137. },
  1138. },
  1139. },
  1140. },
  1141. },
  1142. },
  1143. },
  1144. },
  1145. expectedElements: []string{"Node Affinity", "Required Terms", "Term 0",
  1146. "foo in [val1, val2]",
  1147. "foo exists"},
  1148. },
  1149. {
  1150. name: "test15",
  1151. plugin: "local",
  1152. pv: &corev1.PersistentVolume{
  1153. ObjectMeta: metav1.ObjectMeta{
  1154. Name: "bar",
  1155. DeletionTimestamp: &deletionTimestamp,
  1156. },
  1157. Spec: corev1.PersistentVolumeSpec{
  1158. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1159. Local: &corev1.LocalVolumeSource{},
  1160. },
  1161. },
  1162. },
  1163. expectedElements: []string{"Terminating (lasts 10y)"},
  1164. },
  1165. {
  1166. name: "test16",
  1167. plugin: "local",
  1168. pv: &corev1.PersistentVolume{
  1169. ObjectMeta: metav1.ObjectMeta{
  1170. Name: "bar",
  1171. GenerateName: "test-GenerateName",
  1172. UID: "test-UID",
  1173. CreationTimestamp: metav1.Time{Time: time.Now()},
  1174. DeletionTimestamp: &metav1.Time{Time: time.Now()},
  1175. DeletionGracePeriodSeconds: new(int64),
  1176. Labels: map[string]string{"label1": "label1", "label2": "label2", "label3": "label3"},
  1177. Annotations: map[string]string{"annotation1": "annotation1", "annotation2": "annotation2", "annotation3": "annotation3"},
  1178. },
  1179. Spec: corev1.PersistentVolumeSpec{
  1180. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1181. Local: &corev1.LocalVolumeSource{},
  1182. },
  1183. NodeAffinity: &corev1.VolumeNodeAffinity{
  1184. Required: &corev1.NodeSelector{
  1185. NodeSelectorTerms: []corev1.NodeSelectorTerm{
  1186. {
  1187. MatchExpressions: []corev1.NodeSelectorRequirement{
  1188. {
  1189. Key: "foo",
  1190. Operator: "In",
  1191. Values: []string{"val1", "val2"},
  1192. },
  1193. {
  1194. Key: "foo",
  1195. Operator: "Exists",
  1196. },
  1197. },
  1198. },
  1199. },
  1200. },
  1201. },
  1202. },
  1203. },
  1204. expectedElements: []string{"Node Affinity", "Required Terms", "Term 0",
  1205. "foo in [val1, val2]",
  1206. "foo exists"},
  1207. },
  1208. {
  1209. name: "test17",
  1210. plugin: "local",
  1211. pv: &corev1.PersistentVolume{
  1212. ObjectMeta: metav1.ObjectMeta{
  1213. Name: "bar",
  1214. GenerateName: "test-GenerateName",
  1215. UID: "test-UID",
  1216. CreationTimestamp: metav1.Time{Time: time.Now()},
  1217. DeletionTimestamp: &metav1.Time{Time: time.Now()},
  1218. DeletionGracePeriodSeconds: new(int64),
  1219. Labels: map[string]string{"label1": "label1", "label2": "label2", "label3": "label3"},
  1220. Annotations: map[string]string{"annotation1": "annotation1", "annotation2": "annotation2", "annotation3": "annotation3"},
  1221. },
  1222. Spec: corev1.PersistentVolumeSpec{
  1223. PersistentVolumeSource: corev1.PersistentVolumeSource{
  1224. CSI: &corev1.CSIPersistentVolumeSource{
  1225. Driver: "drive",
  1226. VolumeHandle: "handler",
  1227. ReadOnly: true,
  1228. VolumeAttributes: map[string]string{
  1229. "Attribute1": "Value1",
  1230. "Attribute2": "Value2",
  1231. "Attribute3": "Value3",
  1232. },
  1233. },
  1234. },
  1235. },
  1236. },
  1237. expectedElements: []string{"Driver", "VolumeHandle", "ReadOnly", "VolumeAttributes"},
  1238. },
  1239. }
  1240. for _, test := range testCases {
  1241. t.Run(test.name, func(t *testing.T) {
  1242. fake := fake.NewSimpleClientset(test.pv)
  1243. c := PersistentVolumeDescriber{fake}
  1244. str, err := c.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  1245. if err != nil {
  1246. t.Errorf("Unexpected error for test %s: %v", test.plugin, err)
  1247. }
  1248. if str == "" {
  1249. t.Errorf("Unexpected empty string for test %s. Expected PV Describer output", test.plugin)
  1250. }
  1251. for _, expected := range test.expectedElements {
  1252. if !strings.Contains(str, expected) {
  1253. t.Errorf("expected to find %q in output: %q", expected, str)
  1254. }
  1255. }
  1256. for _, unexpected := range test.unexpectedElements {
  1257. if strings.Contains(str, unexpected) {
  1258. t.Errorf("unexpected to find %q in output: %q", unexpected, str)
  1259. }
  1260. }
  1261. })
  1262. }
  1263. }
  1264. func TestPersistentVolumeClaimDescriber(t *testing.T) {
  1265. block := corev1.PersistentVolumeBlock
  1266. file := corev1.PersistentVolumeFilesystem
  1267. goldClassName := "gold"
  1268. now := time.Now()
  1269. deletionTimestamp := metav1.Time{Time: time.Now().UTC().AddDate(-10, 0, 0)}
  1270. testCases := []struct {
  1271. name string
  1272. pvc *corev1.PersistentVolumeClaim
  1273. expectedElements []string
  1274. unexpectedElements []string
  1275. }{
  1276. {
  1277. name: "default",
  1278. pvc: &corev1.PersistentVolumeClaim{
  1279. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1280. Spec: corev1.PersistentVolumeClaimSpec{
  1281. VolumeName: "volume1",
  1282. StorageClassName: &goldClassName,
  1283. },
  1284. Status: corev1.PersistentVolumeClaimStatus{
  1285. Phase: corev1.ClaimBound,
  1286. },
  1287. },
  1288. unexpectedElements: []string{"VolumeMode", "Filesystem"},
  1289. },
  1290. {
  1291. name: "filesystem",
  1292. pvc: &corev1.PersistentVolumeClaim{
  1293. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1294. Spec: corev1.PersistentVolumeClaimSpec{
  1295. VolumeName: "volume2",
  1296. StorageClassName: &goldClassName,
  1297. VolumeMode: &file,
  1298. },
  1299. Status: corev1.PersistentVolumeClaimStatus{
  1300. Phase: corev1.ClaimBound,
  1301. },
  1302. },
  1303. expectedElements: []string{"VolumeMode", "Filesystem"},
  1304. },
  1305. {
  1306. name: "block",
  1307. pvc: &corev1.PersistentVolumeClaim{
  1308. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1309. Spec: corev1.PersistentVolumeClaimSpec{
  1310. VolumeName: "volume3",
  1311. StorageClassName: &goldClassName,
  1312. VolumeMode: &block,
  1313. },
  1314. Status: corev1.PersistentVolumeClaimStatus{
  1315. Phase: corev1.ClaimBound,
  1316. },
  1317. },
  1318. expectedElements: []string{"VolumeMode", "Block"},
  1319. },
  1320. // Tests for Status.Condition.
  1321. {
  1322. name: "condition-type",
  1323. pvc: &corev1.PersistentVolumeClaim{
  1324. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1325. Spec: corev1.PersistentVolumeClaimSpec{
  1326. VolumeName: "volume4",
  1327. StorageClassName: &goldClassName,
  1328. },
  1329. Status: corev1.PersistentVolumeClaimStatus{
  1330. Conditions: []corev1.PersistentVolumeClaimCondition{
  1331. {Type: corev1.PersistentVolumeClaimResizing},
  1332. },
  1333. },
  1334. },
  1335. expectedElements: []string{"Conditions", "Type", "Resizing"},
  1336. },
  1337. {
  1338. name: "condition-status",
  1339. pvc: &corev1.PersistentVolumeClaim{
  1340. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1341. Spec: corev1.PersistentVolumeClaimSpec{
  1342. VolumeName: "volume5",
  1343. StorageClassName: &goldClassName,
  1344. },
  1345. Status: corev1.PersistentVolumeClaimStatus{
  1346. Conditions: []corev1.PersistentVolumeClaimCondition{
  1347. {Status: corev1.ConditionTrue},
  1348. },
  1349. },
  1350. },
  1351. expectedElements: []string{"Conditions", "Status", "True"},
  1352. },
  1353. {
  1354. name: "condition-last-probe-time",
  1355. pvc: &corev1.PersistentVolumeClaim{
  1356. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1357. Spec: corev1.PersistentVolumeClaimSpec{
  1358. VolumeName: "volume6",
  1359. StorageClassName: &goldClassName,
  1360. },
  1361. Status: corev1.PersistentVolumeClaimStatus{
  1362. Conditions: []corev1.PersistentVolumeClaimCondition{
  1363. {LastProbeTime: metav1.Time{Time: now}},
  1364. },
  1365. },
  1366. },
  1367. expectedElements: []string{"Conditions", "LastProbeTime", now.Format(time.RFC1123Z)},
  1368. },
  1369. {
  1370. name: "condition-last-transition-time",
  1371. pvc: &corev1.PersistentVolumeClaim{
  1372. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1373. Spec: corev1.PersistentVolumeClaimSpec{
  1374. VolumeName: "volume7",
  1375. StorageClassName: &goldClassName,
  1376. },
  1377. Status: corev1.PersistentVolumeClaimStatus{
  1378. Conditions: []corev1.PersistentVolumeClaimCondition{
  1379. {LastTransitionTime: metav1.Time{Time: now}},
  1380. },
  1381. },
  1382. },
  1383. expectedElements: []string{"Conditions", "LastTransitionTime", now.Format(time.RFC1123Z)},
  1384. },
  1385. {
  1386. name: "condition-reason",
  1387. pvc: &corev1.PersistentVolumeClaim{
  1388. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1389. Spec: corev1.PersistentVolumeClaimSpec{
  1390. VolumeName: "volume8",
  1391. StorageClassName: &goldClassName,
  1392. },
  1393. Status: corev1.PersistentVolumeClaimStatus{
  1394. Conditions: []corev1.PersistentVolumeClaimCondition{
  1395. {Reason: "OfflineResize"},
  1396. },
  1397. },
  1398. },
  1399. expectedElements: []string{"Conditions", "Reason", "OfflineResize"},
  1400. },
  1401. {
  1402. name: "condition-message",
  1403. pvc: &corev1.PersistentVolumeClaim{
  1404. ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"},
  1405. Spec: corev1.PersistentVolumeClaimSpec{
  1406. VolumeName: "volume9",
  1407. StorageClassName: &goldClassName,
  1408. },
  1409. Status: corev1.PersistentVolumeClaimStatus{
  1410. Conditions: []corev1.PersistentVolumeClaimCondition{
  1411. {Message: "User request resize"},
  1412. },
  1413. },
  1414. },
  1415. expectedElements: []string{"Conditions", "Message", "User request resize"},
  1416. },
  1417. {
  1418. name: "deletion-timestamp",
  1419. pvc: &corev1.PersistentVolumeClaim{
  1420. ObjectMeta: metav1.ObjectMeta{
  1421. Namespace: "foo",
  1422. Name: "bar",
  1423. DeletionTimestamp: &deletionTimestamp,
  1424. },
  1425. Spec: corev1.PersistentVolumeClaimSpec{
  1426. VolumeName: "volume10",
  1427. StorageClassName: &goldClassName,
  1428. },
  1429. Status: corev1.PersistentVolumeClaimStatus{},
  1430. },
  1431. expectedElements: []string{"Terminating (lasts 10y)"},
  1432. },
  1433. }
  1434. for _, test := range testCases {
  1435. t.Run(test.name, func(t *testing.T) {
  1436. fake := fake.NewSimpleClientset(test.pvc)
  1437. c := PersistentVolumeClaimDescriber{fake}
  1438. str, err := c.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  1439. if err != nil {
  1440. t.Errorf("Unexpected error for test %s: %v", test.name, err)
  1441. }
  1442. if str == "" {
  1443. t.Errorf("Unexpected empty string for test %s. Expected PVC Describer output", test.name)
  1444. }
  1445. for _, expected := range test.expectedElements {
  1446. if !strings.Contains(str, expected) {
  1447. t.Errorf("expected to find %q in output: %q", expected, str)
  1448. }
  1449. }
  1450. for _, unexpected := range test.unexpectedElements {
  1451. if strings.Contains(str, unexpected) {
  1452. t.Errorf("unexpected to find %q in output: %q", unexpected, str)
  1453. }
  1454. }
  1455. })
  1456. }
  1457. }
  1458. func TestDescribeDeployment(t *testing.T) {
  1459. fakeClient := fake.NewSimpleClientset(&appsv1.Deployment{
  1460. ObjectMeta: metav1.ObjectMeta{
  1461. Name: "bar",
  1462. Namespace: "foo",
  1463. },
  1464. Spec: appsv1.DeploymentSpec{
  1465. Replicas: utilpointer.Int32Ptr(1),
  1466. Selector: &metav1.LabelSelector{},
  1467. Template: corev1.PodTemplateSpec{
  1468. Spec: corev1.PodSpec{
  1469. Containers: []corev1.Container{
  1470. {Image: "mytest-image:latest"},
  1471. },
  1472. },
  1473. },
  1474. },
  1475. })
  1476. d := DeploymentDescriber{fakeClient}
  1477. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  1478. if err != nil {
  1479. t.Errorf("unexpected error: %v", err)
  1480. }
  1481. if !strings.Contains(out, "bar") || !strings.Contains(out, "foo") || !strings.Contains(out, "Containers:") || !strings.Contains(out, "mytest-image:latest") {
  1482. t.Errorf("unexpected out: %s", out)
  1483. }
  1484. }
  1485. func TestDescribeStorageClass(t *testing.T) {
  1486. reclaimPolicy := corev1.PersistentVolumeReclaimRetain
  1487. bindingMode := storagev1.VolumeBindingMode("bindingmode")
  1488. f := fake.NewSimpleClientset(&storagev1.StorageClass{
  1489. ObjectMeta: metav1.ObjectMeta{
  1490. Name: "foo",
  1491. ResourceVersion: "4",
  1492. Annotations: map[string]string{
  1493. "name": "foo",
  1494. },
  1495. },
  1496. Provisioner: "my-provisioner",
  1497. Parameters: map[string]string{
  1498. "param1": "value1",
  1499. "param2": "value2",
  1500. },
  1501. ReclaimPolicy: &reclaimPolicy,
  1502. VolumeBindingMode: &bindingMode,
  1503. AllowedTopologies: []corev1.TopologySelectorTerm{
  1504. {
  1505. MatchLabelExpressions: []corev1.TopologySelectorLabelRequirement{
  1506. {
  1507. Key: "failure-domain.beta.kubernetes.io/zone",
  1508. Values: []string{"zone1"},
  1509. },
  1510. {
  1511. Key: "kubernetes.io/hostname",
  1512. Values: []string{"node1"},
  1513. },
  1514. },
  1515. },
  1516. {
  1517. MatchLabelExpressions: []corev1.TopologySelectorLabelRequirement{
  1518. {
  1519. Key: "failure-domain.beta.kubernetes.io/zone",
  1520. Values: []string{"zone2"},
  1521. },
  1522. {
  1523. Key: "kubernetes.io/hostname",
  1524. Values: []string{"node2"},
  1525. },
  1526. },
  1527. },
  1528. },
  1529. })
  1530. s := StorageClassDescriber{f}
  1531. out, err := s.Describe("", "foo", describe.DescriberSettings{ShowEvents: true})
  1532. if err != nil {
  1533. t.Errorf("unexpected error: %v", err)
  1534. }
  1535. if !strings.Contains(out, "foo") ||
  1536. !strings.Contains(out, "my-provisioner") ||
  1537. !strings.Contains(out, "param1") ||
  1538. !strings.Contains(out, "param2") ||
  1539. !strings.Contains(out, "value1") ||
  1540. !strings.Contains(out, "value2") ||
  1541. !strings.Contains(out, "Retain") ||
  1542. !strings.Contains(out, "bindingmode") ||
  1543. !strings.Contains(out, "failure-domain.beta.kubernetes.io/zone") ||
  1544. !strings.Contains(out, "zone1") ||
  1545. !strings.Contains(out, "kubernetes.io/hostname") ||
  1546. !strings.Contains(out, "node1") ||
  1547. !strings.Contains(out, "zone2") ||
  1548. !strings.Contains(out, "node2") {
  1549. t.Errorf("unexpected out: %s", out)
  1550. }
  1551. }
  1552. func TestDescribePodDisruptionBudget(t *testing.T) {
  1553. minAvailable := intstr.FromInt(22)
  1554. f := fake.NewSimpleClientset(&policyv1beta1.PodDisruptionBudget{
  1555. ObjectMeta: metav1.ObjectMeta{
  1556. Namespace: "ns1",
  1557. Name: "pdb1",
  1558. CreationTimestamp: metav1.Time{Time: time.Now().Add(1.9e9)},
  1559. },
  1560. Spec: policyv1beta1.PodDisruptionBudgetSpec{
  1561. MinAvailable: &minAvailable,
  1562. },
  1563. Status: policyv1beta1.PodDisruptionBudgetStatus{
  1564. PodDisruptionsAllowed: 5,
  1565. },
  1566. })
  1567. s := PodDisruptionBudgetDescriber{f}
  1568. out, err := s.Describe("ns1", "pdb1", describe.DescriberSettings{ShowEvents: true})
  1569. if err != nil {
  1570. t.Errorf("unexpected error: %v", err)
  1571. }
  1572. if !strings.Contains(out, "pdb1") ||
  1573. !strings.Contains(out, "ns1") ||
  1574. !strings.Contains(out, "22") ||
  1575. !strings.Contains(out, "5") {
  1576. t.Errorf("unexpected out: %s", out)
  1577. }
  1578. }
  1579. func TestDescribeHorizontalPodAutoscaler(t *testing.T) {
  1580. minReplicasVal := int32(2)
  1581. targetUtilizationVal := int32(80)
  1582. currentUtilizationVal := int32(50)
  1583. metricLabelSelector, err := metav1.ParseToLabelSelector("label=value")
  1584. if err != nil {
  1585. t.Errorf("unable to parse label selector: %v", err)
  1586. }
  1587. testsV2beta2 := []struct {
  1588. name string
  1589. hpa autoscalingv2beta2.HorizontalPodAutoscaler
  1590. }{
  1591. {
  1592. "minReplicas unset",
  1593. autoscalingv2beta2.HorizontalPodAutoscaler{
  1594. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1595. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1596. Name: "some-rc",
  1597. Kind: "ReplicationController",
  1598. },
  1599. MaxReplicas: 10,
  1600. },
  1601. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1602. CurrentReplicas: 4,
  1603. DesiredReplicas: 5,
  1604. },
  1605. },
  1606. },
  1607. {
  1608. "external source type, target average value (no current)",
  1609. autoscalingv2beta2.HorizontalPodAutoscaler{
  1610. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1611. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1612. Name: "some-rc",
  1613. Kind: "ReplicationController",
  1614. },
  1615. MinReplicas: &minReplicasVal,
  1616. MaxReplicas: 10,
  1617. Metrics: []autoscalingv2beta2.MetricSpec{
  1618. {
  1619. Type: autoscalingv2beta2.ExternalMetricSourceType,
  1620. External: &autoscalingv2beta2.ExternalMetricSource{
  1621. Metric: autoscalingv2beta2.MetricIdentifier{
  1622. Name: "some-external-metric",
  1623. Selector: metricLabelSelector,
  1624. },
  1625. Target: autoscalingv2beta2.MetricTarget{
  1626. Type: autoscalingv2beta2.AverageValueMetricType,
  1627. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  1628. },
  1629. },
  1630. },
  1631. },
  1632. },
  1633. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1634. CurrentReplicas: 4,
  1635. DesiredReplicas: 5,
  1636. },
  1637. },
  1638. },
  1639. {
  1640. "external source type, target average value (with current)",
  1641. autoscalingv2beta2.HorizontalPodAutoscaler{
  1642. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1643. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1644. Name: "some-rc",
  1645. Kind: "ReplicationController",
  1646. },
  1647. MinReplicas: &minReplicasVal,
  1648. MaxReplicas: 10,
  1649. Metrics: []autoscalingv2beta2.MetricSpec{
  1650. {
  1651. Type: autoscalingv2beta2.ExternalMetricSourceType,
  1652. External: &autoscalingv2beta2.ExternalMetricSource{
  1653. Metric: autoscalingv2beta2.MetricIdentifier{
  1654. Name: "some-external-metric",
  1655. Selector: metricLabelSelector,
  1656. },
  1657. Target: autoscalingv2beta2.MetricTarget{
  1658. Type: autoscalingv2beta2.AverageValueMetricType,
  1659. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  1660. },
  1661. },
  1662. },
  1663. },
  1664. },
  1665. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1666. CurrentReplicas: 4,
  1667. DesiredReplicas: 5,
  1668. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  1669. {
  1670. Type: autoscalingv2beta2.ExternalMetricSourceType,
  1671. External: &autoscalingv2beta2.ExternalMetricStatus{
  1672. Metric: autoscalingv2beta2.MetricIdentifier{
  1673. Name: "some-external-metric",
  1674. Selector: metricLabelSelector,
  1675. },
  1676. Current: autoscalingv2beta2.MetricValueStatus{
  1677. AverageValue: resource.NewMilliQuantity(50, resource.DecimalSI),
  1678. },
  1679. },
  1680. },
  1681. },
  1682. },
  1683. },
  1684. },
  1685. {
  1686. "external source type, target value (no current)",
  1687. autoscalingv2beta2.HorizontalPodAutoscaler{
  1688. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1689. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1690. Name: "some-rc",
  1691. Kind: "ReplicationController",
  1692. },
  1693. MinReplicas: &minReplicasVal,
  1694. MaxReplicas: 10,
  1695. Metrics: []autoscalingv2beta2.MetricSpec{
  1696. {
  1697. Type: autoscalingv2beta2.ExternalMetricSourceType,
  1698. External: &autoscalingv2beta2.ExternalMetricSource{
  1699. Metric: autoscalingv2beta2.MetricIdentifier{
  1700. Name: "some-external-metric",
  1701. Selector: metricLabelSelector,
  1702. },
  1703. Target: autoscalingv2beta2.MetricTarget{
  1704. Type: autoscalingv2beta2.ValueMetricType,
  1705. Value: resource.NewMilliQuantity(100, resource.DecimalSI),
  1706. },
  1707. },
  1708. },
  1709. },
  1710. },
  1711. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1712. CurrentReplicas: 4,
  1713. DesiredReplicas: 5,
  1714. },
  1715. },
  1716. },
  1717. {
  1718. "external source type, target value (with current)",
  1719. autoscalingv2beta2.HorizontalPodAutoscaler{
  1720. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1721. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1722. Name: "some-rc",
  1723. Kind: "ReplicationController",
  1724. },
  1725. MinReplicas: &minReplicasVal,
  1726. MaxReplicas: 10,
  1727. Metrics: []autoscalingv2beta2.MetricSpec{
  1728. {
  1729. Type: autoscalingv2beta2.ExternalMetricSourceType,
  1730. External: &autoscalingv2beta2.ExternalMetricSource{
  1731. Metric: autoscalingv2beta2.MetricIdentifier{
  1732. Name: "some-external-metric",
  1733. Selector: metricLabelSelector,
  1734. },
  1735. Target: autoscalingv2beta2.MetricTarget{
  1736. Type: autoscalingv2beta2.ValueMetricType,
  1737. Value: resource.NewMilliQuantity(100, resource.DecimalSI),
  1738. },
  1739. },
  1740. },
  1741. },
  1742. },
  1743. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1744. CurrentReplicas: 4,
  1745. DesiredReplicas: 5,
  1746. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  1747. {
  1748. Type: autoscalingv2beta2.ExternalMetricSourceType,
  1749. External: &autoscalingv2beta2.ExternalMetricStatus{
  1750. Metric: autoscalingv2beta2.MetricIdentifier{
  1751. Name: "some-external-metric",
  1752. Selector: metricLabelSelector,
  1753. },
  1754. Current: autoscalingv2beta2.MetricValueStatus{
  1755. Value: resource.NewMilliQuantity(50, resource.DecimalSI),
  1756. },
  1757. },
  1758. },
  1759. },
  1760. },
  1761. },
  1762. },
  1763. {
  1764. "pods source type (no current)",
  1765. autoscalingv2beta2.HorizontalPodAutoscaler{
  1766. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1767. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1768. Name: "some-rc",
  1769. Kind: "ReplicationController",
  1770. },
  1771. MinReplicas: &minReplicasVal,
  1772. MaxReplicas: 10,
  1773. Metrics: []autoscalingv2beta2.MetricSpec{
  1774. {
  1775. Type: autoscalingv2beta2.PodsMetricSourceType,
  1776. Pods: &autoscalingv2beta2.PodsMetricSource{
  1777. Metric: autoscalingv2beta2.MetricIdentifier{
  1778. Name: "some-pods-metric",
  1779. },
  1780. Target: autoscalingv2beta2.MetricTarget{
  1781. Type: autoscalingv2beta2.AverageValueMetricType,
  1782. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  1783. },
  1784. },
  1785. },
  1786. },
  1787. },
  1788. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1789. CurrentReplicas: 4,
  1790. DesiredReplicas: 5,
  1791. },
  1792. },
  1793. },
  1794. {
  1795. "pods source type (with current)",
  1796. autoscalingv2beta2.HorizontalPodAutoscaler{
  1797. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1798. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1799. Name: "some-rc",
  1800. Kind: "ReplicationController",
  1801. },
  1802. MinReplicas: &minReplicasVal,
  1803. MaxReplicas: 10,
  1804. Metrics: []autoscalingv2beta2.MetricSpec{
  1805. {
  1806. Type: autoscalingv2beta2.PodsMetricSourceType,
  1807. Pods: &autoscalingv2beta2.PodsMetricSource{
  1808. Metric: autoscalingv2beta2.MetricIdentifier{
  1809. Name: "some-pods-metric",
  1810. },
  1811. Target: autoscalingv2beta2.MetricTarget{
  1812. Type: autoscalingv2beta2.AverageValueMetricType,
  1813. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  1814. },
  1815. },
  1816. },
  1817. },
  1818. },
  1819. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1820. CurrentReplicas: 4,
  1821. DesiredReplicas: 5,
  1822. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  1823. {
  1824. Type: autoscalingv2beta2.PodsMetricSourceType,
  1825. Pods: &autoscalingv2beta2.PodsMetricStatus{
  1826. Metric: autoscalingv2beta2.MetricIdentifier{
  1827. Name: "some-pods-metric",
  1828. },
  1829. Current: autoscalingv2beta2.MetricValueStatus{
  1830. AverageValue: resource.NewMilliQuantity(50, resource.DecimalSI),
  1831. },
  1832. },
  1833. },
  1834. },
  1835. },
  1836. },
  1837. },
  1838. {
  1839. "object source type target average value (no current)",
  1840. autoscalingv2beta2.HorizontalPodAutoscaler{
  1841. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1842. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1843. Name: "some-rc",
  1844. Kind: "ReplicationController",
  1845. },
  1846. MinReplicas: &minReplicasVal,
  1847. MaxReplicas: 10,
  1848. Metrics: []autoscalingv2beta2.MetricSpec{
  1849. {
  1850. Type: autoscalingv2beta2.ObjectMetricSourceType,
  1851. Object: &autoscalingv2beta2.ObjectMetricSource{
  1852. DescribedObject: autoscalingv2beta2.CrossVersionObjectReference{
  1853. Name: "some-service",
  1854. Kind: "Service",
  1855. },
  1856. Metric: autoscalingv2beta2.MetricIdentifier{
  1857. Name: "some-service-metric",
  1858. },
  1859. Target: autoscalingv2beta2.MetricTarget{
  1860. Type: autoscalingv2beta2.AverageValueMetricType,
  1861. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  1862. },
  1863. },
  1864. },
  1865. },
  1866. },
  1867. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1868. CurrentReplicas: 4,
  1869. DesiredReplicas: 5,
  1870. },
  1871. },
  1872. },
  1873. {
  1874. "object source type target average value (with current)",
  1875. autoscalingv2beta2.HorizontalPodAutoscaler{
  1876. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1877. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1878. Name: "some-rc",
  1879. Kind: "ReplicationController",
  1880. },
  1881. MinReplicas: &minReplicasVal,
  1882. MaxReplicas: 10,
  1883. Metrics: []autoscalingv2beta2.MetricSpec{
  1884. {
  1885. Type: autoscalingv2beta2.ObjectMetricSourceType,
  1886. Object: &autoscalingv2beta2.ObjectMetricSource{
  1887. DescribedObject: autoscalingv2beta2.CrossVersionObjectReference{
  1888. Name: "some-service",
  1889. Kind: "Service",
  1890. },
  1891. Metric: autoscalingv2beta2.MetricIdentifier{
  1892. Name: "some-service-metric",
  1893. },
  1894. Target: autoscalingv2beta2.MetricTarget{
  1895. Type: autoscalingv2beta2.AverageValueMetricType,
  1896. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  1897. },
  1898. },
  1899. },
  1900. },
  1901. },
  1902. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1903. CurrentReplicas: 4,
  1904. DesiredReplicas: 5,
  1905. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  1906. {
  1907. Type: autoscalingv2beta2.ObjectMetricSourceType,
  1908. Object: &autoscalingv2beta2.ObjectMetricStatus{
  1909. DescribedObject: autoscalingv2beta2.CrossVersionObjectReference{
  1910. Name: "some-service",
  1911. Kind: "Service",
  1912. },
  1913. Metric: autoscalingv2beta2.MetricIdentifier{
  1914. Name: "some-service-metric",
  1915. },
  1916. Current: autoscalingv2beta2.MetricValueStatus{
  1917. AverageValue: resource.NewMilliQuantity(50, resource.DecimalSI),
  1918. },
  1919. },
  1920. },
  1921. },
  1922. },
  1923. },
  1924. },
  1925. {
  1926. "object source type target value (no current)",
  1927. autoscalingv2beta2.HorizontalPodAutoscaler{
  1928. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1929. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1930. Name: "some-rc",
  1931. Kind: "ReplicationController",
  1932. },
  1933. MinReplicas: &minReplicasVal,
  1934. MaxReplicas: 10,
  1935. Metrics: []autoscalingv2beta2.MetricSpec{
  1936. {
  1937. Type: autoscalingv2beta2.ObjectMetricSourceType,
  1938. Object: &autoscalingv2beta2.ObjectMetricSource{
  1939. DescribedObject: autoscalingv2beta2.CrossVersionObjectReference{
  1940. Name: "some-service",
  1941. Kind: "Service",
  1942. },
  1943. Metric: autoscalingv2beta2.MetricIdentifier{
  1944. Name: "some-service-metric",
  1945. },
  1946. Target: autoscalingv2beta2.MetricTarget{
  1947. Type: autoscalingv2beta2.ValueMetricType,
  1948. Value: resource.NewMilliQuantity(100, resource.DecimalSI),
  1949. },
  1950. },
  1951. },
  1952. },
  1953. },
  1954. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1955. CurrentReplicas: 4,
  1956. DesiredReplicas: 5,
  1957. },
  1958. },
  1959. },
  1960. {
  1961. "object source type target value (with current)",
  1962. autoscalingv2beta2.HorizontalPodAutoscaler{
  1963. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  1964. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  1965. Name: "some-rc",
  1966. Kind: "ReplicationController",
  1967. },
  1968. MinReplicas: &minReplicasVal,
  1969. MaxReplicas: 10,
  1970. Metrics: []autoscalingv2beta2.MetricSpec{
  1971. {
  1972. Type: autoscalingv2beta2.ObjectMetricSourceType,
  1973. Object: &autoscalingv2beta2.ObjectMetricSource{
  1974. DescribedObject: autoscalingv2beta2.CrossVersionObjectReference{
  1975. Name: "some-service",
  1976. Kind: "Service",
  1977. },
  1978. Metric: autoscalingv2beta2.MetricIdentifier{
  1979. Name: "some-service-metric",
  1980. },
  1981. Target: autoscalingv2beta2.MetricTarget{
  1982. Type: autoscalingv2beta2.ValueMetricType,
  1983. Value: resource.NewMilliQuantity(100, resource.DecimalSI),
  1984. },
  1985. },
  1986. },
  1987. },
  1988. },
  1989. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  1990. CurrentReplicas: 4,
  1991. DesiredReplicas: 5,
  1992. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  1993. {
  1994. Type: autoscalingv2beta2.ObjectMetricSourceType,
  1995. Object: &autoscalingv2beta2.ObjectMetricStatus{
  1996. DescribedObject: autoscalingv2beta2.CrossVersionObjectReference{
  1997. Name: "some-service",
  1998. Kind: "Service",
  1999. },
  2000. Metric: autoscalingv2beta2.MetricIdentifier{
  2001. Name: "some-service-metric",
  2002. },
  2003. Current: autoscalingv2beta2.MetricValueStatus{
  2004. Value: resource.NewMilliQuantity(50, resource.DecimalSI),
  2005. },
  2006. },
  2007. },
  2008. },
  2009. },
  2010. },
  2011. },
  2012. {
  2013. "resource source type, target average value (no current)",
  2014. autoscalingv2beta2.HorizontalPodAutoscaler{
  2015. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  2016. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  2017. Name: "some-rc",
  2018. Kind: "ReplicationController",
  2019. },
  2020. MinReplicas: &minReplicasVal,
  2021. MaxReplicas: 10,
  2022. Metrics: []autoscalingv2beta2.MetricSpec{
  2023. {
  2024. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2025. Resource: &autoscalingv2beta2.ResourceMetricSource{
  2026. Name: corev1.ResourceCPU,
  2027. Target: autoscalingv2beta2.MetricTarget{
  2028. Type: autoscalingv2beta2.AverageValueMetricType,
  2029. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  2030. },
  2031. },
  2032. },
  2033. },
  2034. },
  2035. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  2036. CurrentReplicas: 4,
  2037. DesiredReplicas: 5,
  2038. },
  2039. },
  2040. },
  2041. {
  2042. "resource source type, target average value (with current)",
  2043. autoscalingv2beta2.HorizontalPodAutoscaler{
  2044. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  2045. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  2046. Name: "some-rc",
  2047. Kind: "ReplicationController",
  2048. },
  2049. MinReplicas: &minReplicasVal,
  2050. MaxReplicas: 10,
  2051. Metrics: []autoscalingv2beta2.MetricSpec{
  2052. {
  2053. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2054. Resource: &autoscalingv2beta2.ResourceMetricSource{
  2055. Name: corev1.ResourceCPU,
  2056. Target: autoscalingv2beta2.MetricTarget{
  2057. Type: autoscalingv2beta2.AverageValueMetricType,
  2058. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  2059. },
  2060. },
  2061. },
  2062. },
  2063. },
  2064. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  2065. CurrentReplicas: 4,
  2066. DesiredReplicas: 5,
  2067. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  2068. {
  2069. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2070. Resource: &autoscalingv2beta2.ResourceMetricStatus{
  2071. Name: corev1.ResourceCPU,
  2072. Current: autoscalingv2beta2.MetricValueStatus{
  2073. AverageValue: resource.NewMilliQuantity(50, resource.DecimalSI),
  2074. },
  2075. },
  2076. },
  2077. },
  2078. },
  2079. },
  2080. },
  2081. {
  2082. "resource source type, target utilization (no current)",
  2083. autoscalingv2beta2.HorizontalPodAutoscaler{
  2084. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  2085. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  2086. Name: "some-rc",
  2087. Kind: "ReplicationController",
  2088. },
  2089. MinReplicas: &minReplicasVal,
  2090. MaxReplicas: 10,
  2091. Metrics: []autoscalingv2beta2.MetricSpec{
  2092. {
  2093. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2094. Resource: &autoscalingv2beta2.ResourceMetricSource{
  2095. Name: corev1.ResourceCPU,
  2096. Target: autoscalingv2beta2.MetricTarget{
  2097. Type: autoscalingv2beta2.UtilizationMetricType,
  2098. AverageUtilization: &targetUtilizationVal,
  2099. },
  2100. },
  2101. },
  2102. },
  2103. },
  2104. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  2105. CurrentReplicas: 4,
  2106. DesiredReplicas: 5,
  2107. },
  2108. },
  2109. },
  2110. {
  2111. "resource source type, target utilization (with current)",
  2112. autoscalingv2beta2.HorizontalPodAutoscaler{
  2113. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  2114. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  2115. Name: "some-rc",
  2116. Kind: "ReplicationController",
  2117. },
  2118. MinReplicas: &minReplicasVal,
  2119. MaxReplicas: 10,
  2120. Metrics: []autoscalingv2beta2.MetricSpec{
  2121. {
  2122. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2123. Resource: &autoscalingv2beta2.ResourceMetricSource{
  2124. Name: corev1.ResourceCPU,
  2125. Target: autoscalingv2beta2.MetricTarget{
  2126. Type: autoscalingv2beta2.UtilizationMetricType,
  2127. AverageUtilization: &targetUtilizationVal,
  2128. },
  2129. },
  2130. },
  2131. },
  2132. },
  2133. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  2134. CurrentReplicas: 4,
  2135. DesiredReplicas: 5,
  2136. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  2137. {
  2138. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2139. Resource: &autoscalingv2beta2.ResourceMetricStatus{
  2140. Name: corev1.ResourceCPU,
  2141. Current: autoscalingv2beta2.MetricValueStatus{
  2142. AverageUtilization: &currentUtilizationVal,
  2143. AverageValue: resource.NewMilliQuantity(40, resource.DecimalSI),
  2144. },
  2145. },
  2146. },
  2147. },
  2148. },
  2149. },
  2150. },
  2151. {
  2152. "multiple metrics",
  2153. autoscalingv2beta2.HorizontalPodAutoscaler{
  2154. Spec: autoscalingv2beta2.HorizontalPodAutoscalerSpec{
  2155. ScaleTargetRef: autoscalingv2beta2.CrossVersionObjectReference{
  2156. Name: "some-rc",
  2157. Kind: "ReplicationController",
  2158. },
  2159. MinReplicas: &minReplicasVal,
  2160. MaxReplicas: 10,
  2161. Metrics: []autoscalingv2beta2.MetricSpec{
  2162. {
  2163. Type: autoscalingv2beta2.PodsMetricSourceType,
  2164. Pods: &autoscalingv2beta2.PodsMetricSource{
  2165. Metric: autoscalingv2beta2.MetricIdentifier{
  2166. Name: "some-pods-metric",
  2167. },
  2168. Target: autoscalingv2beta2.MetricTarget{
  2169. Type: autoscalingv2beta2.AverageValueMetricType,
  2170. AverageValue: resource.NewMilliQuantity(100, resource.DecimalSI),
  2171. },
  2172. },
  2173. },
  2174. {
  2175. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2176. Resource: &autoscalingv2beta2.ResourceMetricSource{
  2177. Name: corev1.ResourceCPU,
  2178. Target: autoscalingv2beta2.MetricTarget{
  2179. Type: autoscalingv2beta2.UtilizationMetricType,
  2180. AverageUtilization: &targetUtilizationVal,
  2181. },
  2182. },
  2183. },
  2184. {
  2185. Type: autoscalingv2beta2.PodsMetricSourceType,
  2186. Pods: &autoscalingv2beta2.PodsMetricSource{
  2187. Metric: autoscalingv2beta2.MetricIdentifier{
  2188. Name: "other-pods-metric",
  2189. },
  2190. Target: autoscalingv2beta2.MetricTarget{
  2191. Type: autoscalingv2beta2.AverageValueMetricType,
  2192. AverageValue: resource.NewMilliQuantity(400, resource.DecimalSI),
  2193. },
  2194. },
  2195. },
  2196. },
  2197. },
  2198. Status: autoscalingv2beta2.HorizontalPodAutoscalerStatus{
  2199. CurrentReplicas: 4,
  2200. DesiredReplicas: 5,
  2201. CurrentMetrics: []autoscalingv2beta2.MetricStatus{
  2202. {
  2203. Type: autoscalingv2beta2.PodsMetricSourceType,
  2204. Pods: &autoscalingv2beta2.PodsMetricStatus{
  2205. Metric: autoscalingv2beta2.MetricIdentifier{
  2206. Name: "some-pods-metric",
  2207. },
  2208. Current: autoscalingv2beta2.MetricValueStatus{
  2209. AverageValue: resource.NewMilliQuantity(50, resource.DecimalSI),
  2210. },
  2211. },
  2212. },
  2213. {
  2214. Type: autoscalingv2beta2.ResourceMetricSourceType,
  2215. Resource: &autoscalingv2beta2.ResourceMetricStatus{
  2216. Name: corev1.ResourceCPU,
  2217. Current: autoscalingv2beta2.MetricValueStatus{
  2218. AverageUtilization: &currentUtilizationVal,
  2219. AverageValue: resource.NewMilliQuantity(40, resource.DecimalSI),
  2220. },
  2221. },
  2222. },
  2223. },
  2224. },
  2225. },
  2226. },
  2227. }
  2228. for _, test := range testsV2beta2 {
  2229. t.Run(test.name, func(t *testing.T) {
  2230. test.hpa.ObjectMeta = metav1.ObjectMeta{
  2231. Name: "bar",
  2232. Namespace: "foo",
  2233. }
  2234. fake := fake.NewSimpleClientset(&test.hpa)
  2235. desc := HorizontalPodAutoscalerDescriber{fake}
  2236. str, err := desc.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  2237. if err != nil {
  2238. t.Errorf("Unexpected error for test %s: %v", test.name, err)
  2239. }
  2240. if str == "" {
  2241. t.Errorf("Unexpected empty string for test %s. Expected HPA Describer output", test.name)
  2242. }
  2243. t.Logf("Description for %q:\n%s", test.name, str)
  2244. })
  2245. }
  2246. testsV1 := []struct {
  2247. name string
  2248. hpa autoscalingv1.HorizontalPodAutoscaler
  2249. }{
  2250. {
  2251. "minReplicas unset",
  2252. autoscalingv1.HorizontalPodAutoscaler{
  2253. Spec: autoscalingv1.HorizontalPodAutoscalerSpec{
  2254. ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
  2255. Name: "some-rc",
  2256. Kind: "ReplicationController",
  2257. },
  2258. MaxReplicas: 10,
  2259. },
  2260. Status: autoscalingv1.HorizontalPodAutoscalerStatus{
  2261. CurrentReplicas: 4,
  2262. DesiredReplicas: 5,
  2263. },
  2264. },
  2265. },
  2266. {
  2267. "minReplicas set",
  2268. autoscalingv1.HorizontalPodAutoscaler{
  2269. Spec: autoscalingv1.HorizontalPodAutoscalerSpec{
  2270. ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
  2271. Name: "some-rc",
  2272. Kind: "ReplicationController",
  2273. },
  2274. MinReplicas: &minReplicasVal,
  2275. MaxReplicas: 10,
  2276. },
  2277. Status: autoscalingv1.HorizontalPodAutoscalerStatus{
  2278. CurrentReplicas: 4,
  2279. DesiredReplicas: 5,
  2280. },
  2281. },
  2282. },
  2283. {
  2284. "with target no current",
  2285. autoscalingv1.HorizontalPodAutoscaler{
  2286. Spec: autoscalingv1.HorizontalPodAutoscalerSpec{
  2287. ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
  2288. Name: "some-rc",
  2289. Kind: "ReplicationController",
  2290. },
  2291. MinReplicas: &minReplicasVal,
  2292. MaxReplicas: 10,
  2293. TargetCPUUtilizationPercentage: &targetUtilizationVal,
  2294. },
  2295. Status: autoscalingv1.HorizontalPodAutoscalerStatus{
  2296. CurrentReplicas: 4,
  2297. DesiredReplicas: 5,
  2298. },
  2299. },
  2300. },
  2301. {
  2302. "with target and current",
  2303. autoscalingv1.HorizontalPodAutoscaler{
  2304. Spec: autoscalingv1.HorizontalPodAutoscalerSpec{
  2305. ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
  2306. Name: "some-rc",
  2307. Kind: "ReplicationController",
  2308. },
  2309. MinReplicas: &minReplicasVal,
  2310. MaxReplicas: 10,
  2311. TargetCPUUtilizationPercentage: &targetUtilizationVal,
  2312. },
  2313. Status: autoscalingv1.HorizontalPodAutoscalerStatus{
  2314. CurrentReplicas: 4,
  2315. DesiredReplicas: 5,
  2316. CurrentCPUUtilizationPercentage: &currentUtilizationVal,
  2317. },
  2318. },
  2319. },
  2320. }
  2321. for _, test := range testsV1 {
  2322. t.Run(test.name, func(t *testing.T) {
  2323. test.hpa.ObjectMeta = metav1.ObjectMeta{
  2324. Name: "bar",
  2325. Namespace: "foo",
  2326. }
  2327. fake := fake.NewSimpleClientset(&test.hpa)
  2328. desc := HorizontalPodAutoscalerDescriber{fake}
  2329. str, err := desc.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  2330. if err != nil {
  2331. t.Errorf("Unexpected error for test %s: %v", test.name, err)
  2332. }
  2333. if str == "" {
  2334. t.Errorf("Unexpected empty string for test %s. Expected HPA Describer output", test.name)
  2335. }
  2336. t.Logf("Description for %q:\n%s", test.name, str)
  2337. })
  2338. }
  2339. }
  2340. func TestDescribeEvents(t *testing.T) {
  2341. events := &corev1.EventList{
  2342. Items: []corev1.Event{
  2343. {
  2344. ObjectMeta: metav1.ObjectMeta{
  2345. Namespace: "foo",
  2346. },
  2347. Source: corev1.EventSource{Component: "kubelet"},
  2348. Message: "Item 1",
  2349. FirstTimestamp: metav1.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)),
  2350. LastTimestamp: metav1.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)),
  2351. Count: 1,
  2352. Type: corev1.EventTypeNormal,
  2353. },
  2354. },
  2355. }
  2356. m := map[string]describe.Describer{
  2357. "DaemonSetDescriber": &DaemonSetDescriber{
  2358. fake.NewSimpleClientset(&appsv1.DaemonSet{
  2359. ObjectMeta: metav1.ObjectMeta{
  2360. Name: "bar",
  2361. Namespace: "foo",
  2362. },
  2363. }, events),
  2364. },
  2365. "DeploymentDescriber": &DeploymentDescriber{
  2366. fake.NewSimpleClientset(&appsv1.Deployment{
  2367. ObjectMeta: metav1.ObjectMeta{
  2368. Name: "bar",
  2369. Namespace: "foo",
  2370. },
  2371. Spec: appsv1.DeploymentSpec{
  2372. Replicas: utilpointer.Int32Ptr(1),
  2373. Selector: &metav1.LabelSelector{},
  2374. },
  2375. }, events),
  2376. },
  2377. "EndpointsDescriber": &EndpointsDescriber{
  2378. fake.NewSimpleClientset(&corev1.Endpoints{
  2379. ObjectMeta: metav1.ObjectMeta{
  2380. Name: "bar",
  2381. Namespace: "foo",
  2382. },
  2383. }, events),
  2384. },
  2385. // TODO(jchaloup): add tests for:
  2386. // - IngressDescriber
  2387. // - JobDescriber
  2388. "NodeDescriber": &NodeDescriber{
  2389. fake.NewSimpleClientset(&corev1.Node{
  2390. ObjectMeta: metav1.ObjectMeta{
  2391. Name: "bar",
  2392. SelfLink: "url/url/url/url",
  2393. },
  2394. }, events),
  2395. },
  2396. "PersistentVolumeDescriber": &PersistentVolumeDescriber{
  2397. fake.NewSimpleClientset(&corev1.PersistentVolume{
  2398. ObjectMeta: metav1.ObjectMeta{
  2399. Name: "bar",
  2400. SelfLink: "url/url/url/url",
  2401. },
  2402. }, events),
  2403. },
  2404. "PodDescriber": &PodDescriber{
  2405. fake.NewSimpleClientset(&corev1.Pod{
  2406. ObjectMeta: metav1.ObjectMeta{
  2407. Name: "bar",
  2408. Namespace: "foo",
  2409. SelfLink: "url/url/url/url",
  2410. },
  2411. }, events),
  2412. },
  2413. "ReplicaSetDescriber": &ReplicaSetDescriber{
  2414. fake.NewSimpleClientset(&appsv1.ReplicaSet{
  2415. ObjectMeta: metav1.ObjectMeta{
  2416. Name: "bar",
  2417. Namespace: "foo",
  2418. },
  2419. Spec: appsv1.ReplicaSetSpec{
  2420. Replicas: utilpointer.Int32Ptr(1),
  2421. },
  2422. }, events),
  2423. },
  2424. "ReplicationControllerDescriber": &ReplicationControllerDescriber{
  2425. fake.NewSimpleClientset(&corev1.ReplicationController{
  2426. ObjectMeta: metav1.ObjectMeta{
  2427. Name: "bar",
  2428. Namespace: "foo",
  2429. },
  2430. Spec: corev1.ReplicationControllerSpec{
  2431. Replicas: utilpointer.Int32Ptr(1),
  2432. },
  2433. }, events),
  2434. },
  2435. "Service": &ServiceDescriber{
  2436. fake.NewSimpleClientset(&corev1.Service{
  2437. ObjectMeta: metav1.ObjectMeta{
  2438. Name: "bar",
  2439. Namespace: "foo",
  2440. },
  2441. }, events),
  2442. },
  2443. "StorageClass": &StorageClassDescriber{
  2444. fake.NewSimpleClientset(&storagev1.StorageClass{
  2445. ObjectMeta: metav1.ObjectMeta{
  2446. Name: "bar",
  2447. },
  2448. }, events),
  2449. },
  2450. "HorizontalPodAutoscaler": &HorizontalPodAutoscalerDescriber{
  2451. fake.NewSimpleClientset(&autoscalingv2beta2.HorizontalPodAutoscaler{
  2452. ObjectMeta: metav1.ObjectMeta{
  2453. Name: "bar",
  2454. Namespace: "foo",
  2455. },
  2456. }, events),
  2457. },
  2458. "ConfigMap": &ConfigMapDescriber{
  2459. fake.NewSimpleClientset(&corev1.ConfigMap{
  2460. ObjectMeta: metav1.ObjectMeta{
  2461. Name: "bar",
  2462. Namespace: "foo",
  2463. },
  2464. }, events),
  2465. },
  2466. }
  2467. for name, d := range m {
  2468. t.Run(name, func(t *testing.T) {
  2469. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  2470. if err != nil {
  2471. t.Errorf("unexpected error for %q: %v", name, err)
  2472. }
  2473. if !strings.Contains(out, "bar") {
  2474. t.Errorf("unexpected out for %q: %s", name, out)
  2475. }
  2476. if !strings.Contains(out, "Events:") {
  2477. t.Errorf("events not found for %q when ShowEvents=true: %s", name, out)
  2478. }
  2479. out, err = d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: false})
  2480. if err != nil {
  2481. t.Errorf("unexpected error for %q: %s", name, err)
  2482. }
  2483. if !strings.Contains(out, "bar") {
  2484. t.Errorf("unexpected out for %q: %s", name, out)
  2485. }
  2486. if strings.Contains(out, "Events:") {
  2487. t.Errorf("events found for %q when ShowEvents=false: %s", name, out)
  2488. }
  2489. })
  2490. }
  2491. }
  2492. func TestPrintLabelsMultiline(t *testing.T) {
  2493. key := "MaxLenAnnotation"
  2494. value := strings.Repeat("a", maxAnnotationLen-len(key)-2)
  2495. testCases := []struct {
  2496. annotations map[string]string
  2497. expectPrint string
  2498. }{
  2499. {
  2500. annotations: map[string]string{"col1": "asd", "COL2": "zxc"},
  2501. expectPrint: "Annotations:\tCOL2: zxc\n\tcol1: asd\n",
  2502. },
  2503. {
  2504. annotations: map[string]string{"MaxLenAnnotation": value},
  2505. expectPrint: fmt.Sprintf("Annotations:\t%s: %s\n", key, value),
  2506. },
  2507. {
  2508. annotations: map[string]string{"MaxLenAnnotation": value + "1"},
  2509. expectPrint: fmt.Sprintf("Annotations:\t%s:\n\t %s\n", key, value+"1"),
  2510. },
  2511. {
  2512. annotations: map[string]string{"MaxLenAnnotation": value + value},
  2513. expectPrint: fmt.Sprintf("Annotations:\t%s:\n\t %s\n", key, strings.Repeat("a", maxAnnotationLen-2)+"..."),
  2514. },
  2515. {
  2516. annotations: map[string]string{"key": "value\nwith\nnewlines\n"},
  2517. expectPrint: "Annotations:\tkey:\n\t value\n\t with\n\t newlines\n",
  2518. },
  2519. {
  2520. annotations: map[string]string{},
  2521. expectPrint: "Annotations:\t<none>\n",
  2522. },
  2523. }
  2524. for i, testCase := range testCases {
  2525. t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
  2526. out := new(bytes.Buffer)
  2527. writer := NewPrefixWriter(out)
  2528. printAnnotationsMultiline(writer, "Annotations", testCase.annotations)
  2529. output := out.String()
  2530. if output != testCase.expectPrint {
  2531. t.Errorf("Test case %d: expected to match:\n%q\nin output:\n%q", i, testCase.expectPrint, output)
  2532. }
  2533. })
  2534. }
  2535. }
  2536. func TestDescribeUnstructuredContent(t *testing.T) {
  2537. testCases := []struct {
  2538. expected string
  2539. unexpected string
  2540. }{
  2541. {
  2542. expected: `API Version: v1
  2543. Dummy - Dummy: present
  2544. dummy-dummy@dummy: present
  2545. dummy/dummy: present
  2546. dummy2: present
  2547. Dummy Dummy: present
  2548. Items:
  2549. Item Bool: true
  2550. Item Int: 42
  2551. Kind: Test
  2552. Metadata:
  2553. Creation Timestamp: 2017-04-01T00:00:00Z
  2554. Name: MyName
  2555. Namespace: MyNamespace
  2556. Resource Version: 123
  2557. UID: 00000000-0000-0000-0000-000000000001
  2558. Status: ok
  2559. URL: http://localhost
  2560. `,
  2561. },
  2562. {
  2563. unexpected: "\nDummy 1:\tpresent\n",
  2564. },
  2565. {
  2566. unexpected: "Dummy 1",
  2567. },
  2568. {
  2569. unexpected: "Dummy 3",
  2570. },
  2571. {
  2572. unexpected: "Dummy3",
  2573. },
  2574. {
  2575. unexpected: "dummy3",
  2576. },
  2577. {
  2578. unexpected: "dummy 3",
  2579. },
  2580. }
  2581. out := new(bytes.Buffer)
  2582. w := NewPrefixWriter(out)
  2583. obj := &unstructured.Unstructured{
  2584. Object: map[string]interface{}{
  2585. "apiVersion": "v1",
  2586. "kind": "Test",
  2587. "dummyDummy": "present",
  2588. "dummy/dummy": "present",
  2589. "dummy-dummy@dummy": "present",
  2590. "dummy-dummy": "present",
  2591. "dummy1": "present",
  2592. "dummy2": "present",
  2593. "metadata": map[string]interface{}{
  2594. "name": "MyName",
  2595. "namespace": "MyNamespace",
  2596. "creationTimestamp": "2017-04-01T00:00:00Z",
  2597. "resourceVersion": 123,
  2598. "uid": "00000000-0000-0000-0000-000000000001",
  2599. "dummy3": "present",
  2600. },
  2601. "items": []interface{}{
  2602. map[string]interface{}{
  2603. "itemBool": true,
  2604. "itemInt": 42,
  2605. },
  2606. },
  2607. "url": "http://localhost",
  2608. "status": "ok",
  2609. },
  2610. }
  2611. printUnstructuredContent(w, LEVEL_0, obj.UnstructuredContent(), "", ".dummy1", ".metadata.dummy3")
  2612. output := out.String()
  2613. for _, test := range testCases {
  2614. if len(test.expected) > 0 {
  2615. if !strings.Contains(output, test.expected) {
  2616. t.Errorf("Expected to find %q in: %q", test.expected, output)
  2617. }
  2618. }
  2619. if len(test.unexpected) > 0 {
  2620. if strings.Contains(output, test.unexpected) {
  2621. t.Errorf("Didn't expect to find %q in: %q", test.unexpected, output)
  2622. }
  2623. }
  2624. }
  2625. }
  2626. func TestDescribePodSecurityPolicy(t *testing.T) {
  2627. expected := []string{
  2628. "Name:\\s*mypsp",
  2629. "Allow Privileged:\\s*false",
  2630. "Default Add Capabilities:\\s*<none>",
  2631. "Required Drop Capabilities:\\s*<none>",
  2632. "Allowed Capabilities:\\s*<none>",
  2633. "Allowed Volume Types:\\s*<none>",
  2634. "Allowed Unsafe Sysctls:\\s*kernel\\.\\*,net\\.ipv4.ip_local_port_range",
  2635. "Forbidden Sysctls:\\s*net\\.ipv4\\.ip_default_ttl",
  2636. "Allow Host Network:\\s*false",
  2637. "Allow Host Ports:\\s*<none>",
  2638. "Allow Host PID:\\s*false",
  2639. "Allow Host IPC:\\s*false",
  2640. "Read Only Root Filesystem:\\s*false",
  2641. "SELinux Context Strategy: RunAsAny",
  2642. "User:\\s*<none>",
  2643. "Role:\\s*<none>",
  2644. "Type:\\s*<none>",
  2645. "Level:\\s*<none>",
  2646. "Run As User Strategy: RunAsAny",
  2647. "FSGroup Strategy: RunAsAny",
  2648. "Supplemental Groups Strategy: RunAsAny",
  2649. }
  2650. fake := fake.NewSimpleClientset(&policyv1beta1.PodSecurityPolicy{
  2651. ObjectMeta: metav1.ObjectMeta{
  2652. Name: "mypsp",
  2653. },
  2654. Spec: policyv1beta1.PodSecurityPolicySpec{
  2655. AllowedUnsafeSysctls: []string{"kernel.*", "net.ipv4.ip_local_port_range"},
  2656. ForbiddenSysctls: []string{"net.ipv4.ip_default_ttl"},
  2657. SELinux: policyv1beta1.SELinuxStrategyOptions{
  2658. Rule: policyv1beta1.SELinuxStrategyRunAsAny,
  2659. },
  2660. RunAsUser: policyv1beta1.RunAsUserStrategyOptions{
  2661. Rule: policyv1beta1.RunAsUserStrategyRunAsAny,
  2662. },
  2663. FSGroup: policyv1beta1.FSGroupStrategyOptions{
  2664. Rule: policyv1beta1.FSGroupStrategyRunAsAny,
  2665. },
  2666. SupplementalGroups: policyv1beta1.SupplementalGroupsStrategyOptions{
  2667. Rule: policyv1beta1.SupplementalGroupsStrategyRunAsAny,
  2668. },
  2669. },
  2670. })
  2671. c := &describeClient{T: t, Namespace: "", Interface: fake}
  2672. d := PodSecurityPolicyDescriber{c}
  2673. out, err := d.Describe("", "mypsp", describe.DescriberSettings{})
  2674. if err != nil {
  2675. t.Fatalf("unexpected error: %v", err)
  2676. }
  2677. for _, item := range expected {
  2678. if matched, _ := regexp.MatchString(item, out); !matched {
  2679. t.Errorf("Expected to find %q in: %q", item, out)
  2680. }
  2681. }
  2682. }
  2683. func TestDescribeResourceQuota(t *testing.T) {
  2684. fake := fake.NewSimpleClientset(&corev1.ResourceQuota{
  2685. ObjectMeta: metav1.ObjectMeta{
  2686. Name: "bar",
  2687. Namespace: "foo",
  2688. },
  2689. Status: corev1.ResourceQuotaStatus{
  2690. Hard: corev1.ResourceList{
  2691. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("1"),
  2692. corev1.ResourceName(corev1.ResourceLimitsCPU): resource.MustParse("2"),
  2693. corev1.ResourceName(corev1.ResourceLimitsMemory): resource.MustParse("2G"),
  2694. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("1G"),
  2695. corev1.ResourceName(corev1.ResourceRequestsCPU): resource.MustParse("1"),
  2696. corev1.ResourceName(corev1.ResourceRequestsMemory): resource.MustParse("1G"),
  2697. },
  2698. Used: corev1.ResourceList{
  2699. corev1.ResourceName(corev1.ResourceCPU): resource.MustParse("0"),
  2700. corev1.ResourceName(corev1.ResourceLimitsCPU): resource.MustParse("0"),
  2701. corev1.ResourceName(corev1.ResourceLimitsMemory): resource.MustParse("0G"),
  2702. corev1.ResourceName(corev1.ResourceMemory): resource.MustParse("0G"),
  2703. corev1.ResourceName(corev1.ResourceRequestsCPU): resource.MustParse("0"),
  2704. corev1.ResourceName(corev1.ResourceRequestsMemory): resource.MustParse("0G"),
  2705. },
  2706. },
  2707. })
  2708. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  2709. d := ResourceQuotaDescriber{c}
  2710. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  2711. if err != nil {
  2712. t.Errorf("unexpected error: %v", err)
  2713. }
  2714. expectedOut := []string{"bar", "foo", "limits.cpu", "2", "limits.memory", "2G", "requests.cpu", "1", "requests.memory", "1G"}
  2715. for _, expected := range expectedOut {
  2716. if !strings.Contains(out, expected) {
  2717. t.Errorf("expected to find %q in output: %q", expected, out)
  2718. }
  2719. }
  2720. }
  2721. func TestDescribeNetworkPolicies(t *testing.T) {
  2722. expectedTime, err := time.Parse("2006-01-02 15:04:05 Z0700 MST", "2017-06-04 21:45:56 -0700 PDT")
  2723. if err != nil {
  2724. t.Errorf("unable to parse time %q error: %s", "2017-06-04 21:45:56 -0700 PDT", err)
  2725. }
  2726. expectedOut := `Name: network-policy-1
  2727. Namespace: default
  2728. Created on: 2017-06-04 21:45:56 -0700 PDT
  2729. Labels: <none>
  2730. Annotations: <none>
  2731. Spec:
  2732. PodSelector: foo in (bar1,bar2),foo2 notin (bar1,bar2),id1=app1,id2=app2
  2733. Allowing ingress traffic:
  2734. To Port: 80/TCP
  2735. To Port: 82/TCP
  2736. From:
  2737. NamespaceSelector: id=ns1,id2=ns2
  2738. PodSelector: id=pod1,id2=pod2
  2739. From:
  2740. PodSelector: id=app2,id2=app3
  2741. From:
  2742. NamespaceSelector: id=app2,id2=app3
  2743. From:
  2744. NamespaceSelector: foo in (bar1,bar2),id=app2,id2=app3
  2745. From:
  2746. IPBlock:
  2747. CIDR: 192.168.0.0/16
  2748. Except: 192.168.3.0/24, 192.168.4.0/24
  2749. ----------
  2750. To Port: <any> (traffic allowed to all ports)
  2751. From: <any> (traffic not restricted by source)
  2752. Allowing egress traffic:
  2753. To Port: 80/TCP
  2754. To Port: 82/TCP
  2755. To:
  2756. NamespaceSelector: id=ns1,id2=ns2
  2757. PodSelector: id=pod1,id2=pod2
  2758. To:
  2759. PodSelector: id=app2,id2=app3
  2760. To:
  2761. NamespaceSelector: id=app2,id2=app3
  2762. To:
  2763. NamespaceSelector: foo in (bar1,bar2),id=app2,id2=app3
  2764. To:
  2765. IPBlock:
  2766. CIDR: 192.168.0.0/16
  2767. Except: 192.168.3.0/24, 192.168.4.0/24
  2768. ----------
  2769. To Port: <any> (traffic allowed to all ports)
  2770. To: <any> (traffic not restricted by source)
  2771. Policy Types: Ingress, Egress
  2772. `
  2773. port80 := intstr.FromInt(80)
  2774. port82 := intstr.FromInt(82)
  2775. protoTCP := corev1.ProtocolTCP
  2776. versionedFake := fake.NewSimpleClientset(&networkingv1.NetworkPolicy{
  2777. ObjectMeta: metav1.ObjectMeta{
  2778. Name: "network-policy-1",
  2779. Namespace: "default",
  2780. CreationTimestamp: metav1.NewTime(expectedTime),
  2781. },
  2782. Spec: networkingv1.NetworkPolicySpec{
  2783. PodSelector: metav1.LabelSelector{
  2784. MatchLabels: map[string]string{
  2785. "id1": "app1",
  2786. "id2": "app2",
  2787. },
  2788. MatchExpressions: []metav1.LabelSelectorRequirement{
  2789. {Key: "foo", Operator: "In", Values: []string{"bar1", "bar2"}},
  2790. {Key: "foo2", Operator: "NotIn", Values: []string{"bar1", "bar2"}},
  2791. },
  2792. },
  2793. Ingress: []networkingv1.NetworkPolicyIngressRule{
  2794. {
  2795. Ports: []networkingv1.NetworkPolicyPort{
  2796. {Port: &port80},
  2797. {Port: &port82, Protocol: &protoTCP},
  2798. },
  2799. From: []networkingv1.NetworkPolicyPeer{
  2800. {
  2801. PodSelector: &metav1.LabelSelector{
  2802. MatchLabels: map[string]string{
  2803. "id": "pod1",
  2804. "id2": "pod2",
  2805. },
  2806. },
  2807. NamespaceSelector: &metav1.LabelSelector{
  2808. MatchLabels: map[string]string{
  2809. "id": "ns1",
  2810. "id2": "ns2",
  2811. },
  2812. },
  2813. },
  2814. {
  2815. PodSelector: &metav1.LabelSelector{
  2816. MatchLabels: map[string]string{
  2817. "id": "app2",
  2818. "id2": "app3",
  2819. },
  2820. },
  2821. },
  2822. {
  2823. NamespaceSelector: &metav1.LabelSelector{
  2824. MatchLabels: map[string]string{
  2825. "id": "app2",
  2826. "id2": "app3",
  2827. },
  2828. },
  2829. },
  2830. {
  2831. NamespaceSelector: &metav1.LabelSelector{
  2832. MatchLabels: map[string]string{
  2833. "id": "app2",
  2834. "id2": "app3",
  2835. },
  2836. MatchExpressions: []metav1.LabelSelectorRequirement{
  2837. {Key: "foo", Operator: "In", Values: []string{"bar1", "bar2"}},
  2838. },
  2839. },
  2840. },
  2841. {
  2842. IPBlock: &networkingv1.IPBlock{
  2843. CIDR: "192.168.0.0/16",
  2844. Except: []string{"192.168.3.0/24", "192.168.4.0/24"},
  2845. },
  2846. },
  2847. },
  2848. },
  2849. {},
  2850. },
  2851. Egress: []networkingv1.NetworkPolicyEgressRule{
  2852. {
  2853. Ports: []networkingv1.NetworkPolicyPort{
  2854. {Port: &port80},
  2855. {Port: &port82, Protocol: &protoTCP},
  2856. },
  2857. To: []networkingv1.NetworkPolicyPeer{
  2858. {
  2859. PodSelector: &metav1.LabelSelector{
  2860. MatchLabels: map[string]string{
  2861. "id": "pod1",
  2862. "id2": "pod2",
  2863. },
  2864. },
  2865. NamespaceSelector: &metav1.LabelSelector{
  2866. MatchLabels: map[string]string{
  2867. "id": "ns1",
  2868. "id2": "ns2",
  2869. },
  2870. },
  2871. },
  2872. {
  2873. PodSelector: &metav1.LabelSelector{
  2874. MatchLabels: map[string]string{
  2875. "id": "app2",
  2876. "id2": "app3",
  2877. },
  2878. },
  2879. },
  2880. {
  2881. NamespaceSelector: &metav1.LabelSelector{
  2882. MatchLabels: map[string]string{
  2883. "id": "app2",
  2884. "id2": "app3",
  2885. },
  2886. },
  2887. },
  2888. {
  2889. NamespaceSelector: &metav1.LabelSelector{
  2890. MatchLabels: map[string]string{
  2891. "id": "app2",
  2892. "id2": "app3",
  2893. },
  2894. MatchExpressions: []metav1.LabelSelectorRequirement{
  2895. {Key: "foo", Operator: "In", Values: []string{"bar1", "bar2"}},
  2896. },
  2897. },
  2898. },
  2899. {
  2900. IPBlock: &networkingv1.IPBlock{
  2901. CIDR: "192.168.0.0/16",
  2902. Except: []string{"192.168.3.0/24", "192.168.4.0/24"},
  2903. },
  2904. },
  2905. },
  2906. },
  2907. {},
  2908. },
  2909. PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress, networkingv1.PolicyTypeEgress},
  2910. },
  2911. })
  2912. d := NetworkPolicyDescriber{versionedFake}
  2913. out, err := d.Describe("", "network-policy-1", describe.DescriberSettings{})
  2914. if err != nil {
  2915. t.Errorf("unexpected error: %s", err)
  2916. }
  2917. if out != expectedOut {
  2918. t.Errorf("want:\n%s\ngot:\n%s", expectedOut, out)
  2919. }
  2920. }
  2921. func TestDescribeServiceAccount(t *testing.T) {
  2922. fake := fake.NewSimpleClientset(&corev1.ServiceAccount{
  2923. ObjectMeta: metav1.ObjectMeta{
  2924. Name: "bar",
  2925. Namespace: "foo",
  2926. },
  2927. Secrets: []corev1.ObjectReference{
  2928. {
  2929. Name: "test-objectref",
  2930. },
  2931. },
  2932. ImagePullSecrets: []corev1.LocalObjectReference{
  2933. {
  2934. Name: "test-local-ref",
  2935. },
  2936. },
  2937. })
  2938. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  2939. d := ServiceAccountDescriber{c}
  2940. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  2941. if err != nil {
  2942. t.Errorf("unexpected error: %v", err)
  2943. }
  2944. expectedOut := `Name: bar
  2945. Namespace: foo
  2946. Labels: <none>
  2947. Annotations: <none>
  2948. Image pull secrets: test-local-ref (not found)
  2949. Mountable secrets: test-objectref (not found)
  2950. Tokens: <none>
  2951. Events: <none>` + "\n"
  2952. if out != expectedOut {
  2953. t.Errorf("expected : %q\n but got output:\n %q", expectedOut, out)
  2954. }
  2955. }
  2956. func TestDescribeNode(t *testing.T) {
  2957. fake := fake.NewSimpleClientset(&corev1.Node{
  2958. ObjectMeta: metav1.ObjectMeta{
  2959. Name: "bar",
  2960. Namespace: "foo",
  2961. },
  2962. Spec: corev1.NodeSpec{
  2963. Unschedulable: true,
  2964. },
  2965. })
  2966. c := &describeClient{T: t, Namespace: "foo", Interface: fake}
  2967. d := NodeDescriber{c}
  2968. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  2969. if err != nil {
  2970. t.Errorf("unexpected error: %v", err)
  2971. }
  2972. expectedOut := []string{"Unschedulable", "true"}
  2973. for _, expected := range expectedOut {
  2974. if !strings.Contains(out, expected) {
  2975. t.Errorf("expected to find %q in output: %q", expected, out)
  2976. }
  2977. }
  2978. }
  2979. func TestDescribeStatefulSet(t *testing.T) {
  2980. var partition int32 = 2
  2981. var replicas int32 = 1
  2982. fake := fake.NewSimpleClientset(&appsv1.StatefulSet{
  2983. ObjectMeta: metav1.ObjectMeta{
  2984. Name: "bar",
  2985. Namespace: "foo",
  2986. },
  2987. Spec: appsv1.StatefulSetSpec{
  2988. Replicas: &replicas,
  2989. Selector: &metav1.LabelSelector{},
  2990. Template: corev1.PodTemplateSpec{
  2991. Spec: corev1.PodSpec{
  2992. Containers: []corev1.Container{
  2993. {Image: "mytest-image:latest"},
  2994. },
  2995. },
  2996. },
  2997. UpdateStrategy: appsv1.StatefulSetUpdateStrategy{
  2998. Type: appsv1.RollingUpdateStatefulSetStrategyType,
  2999. RollingUpdate: &appsv1.RollingUpdateStatefulSetStrategy{
  3000. Partition: &partition,
  3001. },
  3002. },
  3003. },
  3004. })
  3005. d := StatefulSetDescriber{fake}
  3006. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: true})
  3007. if err != nil {
  3008. t.Errorf("unexpected error: %v", err)
  3009. }
  3010. expectedOutputs := []string{
  3011. "bar", "foo", "Containers:", "mytest-image:latest", "Update Strategy", "RollingUpdate", "Partition",
  3012. }
  3013. for _, o := range expectedOutputs {
  3014. if !strings.Contains(out, o) {
  3015. t.Errorf("unexpected out: %s", out)
  3016. break
  3017. }
  3018. }
  3019. }
  3020. func TestControllerRef(t *testing.T) {
  3021. var replicas int32 = 1
  3022. f := fake.NewSimpleClientset(
  3023. &corev1.ReplicationController{
  3024. ObjectMeta: metav1.ObjectMeta{
  3025. Name: "bar",
  3026. Namespace: "foo",
  3027. UID: "123456",
  3028. },
  3029. TypeMeta: metav1.TypeMeta{
  3030. Kind: "ReplicationController",
  3031. },
  3032. Spec: corev1.ReplicationControllerSpec{
  3033. Replicas: &replicas,
  3034. Selector: map[string]string{"abc": "xyz"},
  3035. Template: &corev1.PodTemplateSpec{
  3036. Spec: corev1.PodSpec{
  3037. Containers: []corev1.Container{
  3038. {Image: "mytest-image:latest"},
  3039. },
  3040. },
  3041. },
  3042. },
  3043. },
  3044. &corev1.Pod{
  3045. ObjectMeta: metav1.ObjectMeta{
  3046. Name: "barpod",
  3047. Namespace: "foo",
  3048. Labels: map[string]string{"abc": "xyz"},
  3049. OwnerReferences: []metav1.OwnerReference{{Name: "bar", UID: "123456", Controller: utilpointer.BoolPtr(true)}},
  3050. },
  3051. TypeMeta: metav1.TypeMeta{
  3052. Kind: "Pod",
  3053. },
  3054. Spec: corev1.PodSpec{
  3055. Containers: []corev1.Container{
  3056. {Image: "mytest-image:latest"},
  3057. },
  3058. },
  3059. Status: corev1.PodStatus{
  3060. Phase: corev1.PodRunning,
  3061. },
  3062. },
  3063. &corev1.Pod{
  3064. ObjectMeta: metav1.ObjectMeta{
  3065. Name: "orphan",
  3066. Namespace: "foo",
  3067. Labels: map[string]string{"abc": "xyz"},
  3068. },
  3069. TypeMeta: metav1.TypeMeta{
  3070. Kind: "Pod",
  3071. },
  3072. Spec: corev1.PodSpec{
  3073. Containers: []corev1.Container{
  3074. {Image: "mytest-image:latest"},
  3075. },
  3076. },
  3077. Status: corev1.PodStatus{
  3078. Phase: corev1.PodRunning,
  3079. },
  3080. },
  3081. &corev1.Pod{
  3082. ObjectMeta: metav1.ObjectMeta{
  3083. Name: "buzpod",
  3084. Namespace: "foo",
  3085. Labels: map[string]string{"abc": "xyz"},
  3086. OwnerReferences: []metav1.OwnerReference{{Name: "buz", UID: "654321", Controller: utilpointer.BoolPtr(true)}},
  3087. },
  3088. TypeMeta: metav1.TypeMeta{
  3089. Kind: "Pod",
  3090. },
  3091. Spec: corev1.PodSpec{
  3092. Containers: []corev1.Container{
  3093. {Image: "mytest-image:latest"},
  3094. },
  3095. },
  3096. Status: corev1.PodStatus{
  3097. Phase: corev1.PodRunning,
  3098. },
  3099. })
  3100. d := ReplicationControllerDescriber{f}
  3101. out, err := d.Describe("foo", "bar", describe.DescriberSettings{ShowEvents: false})
  3102. if err != nil {
  3103. t.Errorf("unexpected error: %v", err)
  3104. }
  3105. if !strings.Contains(out, "1 Running") {
  3106. t.Errorf("unexpected out: %s", out)
  3107. }
  3108. }