...

Source file src/cloud.google.com/go/auth/credentials/compute_test.go

Documentation: cloud.google.com/go/auth/credentials

     1  // Copyright 2023 Google LLC
     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 credentials
    16  
    17  import (
    18  	"context"
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"strings"
    22  	"testing"
    23  )
    24  
    25  const computeMetadataEnvVar = "GCE_METADATA_HOST"
    26  
    27  func TestComputeTokenProvider(t *testing.T) {
    28  	scope := "https://www.googleapis.com/auth/bigquery"
    29  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    30  		if strings.HasSuffix(r.URL.String(), computeTokenURI) {
    31  			t.Errorf("got %q, want %q", r.URL.String(), computeTokenURI)
    32  		}
    33  		if r.URL.Query().Get("scopes") != scope {
    34  			t.Errorf("got %q, want %q", r.URL.Query().Get("scopes"), scope)
    35  		}
    36  		w.Header().Set("Content-Type", "application/json")
    37  		w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "token_type": "bearer", "expires_in": 86400}`))
    38  	}))
    39  	t.Setenv(computeMetadataEnvVar, strings.TrimPrefix(ts.URL, "http://"))
    40  	tp := computeTokenProvider(0, scope)
    41  	tok, err := tp.Token(context.Background())
    42  	if err != nil {
    43  		t.Fatal(err)
    44  	}
    45  	if want := "90d64460d14870c08c81352a05dedd3465940a7c"; tok.Value != want {
    46  		t.Errorf("got %q, want %q", tok.Value, want)
    47  	}
    48  	if want := "bearer"; tok.Type != want {
    49  		t.Errorf("got %q, want %q", tok.Value, want)
    50  	}
    51  }
    52  

View as plain text