### Install 'gock' Go HTTP mocking library Source: https://github.com/h2non/gock/blob/master/_examples/README.md Installs the 'gock' Go package, a powerful HTTP mocking library. This command fetches and updates the package from GitHub, preparing the environment for HTTP request mocking. ```bash go get -u github.com/h2non/gock ``` -------------------------------- ### Install 'st' Go testing utility Source: https://github.com/h2non/gock/blob/master/_examples/README.md Installs the 'st' Go package, a testing utility often used with mocking libraries. This command fetches and updates the package from GitHub. ```bash go get -u github.com/nbio/st ``` -------------------------------- ### Run gock executable examples Source: https://github.com/h2non/gock/blob/master/_examples/README.md Executes a Go program located in a specific example directory. Replace `` with the desired example name to run its standalone executable, showcasing gock's features in a runnable application. ```bash go run ./_examples//.go ``` -------------------------------- ### Run basic gock test example Source: https://github.com/h2non/gock/blob/master/_examples/README.md Specifically runs the 'basic' example tests for gock. This demonstrates fundamental usage of the gock library within a Go testing context. ```bash go test ./_examples/basic ``` -------------------------------- ### Run gock test-based examples Source: https://github.com/h2non/gock/blob/master/_examples/README.md Executes Go tests located in a specific example directory. Replace `` with the desired example name to run its associated tests, demonstrating gock's usage within a testing framework. ```bash go test ./_examples/ ``` -------------------------------- ### Run gock networking example Source: https://github.com/h2non/gock/blob/master/_examples/README.md Specifically runs the 'enable_networking' executable example for gock. This demonstrates how gock can be used in a standalone application that interacts with network requests. ```bash go run ./_examples/enable_networking/networking.go ``` -------------------------------- ### Install gock using Go Source: https://github.com/h2non/gock/blob/master/README.md This command installs the gock library for Go, fetching the latest version from its GitHub repository. It uses the Go module system to add gock to your project dependencies. ```Bash go get -u github.com/h2non/gock ``` -------------------------------- ### Mocking Basic HTTP GET Requests with Gock in Go Source: https://github.com/h2non/gock/blob/master/README.md Demonstrates how to create a simple HTTP GET mock using Gock. It sets up a mock for 'http://foo.com/bar' to return a 200 status and a JSON body, then verifies the mock is hit and the response is correct. ```go package test import ( "io/ioutil" "net/http" "testing" "github.com/nbio/st" "github.com/h2non/gock" ) func TestSimple(t *testing.T) { defer gock.Off() gock.New("http://foo.com"). Get("/bar"). Reply(200). JSON(map[string]string{"foo": "bar"}) res, err := http.Get("http://foo.com/bar") st.Expect(t, err, nil) st.Expect(t, res.StatusCode, 200) body, _ := ioutil.ReadAll(res.Body) st.Expect(t, string(body)[:13], `{"foo":"bar"}`) // Verify that we don't have pending mocks st.Expect(t, gock.IsDone(), true) } ``` -------------------------------- ### Matching HTTP Request Parameters with Gock in Go Source: https://github.com/h2non/gock/blob/master/README.md Shows how to create mocks that match specific URL query parameters. The example sets up a mock for 'http://foo.com' that only responds if 'page=1' and 'per_page=10' parameters are present in the request. ```go package test import ( "io/ioutil" "net/http" "testing" "github.com/nbio/st" "github.com/h2non/gock" ) func TestMatchParams(t *testing.T) { defer gock.Off() gock.New("http://foo.com"). MatchParam("page", "1"). MatchParam("per_page", "10"). Reply(200). BodyString("foo foo") req, err := http.NewRequest("GET", "http://foo.com?page=1&per_page=10", nil) res, err := (&http.Client{}).Do(req) st.Expect(t, err, nil) st.Expect(t, res.StatusCode, 200) body, _ := ioutil.ReadAll(res.Body) st.Expect(t, string(body), "foo foo") // Verify that we don't have pending mocks st.Expect(t, gock.IsDone(), true) } ``` -------------------------------- ### Enabling Real Networking Alongside Mocks with Gock in Go Source: https://github.com/h2non/gock/blob/master/README.md Shows how to enable real network requests while still having Gock mocks active. This allows specific URLs to be mocked while others go through to the actual network. The example mocks 'http://httpbin.org/get' but allows the body to come from the real server. ```go package main import ( "fmt" "io/ioutil" "net/http" "github.com/h2non/gock" ) func main() { defer gock.Off() defer gock.DisableNetworking() gock.EnableNetworking() gock.New("http://httpbin.org"). Get("/get"). Reply(201). SetHeader("Server", "gock") res, err := http.Get("http://httpbin.org/get") if err != nil { fmt.Errorf("Error: %s", err) } // The response status comes from the mock fmt.Printf("Status: %d\n", res.StatusCode) // The server header comes from mock as well fmt.Printf("Server header: %s\n", res.Header.Get("Server")) // Response body is the original body, _ := ioutil.ReadAll(res.Body) fmt.Printf("Body: %s", string(body)) } ``` -------------------------------- ### Define a basic HTTP mock for testing in Go Source: https://github.com/h2non/gock/blob/master/README.md This Go test function demonstrates how to define a simple HTTP mock using gock. It sets up an expectation for a GET request to 'http://server.com/bar' and configures a 200 OK response with a JSON body. The `defer gock.Off()` ensures that pending mocks are flushed after test execution. ```Go func TestFoo(t *testing.T) { defer gock.Off() // Flush pending mocks after test execution gock.New("http://server.com"). Get("/bar"). Reply(200). JSON(map[string]string{"foo": "bar"}) // Your test code starts here... } ``` -------------------------------- ### Restore an http.Client after gock interception in Go Source: https://github.com/h2non/gock/blob/master/README.md This Go example illustrates how to restore an `http.Client` to its original state after gock has intercepted it. It's a good practice for cleaning up test environments, especially when not using `http.DefaultClient` or `http.DefaultTransport`. The `defer gock.RestoreClient(client)` ensures the client is restored after the test. ```Go func TestGock (t *testing.T) { defer gock.Off() defer gock.RestoreClient(client) // ... my test code goes here } ``` -------------------------------- ### Matching HTTP Request Headers with Gock in Go Source: https://github.com/h2non/gock/blob/master/README.md Illustrates how to define mocks that match specific request headers using Gock's `MatchHeader` and `HeaderPresent` methods. It shows how to set up a mock that requires 'Authorization', 'API', and 'Accept' headers to be present and match certain patterns. ```go package test import ( "io/ioutil" "net/http" "testing" "github.com/nbio/st" "github.com/h2non/gock" ) func TestMatchHeaders(t *testing.T) { defer gock.Off() gock.New("http://foo.com"). MatchHeader("Authorization", "^foo bar$"). MatchHeader("API", "1.[0-9]+"). HeaderPresent("Accept"). Reply(200). BodyString("foo foo") req, err := http.NewRequest("GET", "http://foo.com", nil) req.Header.Set("Authorization", "foo bar") req.Header.Set("API", "1.0") req.Header.Set("Accept", "text/plain") res, err := (&http.Client{}).Do(req) st.Expect(t, err, nil) st.Expect(t, res.StatusCode, 200) body, _ := ioutil.ReadAll(res.Body) st.Expect(t, string(body), "foo foo") // Verify that we don't have pending mocks st.Expect(t, gock.IsDone(), true) } ``` -------------------------------- ### Intercepting Custom http.Client with Gock in Go Source: https://github.com/h2non/gock/blob/master/README.md Demonstrates how to make Gock intercept requests made by a custom `http.Client` instance, rather than the default `http.DefaultClient`. This is achieved by calling `gock.InterceptClient(client)`. ```go package test import ( "io/ioutil" "net/http" "testing" "github.com/nbio/st" "github.com/h2non/gock" ) func TestClient(t *testing.T) { defer gock.Off() gock.New("http://foo.com"). Reply(200). BodyString("foo foo") req, err := http.NewRequest("GET", "http://foo.com", nil) client := &http.Client{Transport: &http.Transport{}} gock.InterceptClient(client) res, err := client.Do(req) st.Expect(t, err, nil) st.Expect(t, res.StatusCode, 200) body, _ := ioutil.ReadAll(res.Body) st.Expect(t, string(body), "foo foo") // Verify that we don't have pending mocks st.Expect(t, gock.IsDone(), true) } ``` -------------------------------- ### Matching and Responding with JSON Bodies in Gock Go Source: https://github.com/h2non/gock/blob/master/README.md Explains how to mock HTTP POST requests that expect a specific JSON request body and respond with a custom JSON body. It uses `MatchType("json")` and `JSON()` for both request matching and response generation. ```go package test import ( "bytes" "io/ioutil" "net/http" "testing" "github.com/nbio/st" "github.com/h2non/gock" ) func TestMockSimple(t *testing.T) { defer gock.Off() gock.New("http://foo.com"). Post("/bar"). MatchType("json"). JSON(map[string]string{"foo": "bar"}). Reply(201). JSON(map[string]string{"bar": "foo"}) body := bytes.NewBuffer([]byte(`{"foo":"bar"}`)) res, err := http.Post("http://foo.com/bar", "application/json", body) st.Expect(t, err, nil) st.Expect(t, res.StatusCode, 201) resBody, _ := ioutil.ReadAll(res.Body) st.Expect(t, string(resBody)[:13], `{"bar":"foo"}`) // Verify that we don't have pending mocks st.Expect(t, gock.IsDone(), true) } ``` -------------------------------- ### Debugging Intercepted HTTP Requests with Gock in Go Source: https://github.com/h2non/gock/blob/master/README.md Illustrates how to observe and debug HTTP requests intercepted by Gock. By using `gock.Observe(gock.DumpRequest)`, developers can print detailed information about incoming requests to the console, aiding in debugging mock matching issues. ```go package main import ( "bytes" "net/http" "github.com/h2non/gock" ) func main() { defer gock.Off() gock.Observe(gock.DumpRequest) gock.New("http://foo.com"). Post("/bar"). MatchType("json"). JSON(map[string]string{"foo": "bar"}). Reply(200) body := bytes.NewBuffer([]byte(`{"foo":"bar"}`)) http.Post("http://foo.com/bar", "application/json", body) } ``` -------------------------------- ### Disable gock traffic interception after testing in Go Source: https://github.com/h2non/gock/blob/master/README.md This Go snippet shows the idiomatic way to disable gock's HTTP traffic interception after a test scenario. Using `defer gock.Off()` ensures that gock is turned off, minimizing potential side effects and cleaning up the test environment. ```Go func TestGock (t *testing.T) { defer gock.Off() // ... my test code goes here } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.