go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gce/vmtoken/client/client_test.go (about)

     1  // Copyright 2019 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 client
    16  
    17  import (
    18  	"net/http"
    19  	"net/http/httptest"
    20  	"net/url"
    21  	"testing"
    22  
    23  	"cloud.google.com/go/compute/metadata"
    24  
    25  	"go.chromium.org/luci/gce/appengine/testing/roundtripper"
    26  	"go.chromium.org/luci/gce/vmtoken"
    27  
    28  	. "github.com/smartystreets/goconvey/convey"
    29  )
    30  
    31  func TestNewClient(t *testing.T) {
    32  	t.Parallel()
    33  
    34  	Convey("NewClient", t, func(c C) {
    35  		// Create a test server which expects the token.
    36  		srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
    37  			c.So(req.Header.Get(vmtoken.Header), ShouldEqual, "token")
    38  		}))
    39  
    40  		// Create a mock metadata client which returns the token.
    41  		meta := metadata.NewClient(&http.Client{
    42  			Transport: &roundtripper.StringRoundTripper{
    43  				Handler: func(req *http.Request) (int, string) {
    44  					So(req.URL.Path, ShouldEqual, "/computeMetadata/v1/instance/service-accounts/account/identity")
    45  					url, err := url.Parse(srv.URL)
    46  					So(err, ShouldBeNil)
    47  					So(req.URL.Query().Get("audience"), ShouldEqual, "http://"+url.Host)
    48  					return http.StatusOK, "token"
    49  				},
    50  			},
    51  		})
    52  
    53  		cli := NewClient(meta, "account")
    54  		_, err := cli.Get(srv.URL)
    55  		So(err, ShouldBeNil)
    56  	})
    57  }