github.com/vmware/govmomi@v0.51.0/vapi/rest/client_test.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package rest_test 6 7 import ( 8 "bytes" 9 "context" 10 "io" 11 "net/http" 12 "strings" 13 "testing" 14 15 "github.com/vmware/govmomi/simulator" 16 "github.com/vmware/govmomi/vapi/internal" 17 "github.com/vmware/govmomi/vapi/rest" 18 _ "github.com/vmware/govmomi/vapi/simulator" 19 "github.com/vmware/govmomi/vim25" 20 ) 21 22 func TestSession(t *testing.T) { 23 simulator.Test(func(ctx context.Context, vc *vim25.Client) { 24 c := rest.NewClient(vc) 25 26 session, err := c.Session(ctx) 27 if err != nil { 28 t.Fatal(err) 29 } 30 31 if session != nil { 32 t.Fatal("expected nil session") 33 } 34 35 err = c.Login(ctx, simulator.DefaultLogin) 36 if err != nil { 37 t.Fatal(err) 38 } 39 40 session, err = c.Session(ctx) 41 if err != nil { 42 t.Fatal(err) 43 } 44 45 if session == nil { 46 t.Fatal("expected non-nil session") 47 } 48 49 path := c.Resource("/xpto/bla") 50 err = c.Do(ctx, path.Request(http.MethodGet), nil) 51 if !rest.IsStatusError(err, http.StatusNotFound) { 52 t.Fatal("expecting error to be 'StatusNotFound'", err) 53 } 54 }) 55 } 56 57 func TestWithHeaders(t *testing.T) { 58 simulator.Test(func(ctx context.Context, vc *vim25.Client) { 59 c := rest.NewClient(vc) 60 if err := c.Login(ctx, simulator.DefaultLogin); err != nil { 61 t.Fatal(err) 62 } 63 64 // Assign the headers. 65 ctx = c.WithHeader(ctx, http.Header{ 66 "client-token": []string{"unique-token"}, 67 "pid": []string{"2", "3", "4"}, 68 }) 69 70 req, err := http.NewRequest( 71 http.MethodPost, 72 c.Resource(internal.DebugEcho).String(), 73 strings.NewReader("Hello, world.")) 74 if err != nil { 75 t.Fatal(err) 76 } 77 78 // Send a rest.RawResponse into the decoder to capture the raw 79 // response data. 80 var res rest.RawResponse 81 if err := c.Do(ctx, req, &res); err != nil { 82 t.Fatal(err) 83 } 84 85 // Read the raw response. 86 data, err := io.ReadAll(&res.Buffer) 87 if err != nil { 88 t.Fatal(err) 89 } 90 91 // Assert all of the request headers were echoed back to the client. 92 if !bytes.Contains(data, []byte("Client-Token: unique-token")) { 93 t.Fatal("missing Client-Token: unique-token") 94 } 95 if !bytes.Contains(data, []byte("Pid: 2")) { 96 t.Fatal("missing Pid: 2") 97 } 98 if !bytes.Contains(data, []byte("Pid: 3")) { 99 t.Fatal("missing Pid: 3") 100 } 101 if !bytes.Contains(data, []byte("Pid: 4")) { 102 t.Fatal("missing Pid: 4") 103 } 104 }) 105 }