github.com/instana/go-sensor@v1.62.2-0.20240520081010-4919868049e1/gcloud/compute_metadata_test.go (about)

     1  // (c) Copyright IBM Corp. 2021
     2  // (c) Copyright Instana Inc. 2020
     3  
     4  package gcloud_test
     5  
     6  import (
     7  	"context"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"net/http/httptest"
    11  	"testing"
    12  
    13  	"github.com/instana/go-sensor/gcloud"
    14  	"github.com/stretchr/testify/assert"
    15  	"github.com/stretchr/testify/require"
    16  )
    17  
    18  func TestComputeMetadataProvider_ComputeMetadata(t *testing.T) {
    19  	baseURL, mux, teardown := setupTS()
    20  	defer teardown()
    21  
    22  	data, err := ioutil.ReadFile("testdata/computeMetadata.json")
    23  	require.NoError(t, err)
    24  
    25  	mux.HandleFunc("/computeMetadata/v1", func(w http.ResponseWriter, req *http.Request) {
    26  		assert.Equal(t, "true", req.URL.Query().Get("recursive"))
    27  		assert.Equal(t, "Google", req.Header.Get("Metadata-Flavor"))
    28  
    29  		w.Write(data)
    30  	})
    31  
    32  	c := gcloud.NewComputeMetadataProvider(baseURL, nil)
    33  
    34  	md, err := c.ComputeMetadata(context.Background())
    35  	require.NoError(t, err)
    36  
    37  	assert.Equal(t, gcloud.ComputeMetadata{
    38  		Project: gcloud.ProjectMetadata{
    39  			NumericProjectID: 1234567890,
    40  			ProjectID:        "test-project",
    41  		},
    42  		Instance: gcloud.InstanceMetadata{
    43  			ID:     "id1",
    44  			Region: "projects/1234567890/regions/us-central1",
    45  		},
    46  	}, md)
    47  }
    48  
    49  func setupTS() (string, *http.ServeMux, func()) {
    50  	mux := http.NewServeMux()
    51  	srv := httptest.NewServer(mux)
    52  
    53  	return srv.URL, mux, srv.Close
    54  }