| 1 |
package testsuite |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"net" |
| 9 |
"net/http" |
| 10 |
"net/http/httptest" |
| 11 |
"net/url" |
| 12 |
"strings" |
| 13 |
"syscall" |
| 14 |
"testing" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/stretchr/testify/require" |
| 18 |
) |
| 19 |
|
| 20 |
// RoundTripperFunc wraps an http.RoundTripper and allows a custom function to |
| 21 |
// intercept each request. |
| 22 |
type RoundTripperFunc struct { |
| 23 |
fn func(rt http.RoundTripper, req *http.Request) (*http.Response, error) |
| 24 |
rt http.RoundTripper |
| 25 |
} |
| 26 |
|
| 27 |
// NewRoundTripperFunc returns a RoundTripperFunc that calls fn with the wrapped |
| 28 |
// RoundTripper for each request. |
| 29 |
func NewRoundTripperFunc(rt http.RoundTripper, fn func(rt http.RoundTripper, req *http.Request) (*http.Response, error)) *RoundTripperFunc { |
| 30 |
return &RoundTripperFunc{fn, rt} |
| 31 |
} |
| 32 |
|
| 33 |
// RoundTrip implements http.RoundTripper. |
| 34 |
func (f *RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { |
| 35 |
return f.fn(f.rt, req) |
| 36 |
} |
| 37 |
|
| 38 |
// MockRoundTripper mocks selected HTTP calls while delegating everything else to |
| 39 |
// the provided RoundTripper. |
| 40 |
type MockRoundTripper struct { |
| 41 |
rt http.RoundTripper |
| 42 |
} |
| 43 |
|
| 44 |
// NewMockRoundTripper creates a MockRoundTripper. If rt is nil the default |
| 45 |
// transport is used. |
| 46 |
func NewMockRoundTripper(rt http.RoundTripper) *MockRoundTripper { |
| 47 |
if rt == nil { |
| 48 |
rt = http.DefaultTransport |
| 49 |
} |
| 50 |
|
| 51 |
return &MockRoundTripper{rt} |
| 52 |
} |
| 53 |
|
| 54 |
// RoundTrip implements http.RoundTripper and returns mocked responses for |
| 55 |
// specific hosts. |
| 56 |
// |
| 57 |
//nolint:cyclop |
| 58 |
func (f *MockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 59 |
switch req.URL.Host { |
| 60 |
case "cloudidentity.googleapis.com": |
| 61 |
resp := httptest.NewRecorder() |
| 62 |
_, _ = resp.WriteString(`{"memberships": [], "nextPageToken": ""}`) |
| 63 |
|
| 64 |
return resp.Result(), nil |
| 65 |
case "api.github.com": |
| 66 |
switch req.URL.Path { |
| 67 |
case "/user": |
| 68 |
resp := httptest.NewRecorder() |
| 69 |
_, _ = resp.WriteString(`{"login": "test-user", "id": 123456, "email": "test-user@localhost"}`) |
| 70 |
resp.Header().Set("Content-Type", "application/json") |
| 71 |
|
| 72 |
return resp.Result(), nil |
| 73 |
case "/user/orgs", "/user/teams": |
| 74 |
resp := httptest.NewRecorder() |
| 75 |
_, _ = resp.WriteString(`[]`) |
| 76 |
resp.Header().Set("Content-Type", "application/json") |
| 77 |
|
| 78 |
return resp.Result(), nil |
| 79 |
default: |
| 80 |
return f.rt.RoundTrip(req) //nolint:wrapcheck |
| 81 |
} |
| 82 |
|
| 83 |
case "github.com": |
| 84 |
// https://blog.seriesci.com/how-to-mock-oauth-in-go/ |
| 85 |
switch req.URL.Path { |
| 86 |
case "/login/oauth/authorize": |
| 87 |
state := req.FormValue("state") |
| 88 |
redirectURI := req.FormValue("redirect_uri") |
| 89 |
|
| 90 |
uri, err := url.Parse(redirectURI) |
| 91 |
if err != nil { |
| 92 |
return nil, err //nolint:wrapcheck |
| 93 |
} |
| 94 |
|
| 95 |
v := url.Values{} |
| 96 |
v.Set("code", "code") |
| 97 |
v.Set("state", state) |
| 98 |
uri.RawQuery = v.Encode() |
| 99 |
|
| 100 |
resp := httptest.NewRecorder() |
| 101 |
resp.Header().Set("Location", uri.String()) |
| 102 |
resp.WriteHeader(http.StatusTemporaryRedirect) |
| 103 |
|
| 104 |
return resp.Result(), nil |
| 105 |
case "/login/oauth/access_token": |
| 106 |
resp := httptest.NewRecorder() |
| 107 |
resp.Header().Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") |
| 108 |
_, _ = resp.WriteString(`access_token=gho_mock&scope=read%3Aorg%2Cuser%3Aemail&token_type=bearer`) |
| 109 |
|
| 110 |
return resp.Result(), nil |
| 111 |
} |
| 112 |
|
| 113 |
return f.rt.RoundTrip(req) //nolint:wrapcheck |
| 114 |
default: |
| 115 |
return f.rt.RoundTrip(req) //nolint:wrapcheck |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
func DoHTTPRequest(tb testing.TB, client *http.Client, baseURL, method, requestURL string, header http.Header, body io.Reader) (*http.Response, []byte, error) { |
| 120 |
tb.Helper() |
| 121 |
|
| 122 |
if !strings.Contains(requestURL, "://") && baseURL != "" { |
| 123 |
requestURL = baseURL + requestURL |
| 124 |
} |
| 125 |
|
| 126 |
request, err := http.NewRequestWithContext(tb.Context(), method, requestURL, body) |
| 127 |
require.NoError(tb, err) |
| 128 |
|
| 129 |
if header != nil { |
| 130 |
request.Header = header |
| 131 |
} |
| 132 |
|
| 133 |
resp, err := client.Do(request) |
| 134 |
require.NoError(tb, err) |
| 135 |
|
| 136 |
defer func() { |
| 137 |
_ = resp.Body.Close() |
| 138 |
}() |
| 139 |
|
| 140 |
respBody, err := io.ReadAll(resp.Body) |
| 141 |
require.NoError(tb, err) |
| 142 |
|
| 143 |
return resp, respBody, nil |
| 144 |
} |
| 145 |
|
| 146 |
// WaitUntilListening tries to connect to a network address until it is |
| 147 |
// available. It returns the connection or an error after several retries. |
| 148 |
func WaitUntilListening(ctx context.Context, tb testing.TB, network, address string) (net.Conn, error) { |
| 149 |
tb.Helper() |
| 150 |
|
| 151 |
var ( |
| 152 |
conn net.Conn |
| 153 |
err error |
| 154 |
) |
| 155 |
|
| 156 |
dialer := &net.Dialer{Timeout: 100 * time.Millisecond} |
| 157 |
|
| 158 |
ticker := time.NewTicker(50 * time.Millisecond) |
| 159 |
defer ticker.Stop() |
| 160 |
|
| 161 |
for range 10 { |
| 162 |
conn, err = dialer.DialContext(ctx, network, address) |
| 163 |
if err == nil { |
| 164 |
return conn, nil |
| 165 |
} |
| 166 |
|
| 167 |
if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.Errno(10061)) { |
| 168 |
select { |
| 169 |
case <-ctx.Done(): |
| 170 |
return nil, fmt.Errorf("listener not listening: %w", ctx.Err()) |
| 171 |
case <-ticker.C: |
| 172 |
} |
| 173 |
|
| 174 |
continue |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
return nil, fmt.Errorf("listener not listening: %w", err) |
| 179 |
} |