|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "io/ioutil" |
| 8 | + "net/http" |
| 9 | + "path/filepath" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/stretchr/testify/assert" |
| 14 | + "github.com/stretchr/testify/require" |
| 15 | +) |
| 16 | + |
| 17 | +func Test_CacheReponse(t *testing.T) { |
| 18 | + counter := 0 |
| 19 | + fakeHTTP := funcTripper{ |
| 20 | + roundTrip: func(req *http.Request) (*http.Response, error) { |
| 21 | + counter += 1 |
| 22 | + body := fmt.Sprintf("%d: %s %s", counter, req.Method, req.URL.String()) |
| 23 | + return &http.Response{ |
| 24 | + StatusCode: 200, |
| 25 | + Body: ioutil.NopCloser(bytes.NewBufferString(body)), |
| 26 | + }, nil |
| 27 | + }, |
| 28 | + } |
| 29 | + |
| 30 | + cacheDir := filepath.Join(t.TempDir(), "gh-cli-cache") |
| 31 | + httpClient := NewHTTPClient(ReplaceTripper(fakeHTTP), CacheReponse(time.Minute, cacheDir)) |
| 32 | + |
| 33 | + do := func(method, url string, body io.Reader) (string, error) { |
| 34 | + req, err := http.NewRequest(method, url, body) |
| 35 | + if err != nil { |
| 36 | + return "", err |
| 37 | + } |
| 38 | + res, err := httpClient.Do(req) |
| 39 | + if err != nil { |
| 40 | + return "", err |
| 41 | + } |
| 42 | + resBody, err := ioutil.ReadAll(res.Body) |
| 43 | + if err != nil { |
| 44 | + err = fmt.Errorf("ReadAll: %w", err) |
| 45 | + } |
| 46 | + return string(resBody), err |
| 47 | + } |
| 48 | + |
| 49 | + res1, err := do("GET", "http://example.com/path", nil) |
| 50 | + require.NoError(t, err) |
| 51 | + assert.Equal(t, "1: GET http://example.com/path", res1) |
| 52 | + res2, err := do("GET", "http://example.com/path", nil) |
| 53 | + require.NoError(t, err) |
| 54 | + assert.Equal(t, "1: GET http://example.com/path", res2) |
| 55 | + |
| 56 | + res3, err := do("GET", "http://example.com/path2", nil) |
| 57 | + require.NoError(t, err) |
| 58 | + assert.Equal(t, "2: GET http://example.com/path2", res3) |
| 59 | + |
| 60 | + res4, err := do("POST", "http://example.com/path", bytes.NewBufferString(`hello`)) |
| 61 | + require.NoError(t, err) |
| 62 | + assert.Equal(t, "3: POST http://example.com/path", res4) |
| 63 | + res5, err := do("POST", "http://example.com/path", bytes.NewBufferString(`hello`)) |
| 64 | + require.NoError(t, err) |
| 65 | + assert.Equal(t, "3: POST http://example.com/path", res5) |
| 66 | + |
| 67 | + res6, err := do("POST", "http://example.com/path", bytes.NewBufferString(`hello2`)) |
| 68 | + require.NoError(t, err) |
| 69 | + assert.Equal(t, "4: POST http://example.com/path", res6) |
| 70 | +} |
0 commit comments