Last active
October 1, 2025 08:27
-
-
Save xcoulon/6e4c693dc575f629ca2352fe73f24c86 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gock_test | |
import ( | |
"io" | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
"github.com/h2non/gock" | |
"github.com/stretchr/testify/assert" | |
"github.com/stretchr/testify/require" | |
) | |
func TestEnableNetwork(t *testing.T) { | |
// given | |
cl := http.DefaultClient | |
srv := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { | |
// basic handler calling the underlying remote service | |
argoCl := http.DefaultClient | |
r, err := argoCl.Get("https://my-argocd-server/api/v1/applications") | |
if err != nil { | |
t.Errorf("error while calling Argo CD: %v", err.Error()) | |
resp.WriteHeader(http.StatusInternalServerError) | |
return | |
} | |
defer func() { | |
if err := r.Body.Close(); err != nil { | |
t.Errorf("failed to close response body: %v", err.Error()) | |
} | |
}() | |
data, err := io.ReadAll(r.Body) | |
if err != nil { | |
resp.WriteHeader(http.StatusInternalServerError) | |
return | |
} | |
_, _ = resp.Write(data) | |
})) | |
defer srv.Close() | |
gock.New("https://my-argocd-server"). | |
Get("/api/v1/applications"). | |
Reply(200). | |
BodyString(`{"items": []}`) | |
defer gock.Off() | |
gock.EnableNetworking() | |
gock.NetworkingFilter(func(req *http.Request) bool { | |
return req.URL.String() == srv.URL // allow network calls to the MCP server | |
}) | |
// when | |
resp, err := cl.Get(srv.URL) | |
// then | |
require.NoError(t, err) | |
data, err := io.ReadAll(resp.Body) | |
defer func() { | |
if err := resp.Body.Close(); err != nil { | |
t.Errorf("failed to close response body: %v", err.Error()) | |
} | |
}() | |
require.NoError(t, err) | |
require.Equal(t, http.StatusOK, resp.StatusCode) | |
assert.JSONEq(t, `{"items": []}`, string(data)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment