golang.org/x/build@v0.0.0-20240506185731-218518f32b70/kubernetes/client_test.go (about) 1 // Copyright 2022 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package kubernetes_test 6 7 import ( 8 "context" 9 "encoding/json" 10 "fmt" 11 "net/http" 12 "net/http/httptest" 13 "testing" 14 15 "golang.org/x/build/kubernetes" 16 "golang.org/x/build/kubernetes/api" 17 ) 18 19 type handlers []func(w http.ResponseWriter, r *http.Request) error 20 21 func newTestPod() *api.Pod { 22 return &api.Pod{ 23 TypeMeta: api.TypeMeta{ 24 APIVersion: "v1", 25 Kind: "Pod", 26 }, 27 ObjectMeta: api.ObjectMeta{ 28 Name: "test-pod", 29 }, 30 Spec: api.PodSpec{ 31 Containers: []api.Container{ 32 { 33 Name: "test-container", 34 Image: "test-image:latest", 35 }, 36 }, 37 }, 38 } 39 } 40 41 func (hs *handlers) ServeHTTP(w http.ResponseWriter, r *http.Request) { 42 if len(*hs) == 0 { 43 w.WriteHeader(http.StatusInternalServerError) 44 fmt.Fprintf(w, "unexpected request: %v", r) 45 return 46 } 47 h := (*hs)[0] 48 *hs = (*hs)[1:] 49 if err := h(w, r); err != nil { 50 w.WriteHeader(http.StatusInternalServerError) 51 fmt.Fprintf(w, "unexpected error: %v", err) 52 return 53 } 54 } 55 56 func TestRunPod(t *testing.T) { 57 hs := handlers{ 58 func(w http.ResponseWriter, r *http.Request) error { 59 if r.Method != http.MethodPost { 60 return fmt.Errorf("expected %q, got %q", http.MethodPost, r.Method) 61 62 } 63 w.WriteHeader(http.StatusCreated) 64 json.NewEncoder(w).Encode(newTestPod()) 65 return nil 66 }, 67 func(w http.ResponseWriter, r *http.Request) error { 68 if r.Method != http.MethodGet { 69 return fmt.Errorf("expected %q, got %q", http.MethodGet, r.Method) 70 } 71 w.WriteHeader(http.StatusOK) 72 readyPod := newTestPod() 73 readyPod.Status.Phase = api.PodRunning 74 json.NewEncoder(w).Encode(readyPod) 75 return nil 76 }, 77 } 78 s := httptest.NewServer(&hs) 79 defer s.Close() 80 81 c, err := kubernetes.NewClient(s.URL, "default", http.DefaultClient) 82 if err != nil { 83 t.Fatalf("NewClient: %v", err) 84 } 85 ps, err := c.RunLongLivedPod(context.Background(), newTestPod()) 86 if err != nil { 87 t.Fatalf("RunLongLivePod: %v", err) 88 } 89 if ps.Phase != api.PodRunning { 90 t.Fatalf("Pod phase = %q; want %q", ps.Phase, api.PodRunning) 91 } 92 if len(hs) != 0 { 93 t.Fatalf("failed to process all expected requests: %d left", len(hs)) 94 } 95 }