Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gock is not intercepting unit tests request #115

Open
victorvbls-paypal opened this issue Feb 1, 2024 · 0 comments
Open

Gock is not intercepting unit tests request #115

victorvbls-paypal opened this issue Feb 1, 2024 · 0 comments

Comments

@victorvbls-paypal
Copy link

victorvbls-paypal commented Feb 1, 2024

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") != "[email protected]" {
			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 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant