go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gce/appengine/testing/roundtripper/roundtripper_test.go (about) 1 // Copyright 2018 The LUCI Authors. 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // 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 and 13 // limitations under the License. 14 15 package roundtripper 16 17 import ( 18 "io" 19 "net/http" 20 "reflect" 21 "testing" 22 23 "google.golang.org/api/compute/v1" 24 "google.golang.org/api/googleapi" 25 26 . "github.com/smartystreets/goconvey/convey" 27 ) 28 29 func TestJSONRoundTripper(t *testing.T) { 30 t.Parallel() 31 32 Convey("RoundTrip", t, func() { 33 rt := &JSONRoundTripper{} 34 gce, err := compute.New(&http.Client{Transport: rt}) 35 So(err, ShouldBeNil) 36 srv := compute.NewInstancesService(gce) 37 call := srv.Insert("project", "zone", &compute.Instance{Name: "name"}) 38 39 Convey("ok", func() { 40 rt.Handler = func(req any) (int, any) { 41 inst, ok := req.(*compute.Instance) 42 So(ok, ShouldBeTrue) 43 So(inst.Name, ShouldEqual, "name") 44 return http.StatusOK, &compute.Operation{ 45 ClientOperationId: "id", 46 } 47 } 48 rt.Type = reflect.TypeOf(compute.Instance{}) 49 rsp, err := call.Do() 50 So(err, ShouldBeNil) 51 So(rsp, ShouldNotBeNil) 52 So(rsp.ClientOperationId, ShouldEqual, "id") 53 }) 54 55 Convey("error", func() { 56 rt.Handler = func(_ any) (int, any) { 57 return http.StatusNotFound, nil 58 } 59 rt.Type = reflect.TypeOf(compute.Instance{}) 60 rsp, err := call.Do() 61 So(err.(*googleapi.Error).Code, ShouldEqual, http.StatusNotFound) 62 So(rsp, ShouldBeNil) 63 }) 64 }) 65 } 66 67 func TestStringRoundTripper(t *testing.T) { 68 t.Parallel() 69 70 Convey("RoundTrip", t, func() { 71 rt := &StringRoundTripper{} 72 cli := &http.Client{Transport: rt} 73 rt.Handler = func(req *http.Request) (int, string) { 74 So(req, ShouldNotBeNil) 75 return http.StatusOK, "test" 76 } 77 rsp, err := cli.Get("https://example.com") 78 So(err, ShouldBeNil) 79 So(rsp, ShouldNotBeNil) 80 So(rsp.StatusCode, ShouldEqual, http.StatusOK) 81 b, err := io.ReadAll(rsp.Body) 82 So(err, ShouldBeNil) 83 So(string(b), ShouldEqual, "test") 84 }) 85 }