1package compute_test 2 3import ( 4 "context" 5 "io/ioutil" 6 "net/http" 7 "path" 8 "strings" 9 "testing" 10 11 "github.com/joyent/triton-go/compute" 12 "github.com/joyent/triton-go/testutils" 13) 14 15// MockComputeClient is used to mock out compute.ComputeClient for all tests 16// under the triton-go/compute package 17func MockComputeClient() *compute.ComputeClient { 18 return &compute.ComputeClient{ 19 Client: testutils.NewMockClient(testutils.MockClientInput{ 20 AccountName: accountURL, 21 }), 22 } 23} 24 25const ( 26 testHeaderName = "X-Test-Header" 27 testHeaderVal1 = "number one" 28 testHeaderVal2 = "number two" 29) 30 31func TestSetHeader(t *testing.T) { 32 computeClient := MockComputeClient() 33 34 do := func(ctx context.Context, cc *compute.ComputeClient) error { 35 defer testutils.DeactivateClient() 36 37 header := &http.Header{} 38 header.Add(testHeaderName, testHeaderVal1) 39 header.Add(testHeaderName, testHeaderVal2) 40 cc.SetHeader(header) 41 42 _, err := cc.Datacenters().List(ctx, &compute.ListDataCentersInput{}) 43 44 return err 45 } 46 47 t.Run("override header", func(t *testing.T) { 48 testutils.RegisterResponder("GET", path.Join("/", accountURL, "datacenters"), overrideHeaderTest(t)) 49 50 err := do(context.Background(), computeClient) 51 if err != nil { 52 t.Error(err) 53 } 54 }) 55} 56 57func overrideHeaderTest(t *testing.T) func(req *http.Request) (*http.Response, error) { 58 return func(req *http.Request) (*http.Response, error) { 59 if req.Header.Get(testHeaderName) == "" { 60 t.Errorf("Request header should contain '%s'", testHeaderName) 61 } 62 testHeader := strings.Join(req.Header[testHeaderName], ",") 63 if !strings.Contains(testHeader, testHeaderVal1) { 64 t.Errorf("Request header should contain '%s': got '%s'", testHeaderVal1, testHeader) 65 } 66 if !strings.Contains(testHeader, testHeaderVal2) { 67 t.Errorf("Request header should contain '%s': got '%s'", testHeaderVal2, testHeader) 68 } 69 70 header := http.Header{} 71 header.Add("Content-Type", "application/json") 72 73 body := strings.NewReader(`{ 74 "us-east-1": "https://us-east-1.api.joyentcloud.com" 75} 76`) 77 78 return &http.Response{ 79 StatusCode: http.StatusOK, 80 Header: header, 81 Body: ioutil.NopCloser(body), 82 }, nil 83 } 84} 85