go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/auth/internal/testing.go (about) 1 // Copyright 2015 The LUCI Authors. 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 internal 16 17 import ( 18 "bytes" 19 "context" 20 "io" 21 "net/http" 22 "sync" 23 ) 24 25 var testTransportKey = "testTransport" 26 27 // TestTransportCallback is used from unit tests. 28 type TestTransportCallback func(r *http.Request, body string) (code int, response string) 29 30 // WithTestTransport puts a testing transport in the context to use for fetches. 31 func WithTestTransport(ctx context.Context, cb TestTransportCallback) context.Context { 32 return context.WithValue(ctx, &testTransportKey, &testTransport{cb: cb}) 33 } 34 35 type testTransport struct { 36 lock sync.Mutex 37 cb TestTransportCallback 38 } 39 40 func (t *testTransport) RoundTrip(r *http.Request) (*http.Response, error) { 41 t.lock.Lock() 42 defer t.lock.Unlock() 43 body, err := io.ReadAll(r.Body) 44 r.Body.Close() 45 if err != nil { 46 return nil, err 47 } 48 code, resp := t.cb(r, string(body)) 49 return &http.Response{ 50 StatusCode: code, 51 Body: io.NopCloser(bytes.NewReader([]byte(resp))), 52 }, nil 53 }