h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
https://pkg.go.dev/github.com/h2non/gock
MIT License
2.04k stars 106 forks source link

Gock is not intercepting unit tests request #115

Open victorvbls-paypal opened 5 months ago

victorvbls-paypal commented 5 months ago

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 ?