gock

repository·master·Indexed 24 days ago

https://github.com/h2non/gock

A versatile HTTP mocking library for Go that works with any net/http based implementation. It allows developers to declaratively define HTTP expectations to simulate API responses in tests or runtime scenarios by intercepting outgoing requests via http.DefaultTransport or custom http.Client instances.

Tokens
6.4K
Snippets
12
Records
52
Agent score
80%

What's inside gock

  1. How gock mocks HTTP requests

    master

    gock operates by intercepting outgoing HTTP requests through the following lifecycle:

    1. Interception: It intercepts requests via http.DefaultTransport or a custom http.Transport used by any http.Client.
    2. Matching: It matches outgoing requests against a pool of defined mock expectations in FIFO (First-In-First-Out) declaration order.
    3. Resolution: If a mock matches, it is used to compose the mock HTTP response.
    4. Fallback: If no mock matches, the request resolves with an error, unless real networking mode is enabled, in which case a real HTTP request is performed.
  2. Install gock and dependencies

    master

    To use gock in your Go projects, install the package and its required dependency using go get:

    go get -u github.com/nbio/st
    go get -u github.com/h2non/gock
    go get -u github.com/nbio/st
    
    go get -u github.com/h2non/gock
  3. Manage gock lifecycle and cleanup

    master

    To prevent side effects and ensure clean test environments, follow these practices:

    • Flush pending mocks: Use defer gock.Off() at the start of your test to ensure all mocks are cleared after the test execution.
    • Disable interception: Use gock.Off() to stop gock from intercepting traffic once your HTTP testing logic is complete.
    • Intercept custom clients: Use gock.InterceptClient(client) to target a specific http.Client instance. You only need to call this once per client.
    • Restore custom clients: If you intercepted a custom client, call gock.RestoreClient(client) (typically in a defer statement) to return the client to its original state. This is not required for http.DefaultClient or http.DefaultTransport.
    func TestGock (t *testing.T) {
    	defer gock.Off()
    	defer gock.RestoreClient(client)
    
    	// ... my test code goes here
    }
  4. Mocking best practices for tests

    master

    Declare mocks before test logic

    Always declare your mocks before starting your concrete test logic to avoid race conditions during configuration or interception.

    Define complex mocks first

    When defining multiple mocks in a single suite, define concrete/specific mocks first and generic mocks last. This prevents generic mocks (which perform less complex matches) from accidentally intercepting requests intended for specific mocks.

  5. Run gock examples

    master

    The _examples directory contains various use cases. You can run them in two ways depending on how they are structured:

    Running Test-based examples

    If the example is structured as a Go test, run it using the go test command:

    go test ./_examples/<example>

    Running Executable examples

    If the example is a standalone Go program, run it using go run:

    go run ./_examples/<example>/<example>.go
  6. How Mocker.Match works

    master

    When Match(req *http.Request) is called, the Mocker performs the following steps in order:

    1. Disable Check: If the mock has been manually disabled via Disable(), it returns false, nil immediately.
    2. Filters: It iterates through all Filters defined on the Request. If any filter returns false, the match fails.
    3. Mappers: It iterates through all Mappers defined on the Request. Mappers can transform the incoming request before matching.
    4. Matcher Execution: It uses the configured Matcher to compare the (potentially transformed) request against the mock's expected Request configuration.
    5. Counter Decrement: If a match is successful, the internal request counter is decremented. If the counter reaches zero and the request is not marked as Persisted, the mock is automatically disabled.
  7. Debug intercepted HTTP requests

    master

    You can inspect intercepted requests by using gock.Observe() with the gock.DumpRequest helper. This is useful for seeing exactly what request gock is seeing during matching.

    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)
    
    	// ... perform request
    }
  8. Simple HTTP mocking example

    master

    A basic example of mocking a GET request and verifying the response and the fact that all mocks were consumed.

    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")
      // ... assertions
    
      // Verify that we don't have pending mocks
      st.Expect(t, gock.IsDone(), true)
    }
  9. Enable real networking mode

    master

    By default, gock will return an error if no mock matches a request. To allow real HTTP requests to proceed when no mock is defined, use gock.EnableNetworking(). To revert to default behavior, use gock.DisableNetworking().

    func main() {
      defer gock.Off()
      defer gock.DisableNetworking()
    
      gock.EnableNetworking()
      // ...
    }
  10. Initialize a gock Transport

    master
    To use gock for intercepting HTTP requests, you can use the NewTransport() function. This creates a new *Transport instance that implements the http.RoundTripper interface. By default, it wraps the NativeTransport (the standard http.DefaultTransport). You can then assign this transport to an http.Client to enable mocking.
  11. Retrieve pending mocks with Pending()

    master
    The Pending() []Mock function returns a slice of mocks that have not yet been triggered. Note that calling Pending() automatically triggers a Clean() operation first to ensure the returned list only contains active, non-done mocks.