Gock is not intercepting unit tests request
victorvbls-paypal opened this issue · comments
victorvbls-paypal commented
I am writing some unit tests that make an request to a given endpoint lets call it myAPI
in my tests I've wrote a setup part to configure the gock to mock myAPI
endpoint
doRequest
is using default http.Client.
t.Run("Happy Path", func(t *testing.T) {
setupMockRequest(r)
defer gock.Off()
err = doRequest()
require.NoError(t, err)
require.True(t, gock.IsDone())
})
...
func setupMockRequest(r *gomodels.Return) {
host := "https://my.api.com"
endpoint := "/v1/data.json"
matcher := gock.New(host).Post(endpoint)
matcher.AddMatcher(func(request *http.Request, request2 *gock.Request) (bool, error) {
err := request.ParseForm()
if err != nil {
return false, err
}
if request.Form.Get("email") != "myemail@email.com" {
return false, nil
}
return true, nil
})
matcher.MatchHeader("Content-Type", "application/x-www-form-urlencoded")
matcher.BasicAuth("abc123", "")
matcher.Reply(200)
}
Code in doRequest
that executed the request:
request, err := http.NewRequest("POST", "https://my.api.com/v1/data.json", strings.NewReader(myApiRequest.Encode()))
if err != nil {
return err
}
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
request.SetBasicAuth(conf.Username, "")
resp, err := httptools.CheckResponse(http.DefaultClient.Do(request))
Unfortunately I am getting 401, it seems that gock it is not intercepting the request, as consequence it is reaching the real API and that why I am getting unauthorized. What I am doing wrong here ? What did I miss ?
Note: My user dont have admin rights in the machine. Is that a problem to gock ?