Debian Codegraph @

internal/oauth2/providers/google/api_test.go

raw
1 package google //nolint:testpackage
2
3 import (
4 "net/http"
5 "net/http/httptest"
6 "net/url"
7 "strings"
8 "testing"
9
10 "github.com/stretchr/testify/require"
11 )
12
13 type apiRoundTripper func(*http.Request) (*http.Response, error)
14
15 func (fn apiRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
16 return fn(req)
17 }
18
19 func TestGetResponseBodyLimits(t *testing.T) {
20 t.Parallel()
21
22 tests := []struct {
23 name string
24 statusCode int
25 body string
26 wantErrContains string
27 wantErrExcludes string
28 }{
29 {
30 name: "successful response at limit",
31 statusCode: http.StatusOK,
32 body: "[]" + strings.Repeat(" ", maxResponseBodySize-2),
33 },
34 {
35 name: "successful response exceeds limit",
36 statusCode: http.StatusOK,
37 body: strings.Repeat(" ", maxResponseBodySize+1),
38 wantErrContains: "response body from Google API https://cloudidentity.googleapis.com/test exceeds the 1048576 byte limit",
39 },
40 {
41 name: "error response is truncated",
42 statusCode: http.StatusInternalServerError,
43 body: "visible" + strings.Repeat("x", maxErrorResponseBodySize) + "hidden",
44 wantErrContains: "visible",
45 wantErrExcludes: "hidden",
46 },
47 }
48
49 for _, testCase := range tests {
50 t.Run(testCase.name, func(t *testing.T) {
51 t.Parallel()
52
53 httpClient := &http.Client{
54 Transport: apiRoundTripper(func(_ *http.Request) (*http.Response, error) {
55 response := httptest.NewRecorder()
56 response.WriteHeader(testCase.statusCode)
57 _, _ = response.WriteString(testCase.body)
58
59 return response.Result(), nil
60 }),
61 }
62
63 apiURL := &url.URL{Scheme: "https", Host: "cloudidentity.googleapis.com", Path: "/test"}
64
65 var data any
66
67 err := get[any](t.Context(), httpClient, "token", apiURL, &data)
68
69 if testCase.wantErrContains == "" {
70 require.NoError(t, err)
71
72 return
73 }
74
75 require.ErrorContains(t, err, testCase.wantErrContains)
76
77 if testCase.wantErrExcludes != "" {
78 require.NotContains(t, err.Error(), testCase.wantErrExcludes)
79 require.ErrorContains(t, err, "[truncated]")
80 }
81 })
82 }
83 }