Best Testkube code snippet using client.IsPodReady
readiness_test.go
Source:readiness_test.go
1package main2import (3 "bytes"4 "context"5 "encoding/json"6 "io"7 "os"8 "testing"9 "time"10 "github.com/mongodb/mongodb-kubernetes-operator/cmd/readiness/testdata"11 "github.com/mongodb/mongodb-kubernetes-operator/pkg/readiness/config"12 "github.com/mongodb/mongodb-kubernetes-operator/pkg/readiness/health"13 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"14 "k8s.io/client-go/kubernetes/fake"15 "github.com/stretchr/testify/assert"16)17// TestDeadlockDetection verifies that if the agent is stuck in "WaitAllRsMembersUp" phase (started > 15 seconds ago)18// then the function returns "ready"19func TestDeadlockDetection(t *testing.T) {20 ready, err := isPodReady(testConfig("testdata/health-status-deadlocked.json"))21 assert.True(t, ready)22 assert.NoError(t, err)23}24// TestNoDeadlock verifies that if the agent has started (but not finished) "WaitRsInit" and then there is another25// started phase ("WaitFeatureCompatibilityVersionCorrect") then no deadlock is found as the latter is considered to26// be the "current" step27func TestNoDeadlock(t *testing.T) {28 health, err := parseHealthStatus(testConfig("testdata/health-status-no-deadlock.json").HealthStatusReader)29 assert.NoError(t, err)30 stepStatus := findCurrentStep(health.ProcessPlans)31 assert.Equal(t, "WaitFeatureCompatibilityVersionCorrect", stepStatus.Step)32 ready, err := isPodReady(testConfig("testdata/health-status-no-deadlock.json"))33 assert.False(t, ready)34 assert.NoError(t, err)35}36// TestDeadlockDetection verifies that if the agent is in "WaitAllRsMembersUp" phase but started < 15 seconds ago37// then the function returns "not ready". To achieve this "started" is put into some long future.38// Note, that the status file is artificial: it has two plans (the first one is complete and has no moves) to make sure39// the readiness logic takes only the last plan for consideration40func TestNotReadyWaitingForRsReady(t *testing.T) {41 ready, err := isPodReady(testConfig("testdata/health-status-pending.json"))42 assert.False(t, ready)43 assert.NoError(t, err)44}45// TestNotReadyHealthFileHasNoPlans verifies that the readiness script doesn't panic if the health file has unexpected46// data (there are no plans at all)47func TestNotReadyHealthFileHasNoPlans(t *testing.T) {48 ready, err := isPodReady(testConfig("testdata/health-status-no-plans.json"))49 assert.False(t, ready)50 assert.NoError(t, err)51}52// TestNotReadyHealthFileHasNoProcesses verifies that the readiness script doesn't panic if the health file has unexpected53// data (there are no processes at all)54func TestNotReadyHealthFileHasNoProcesses(t *testing.T) {55 ready, err := isPodReady(testConfig("testdata/health-status-no-processes.json"))56 assert.False(t, ready)57 assert.NoError(t, err)58}59func TestNotReadyMongodIsDown(t *testing.T) {60 t.Run("Mongod is down for 90 seconds", func(t *testing.T) {61 ready, err := isPodReady(testConfigWithMongoUp("testdata/health-status-ok.json", time.Second*90))62 assert.False(t, ready)63 assert.NoError(t, err)64 })65 t.Run("Mongod is down for 1 hour", func(t *testing.T) {66 ready, err := isPodReady(testConfigWithMongoUp("testdata/health-status-ok.json", time.Hour*1))67 assert.False(t, ready)68 assert.NoError(t, err)69 })70 t.Run("Mongod is down for 2 days", func(t *testing.T) {71 ready, err := isPodReady(testConfigWithMongoUp("testdata/health-status-ok.json", time.Hour*48))72 assert.False(t, ready)73 assert.NoError(t, err)74 })75}76func TestReadyMongodIsUp(t *testing.T) {77 t.Run("Mongod is down for 30 seconds", func(t *testing.T) {78 ready, err := isPodReady(testConfigWithMongoUp("testdata/health-status-ok.json", time.Second*30))79 assert.True(t, ready)80 assert.NoError(t, err)81 })82 t.Run("Mongod is down for 1 second", func(t *testing.T) {83 ready, err := isPodReady(testConfigWithMongoUp("testdata/health-status-ok.json", time.Second*1))84 assert.True(t, ready)85 assert.NoError(t, err)86 })87}88// TestReady verifies that the probe reports "ready" despite "WaitRsInit" stage reporting as not reached89// (this is some bug in Automation Agent which we can work with)90func TestReady(t *testing.T) {91 ready, err := isPodReady(testConfig("testdata/health-status-ok.json"))92 assert.True(t, ready)93 assert.NoError(t, err)94}95// TestNoDeadlockForDownloadProcess verifies that the steps not listed as "riskySteps" (like "download") are not96// considered as stuck97func TestNoDeadlockForDownloadProcess(t *testing.T) {98 before := time.Now().Add(time.Duration(-30) * time.Second)99 downloadStatus := &health.StepStatus{100 Step: "Download",101 Started: &before,102 Completed: nil,103 Result: "",104 }105 assert.False(t, isDeadlocked(downloadStatus))106}107// TestNoDeadlockForImmediateWaitRs verifies the "WaitRsInit" step is not marked as deadlocked if108// it was started < 15 seconds ago109func TestNoDeadlockForImmediateWaitRs(t *testing.T) {110 before := time.Now().Add(time.Duration(-10) * time.Second)111 downloadStatus := &health.StepStatus{112 Step: "WaitRsInit",113 Started: &before,114 Completed: nil,115 Result: "Wait",116 }117 assert.False(t, isDeadlocked(downloadStatus))118}119// TestHeadlessAgentHasntReachedGoal verifies that the probe reports "false" if the config version is higher than the120// last achieved version of the Agent121// Note that the edge case is checked here: the health-status-ok.json has the "WaitRsInit" phase stuck in the last plan122// (as Agent doesn't marks all the step statuses finished when it reaches the goal) but this doesn't affect the result123// as the whole plan is complete already124func TestHeadlessAgentHasntReachedGoal(t *testing.T) {125 _ = os.Setenv(headlessAgent, "true")126 c := testConfig("testdata/health-status-ok.json")127 c.ClientSet = fake.NewSimpleClientset(testdata.TestPod(c.Namespace, c.Hostname), testdata.TestSecret(c.Namespace, c.AutomationConfigSecretName, 6))128 ready, err := isPodReady(c)129 assert.False(t, ready)130 assert.NoError(t, err)131 thePod, _ := c.ClientSet.CoreV1().Pods(c.Namespace).Get(context.TODO(), c.Hostname, metav1.GetOptions{})132 assert.Equal(t, map[string]string{"agent.mongodb.com/version": "5"}, thePod.Annotations)133 os.Unsetenv(headlessAgent)134}135// TestHeadlessAgentReachedGoal verifies that the probe reports "true" if the config version is equal to the136// last achieved version of the Agent137func TestHeadlessAgentReachedGoal(t *testing.T) {138 _ = os.Setenv(headlessAgent, "true")139 c := testConfig("testdata/health-status-ok.json")140 c.ClientSet = fake.NewSimpleClientset(testdata.TestPod(c.Namespace, c.Hostname), testdata.TestSecret(c.Namespace, c.AutomationConfigSecretName, 5))141 ready, err := isPodReady(c)142 assert.True(t, ready)143 assert.NoError(t, err)144 thePod, _ := c.ClientSet.CoreV1().Pods(c.Namespace).Get(context.TODO(), c.Hostname, metav1.GetOptions{})145 assert.Equal(t, map[string]string{"agent.mongodb.com/version": "5"}, thePod.Annotations)146 os.Unsetenv(headlessAgent)147}148func TestPodReadiness(t *testing.T) {149 t.Run("Pod readiness is correctly checked when no ReplicationStatus is present on the file ", func(t *testing.T) {150 ready, err := isPodReady(testConfig("testdata/health-status-no-replication.json"))151 assert.True(t, ready)152 assert.NoError(t, err)153 })154 t.Run("MongoDB replication state is reported by agents", func(t *testing.T) {155 ready, err := isPodReady(testConfig("testdata/health-status-ok-no-replica-status.json"))156 assert.True(t, ready)157 assert.NoError(t, err)158 })159 t.Run("If replication state is not PRIMARY or SECONDARY, Pod is not ready", func(t *testing.T) {160 ready, err := isPodReady(testConfig("testdata/health-status-not-readable-state.json"))161 assert.False(t, ready)162 assert.NoError(t, err)163 })164}165func testConfig(healthFilePath string) config.Config {166 return testConfigWithMongoUp(healthFilePath, 15*time.Second)167}168func testConfigWithMongoUp(healthFilePath string, timeSinceMongoLastUp time.Duration) config.Config {169 file, err := os.Open(healthFilePath)170 if err != nil {171 panic(err)172 }173 defer file.Close()174 status, err := parseHealthStatus(file)175 if err != nil {176 panic(err)177 }178 for key, processHealth := range status.Healthiness {179 processHealth.LastMongoUpTime = time.Now().Add(-timeSinceMongoLastUp).Unix()180 // Need to reassign the object back to map as 'processHealth' is a copy of the struct181 status.Healthiness[key] = processHealth182 }183 return config.Config{184 HealthStatusReader: NewTestHealthStatusReader(status),185 Namespace: "test-ns",186 AutomationConfigSecretName: "test-mongodb-automation-config",187 Hostname: "test-mongodb-0",188 }189}190func NewTestHealthStatusReader(status health.Status) io.Reader {191 data, err := json.Marshal(status)192 if err != nil {193 panic(err)194 }195 return bytes.NewReader(data)196}...
portforwarder.go
Source:portforwarder.go
1// Copyright © 2019 Banzai Cloud2//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 at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package k8sutil15import (16 "context"17 "fmt"18 v1 "k8s.io/api/core/v1"19 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"20 "k8s.io/apimachinery/pkg/labels"21 "k8s.io/client-go/kubernetes"22 corev1 "k8s.io/client-go/kubernetes/typed/core/v1"23 "k8s.io/client-go/rest"24 "github.com/banzaicloud/pipeline/pkg/helm/kube"25)26type TunnelDestinationNotFoundError error27// New creates a new and initialized tunnel.28func NewKubeTunnel(namespace string, client kubernetes.Interface, config *rest.Config, selector labels.Selector, internalPort int) (*kube.Tunnel, error) {29 podName, err := GetPodName(client.CoreV1(), namespace, selector)30 if err != nil {31 return nil, err32 }33 t := kube.NewTunnel(client.CoreV1().RESTClient(), config, namespace, podName, internalPort)34 return t, t.ForwardPort()35}36// GetPodName fetches the name of a pod running in the given namespace.37func GetPodName(client corev1.PodsGetter, namespace string, selector labels.Selector) (string, error) {38 pod, err := getFirstRunningPod(client, namespace, selector)39 if err != nil {40 return "", err41 }42 return pod.ObjectMeta.GetName(), nil43}44func getFirstRunningPod(client corev1.PodsGetter, namespace string, selector labels.Selector) (*v1.Pod, error) {45 options := metav1.ListOptions{LabelSelector: selector.String()}46 pods, err := client.Pods(namespace).List(context.Background(), options)47 if err != nil {48 return nil, err49 }50 if len(pods.Items) < 1 {51 return nil, fmt.Errorf("could not find pod with labels: %s", selector.String())52 }53 for _, p := range pods.Items {54 if isPodReady(&p) {55 return &p, nil56 }57 }58 return nil, fmt.Errorf("could not find a ready pod")59}60// isPodReady returns true if a pod is ready; false otherwise.61func isPodReady(pod *v1.Pod) bool {62 return isPodReadyConditionTrue(pod.Status)63}64// isPodReadyConditionTrue returns true if a pod is ready; false otherwise.65func isPodReadyConditionTrue(status v1.PodStatus) bool {66 condition := getPodReadyCondition(status)67 return condition != nil && condition.Status == v1.ConditionTrue68}69// getPodReadyCondition extracts the pod ready condition from the given status and returns that.70// Returns nil if the condition is not present.71func getPodReadyCondition(status v1.PodStatus) *v1.PodCondition {72 _, condition := getPodCondition(&status, v1.PodReady)73 return condition74}75// getPodCondition extracts the provided condition from the given status and returns that.76// Returns nil and -1 if the condition is not present, and the index of the located condition.77func getPodCondition(status *v1.PodStatus, conditionType v1.PodConditionType) (int, *v1.PodCondition) {78 if status == nil {79 return -1, nil80 }81 for i := range status.Conditions {82 if status.Conditions[i].Type == conditionType {83 return i, &status.Conditions[i]84 }85 }86 return -1, nil87}...
IsPodReady
Using AI Code Generation
1import (2func main() {3 if home := homedir.HomeDir(); home != "" {4 kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")5 } else {6 kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")7 }8 flag.Parse()9 config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)10 if err != nil {11 panic(err.Error())12 }13 clientset, err := kubernetes.NewForConfig(config)14 if err != nil {15 panic(err.Error())16 }17 podReady := clientset.IsPodReady(podName, namespace)18 fmt.Println(podReady)19}
IsPodReady
Using AI Code Generation
1import (2func main() {3 if home := homedir.HomeDir(); home != "" {4 kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")5 } else {6 kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")7 }8 flag.Parse()9 config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)10 if err != nil {11 panic(err.Error())12 }13 clientset, err := kubernetes.NewForConfig(config)14 if err != nil {15 panic(err.Error())16 }17 pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})18 if err != nil {19 panic(err.Error())20 }21 fmt.Printf("There are %d pods in the cluster22", len(pods.Items))23 for _, pod := range pods.Items {24 fmt.Printf("Pod Name: %s25 fmt.Printf("Pod Namespace: %s26 fmt.Printf("Pod Ready Status: %t27", clientset.IsPodReady(&pod))28 }29}
IsPodReady
Using AI Code Generation
1import (2func main() {3 home := os.Getenv("HOME")4 configPath := filepath.Join(home, ".kube", "config")5 config, err := clientcmd.BuildConfigFromFlags("", configPath)6 if err != nil {7 log.Fatal(err)8 }9 clientset, err := kubernetes.NewForConfig(config)10 if err != nil {11 log.Fatal(err)12 }13 selector := labels.NewSelector()14 podList, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{LabelSelector: selector.String()})15 if err != nil {16 log.Fatal(err)17 }18 for _, pod := range podList.Items {19 if IsPodReady(&pod) {20 fmt.Println("Pod is ready")21 } else {22 fmt.Println("Pod is not ready")23 }24 }25}26func IsPodReady(pod *v1.Pod) bool {
IsPodReady
Using AI Code Generation
1func main() {2 pod := &v1.Pod{}3 pod.Status.Conditions = []v1.PodCondition{4 {Type: v1.PodReady, Status: v1.ConditionTrue},5 }6 fmt.Println(podutils.IsPodReady(pod))7}
IsPodReady
Using AI Code Generation
1func main() {2 client := client.NewClient()3 pod := client.GetPod("nginx")4 if client.IsPodReady(pod) {5 fmt.Println("Pod is ready")6 } else {7 fmt.Println("Pod is not ready")8 }9}10func main() {11 client := client.NewClient()12 pod := client.GetPod("nginx")13 if client.IsPodReady(pod) {14 fmt.Println("Pod is ready")15 } else {16 fmt.Println("Pod is not ready")17 }18}19func main() {20 client := client.NewClient()21 pod := client.GetPod("nginx")22 if client.IsPodReady(pod) {23 fmt.Println("Pod is ready")24 } else {25 fmt.Println("Pod is not ready")26 }27}28func main() {29 client := client.NewClient()30 pod := client.GetPod("nginx")31 if client.IsPodReady(pod) {32 fmt.Println("Pod is ready")33 } else {34 fmt.Println("Pod is not ready")35 }36}37func main() {38 client := client.NewClient()39 pod := client.GetPod("nginx")40 if client.IsPodReady(pod) {41 fmt.Println("Pod is ready")42 } else {43 fmt.Println("Pod is not ready")44 }45}46func main() {47 client := client.NewClient()48 pod := client.GetPod("nginx")49 if client.IsPodReady(pod) {50 fmt.Println("Pod is ready")51 } else {52 fmt.Println("Pod is not ready")53 }54}55func main() {56 client := client.NewClient()57 pod := client.GetPod("nginx")58 if client.IsPodReady(pod) {59 fmt.Println("Pod is ready")60 } else {61 fmt.Println("Pod is not ready")62 }63}
IsPodReady
Using AI Code Generation
1import (2func main() {3 config, err := rest.InClusterConfig()4 if err != nil {5 panic(err.Error())6 }7 clientset, err := kubernetes.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 pod, err := clientset.CoreV1().Pods("default").Get("myapp", metav1.GetOptions{})12 if err != nil {13 panic(err.Error())14 }15 client := myk8sclient.NewClient(clientset)16 if client.IsPodReady(pod) {17 fmt.Println("Pod is ready")18 } else {19 fmt.Println("Pod is not ready")20 }21 time.Sleep(10 * time.Second)22}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!