Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Generating Auth tokens for Cloud Function Unit Tests

Hello,

My Go application calls several Cloud Functions, and I am writing Unit tests for it. The documentation seems to recommend using the following [1]

func makeGetRequest(w io.Writer, targetURL string, audience string) error {
       
// For Cloud Functions, endpoint (`serviceUrl`) and `audience` are the same.
       
// Example `audience` value (Cloud Functions): https://<PROJECT>-<REGION>-<PROJECT_ID>.cloudfunctions.net/myFunction
       
// (`targetURL` and `audience` will differ for GET parameters)
        ctx
:= context.Background()

       
// client is a http.Client that automatically adds an "Authorization" header
       
// to any requests made.
        client
, err := idtoken.NewClient(ctx, audience)
       
if err != nil {
               
return fmt.Errorf("idtoken.NewClient: %v", err)
       
}

        resp
, err := client.Get(targetURL)
       
if err != nil {
               
return fmt.Errorf("client.Get: %v", err)
       
}
        defer resp
.Body.Close()
       
if _, err := io.Copy(w, resp.Body); err != nil {
               
return fmt.Errorf("io.Copy: %v", err)
       
}

       
return nil
}

I can mock the targetUrl rather easily by using httptest to generate a testServer and use its URL property:

 

testServer = httptest.NewServer(http.HandlerFunc(MockHandlerFunc))
MockRegisterTriggerUrls(testServer.URL)

But using the same URL for the audience gives the following error:

idtoken: unsupported credentials type

Is there any workaround for this?

[1] https://cloud.google.com/functions/docs/securing/authenticating#generating_tokens_programmatically

 

0 1 816
1 REPLY 1

more over, can we please add a documentation page that is the equivalent of the page below, for 2nd gen cloud functions:

https://cloud.google.com/functions/docs/testing/test-http