| 1 |
package github //nolint:testpackage |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"io" |
| 6 |
"net/http" |
| 7 |
"strings" |
| 8 |
"testing" |
| 9 |
) |
| 10 |
|
| 11 |
type benchmarkRoundTripper func(*http.Request) (*http.Response, error) |
| 12 |
|
| 13 |
func (fn benchmarkRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 14 |
return fn(req) |
| 15 |
} |
| 16 |
|
| 17 |
func BenchmarkGetPagination(b *testing.B) { |
| 18 |
for _, tc := range []struct { |
| 19 |
name string |
| 20 |
apiURL string |
| 21 |
link string |
| 22 |
}{ |
| 23 |
{ |
| 24 |
name: "no-pagination", |
| 25 |
apiURL: "https://api.github.com/user/orgs", |
| 26 |
link: "", |
| 27 |
}, |
| 28 |
{ |
| 29 |
name: "next-page", |
| 30 |
apiURL: "https://api.github.com/user/orgs?page=1", |
| 31 |
link: `<https://api.github.com/user/orgs?page=2>; rel="next", <https://api.github.com/user/orgs?page=4>; rel="last"`, |
| 32 |
}, |
| 33 |
{ |
| 34 |
name: "already-last-page", |
| 35 |
apiURL: "https://api.github.com/user/orgs?page=4", |
| 36 |
link: `<https://api.github.com/user/orgs?page=4>; rel="last"`, |
| 37 |
}, |
| 38 |
} { |
| 39 |
b.Run(tc.name, func(b *testing.B) { |
| 40 |
resp := &http.Response{Header: http.Header{"Link": []string{tc.link}}} |
| 41 |
|
| 42 |
var ( |
| 43 |
nextURL string |
| 44 |
err error |
| 45 |
) |
| 46 |
|
| 47 |
b.ReportAllocs() |
| 48 |
b.ResetTimer() |
| 49 |
|
| 50 |
for b.Loop() { |
| 51 |
nextURL, err = getPagination(tc.apiURL, resp) |
| 52 |
if err != nil { |
| 53 |
b.Fatal(err) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
_ = nextURL |
| 58 |
}) |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
func BenchmarkGet(b *testing.B) { |
| 63 |
ctx := context.Background() |
| 64 |
client := &http.Client{ |
| 65 |
Transport: benchmarkRoundTripper(func(_ *http.Request) (*http.Response, error) { |
| 66 |
return &http.Response{ |
| 67 |
StatusCode: http.StatusOK, |
| 68 |
Header: make(http.Header), |
| 69 |
Body: io.NopCloser(strings.NewReader(`{"login":"octocat","id":1}`)), |
| 70 |
}, nil |
| 71 |
}), |
| 72 |
} |
| 73 |
|
| 74 |
apiURL := "https://api.github.com/user" |
| 75 |
|
| 76 |
var ( |
| 77 |
nextURL string |
| 78 |
user struct { |
| 79 |
Login string `json:"login"` |
| 80 |
ID int `json:"id"` |
| 81 |
} |
| 82 |
) |
| 83 |
|
| 84 |
b.ReportAllocs() |
| 85 |
b.ResetTimer() |
| 86 |
|
| 87 |
for b.Loop() { |
| 88 |
user = struct { |
| 89 |
Login string `json:"login"` |
| 90 |
ID int `json:"id"` |
| 91 |
}{} |
| 92 |
|
| 93 |
var err error |
| 94 |
|
| 95 |
nextURL, err = get(ctx, client, "TOKEN", apiURL, &user) |
| 96 |
if err != nil { |
| 97 |
b.Fatal(err) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
_ = nextURL |
| 102 |
_ = user |
| 103 |
} |