Conversation
This adds a thread-safe RoundTripper that can be used for mocking HTTP requests in tests. Incoming requests are matched based on their contents, not the order the stubs were registered in.
| return result, nil | ||
| } | ||
|
|
||
| func RepoNetworkStubResponse(owner, repo, permission string) string { |
There was a problem hiding this comment.
This moves the non-trivial response stub more closer to the actual implementation so it can be kept in sync with RepoNetwork.
| { "data": { "repository": { "forks": { "nodes": [ | ||
| ] } } } } | ||
| http := initMockHTTP() | ||
| defer http.Verify(t) |
There was a problem hiding this comment.
Optional: once the test is done, verify that all response stubs were matched and fail the test otherwise
There was a problem hiding this comment.
This is a nice idea but I don't mind if you want to do it later
There was a problem hiding this comment.
Oh, it's done! This demonstrates its use. It's an added level of assertion; I've only indicated that this line is "optional" because the test case would have passed without it too
| ] } } } } | ||
| http := initMockHTTP() | ||
| defer http.Verify(t) | ||
| http.Register(httpmock.GraphQL(`\bviewerPermission\b`), httpmock.StringResponse(api.RepoNetworkStubResponse("OWNER", "REPO", "WRITE"))) |
There was a problem hiding this comment.
Incoming requests are now matched by their GraphQL query contents; this simple regexp is used to determine that this query is detecting the base/head repository, and we return a stubbed RepoNetwork response
| `, func(inputs map[string]interface{}) { | ||
| eq(t, inputs["repositoryId"], "REPOID") |
There was a problem hiding this comment.
For GraphQL mutations we can opt to receive a parsed map of input variables which we can then check without having to repeat the JSON-parsing boilerplate.
| return http | ||
| } | ||
|
|
||
| func initMockHTTP() *httpmock.Registry { |
There was a problem hiding this comment.
This supersedes initFakeHTTP, which was the obsolete sequential stubber
| { "data": { "repository": { "forks": { "nodes": [ | ||
| ] } } } } | ||
| http := initMockHTTP() | ||
| defer http.Verify(t) |
There was a problem hiding this comment.
This is a nice idea but I don't mind if you want to do it later
This adds a thread-safe RoundTripper that can be used for mocking HTTP requests in tests. Incoming requests are matched based on their contents, not the order the stubs were registered in. This ensures that the tests keep working even if the requests themselves were parallelized and their order isn't guaranteed.
This was loosely modeled after https://pkg.go.dev/github.com/jarcoal/httpmock which I was evaluating for potential use in tests, but that one was designed for RESTful APIs and didn't look like it could handle looking inside GraphQL requests in the matching phase.
Needed for #787