• Stars
    star
    2,067
  • Rank 22,353 (Top 0.5 %)
  • Language
    Go
  • License
    MIT License
  • Created over 8 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

gock GitHub release GoDoc Coverage Status Go Report Card license

Versatile HTTP mocking made easy in Go that works with any net/http based stdlib implementation.

Heavily inspired by nock. There is also its Python port, pook.

To get started, take a look to the examples.

Features

  • Simple, expressive, fluent API.
  • Semantic API DSL for declarative HTTP mock declarations.
  • Built-in helpers for easy JSON/XML mocking.
  • Supports persistent and volatile TTL-limited mocks.
  • Full regular expressions capable HTTP request mock matching.
  • Designed for both testing and runtime scenarios.
  • Match request by method, URL params, headers and bodies.
  • Extensible and pluggable HTTP matching rules.
  • Ability to switch between mock and real networking modes.
  • Ability to filter/map HTTP requests for accurate mock matching.
  • Supports map and filters to handle mocks easily.
  • Wide compatible HTTP interceptor using http.RoundTripper interface.
  • Works with any net/http compatible client, such as gentleman.
  • Network timeout/cancelation delay simulation.
  • Extensible and hackable API.
  • Dependency free.

Installation

go get -u github.com/h2non/gock

API

See godoc reference for detailed API documentation.

How it mocks

  1. Intercepts any HTTP outgoing request via http.DefaultTransport or custom http.Transport used by any http.Client.
  2. Matches outgoing HTTP requests against a pool of defined HTTP mock expectations in FIFO declaration order.
  3. If at least one mock matches, it will be used in order to compose the mock HTTP response.
  4. If no mock can be matched, it will resolve the request with an error, unless real networking mode is enable, in which case a real HTTP request will be performed.

Tips

Testing

Declare your mocks before you start declaring the concrete test logic:

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...
}

Race conditions

If you're running concurrent code, be aware that your mocks are declared first to avoid unexpected race conditions while configuring gock or intercepting custom HTTP clients.

gock is not fully thread-safe, but sensible parts are. Any help making gock more reliable in this sense is appreciated.

Define complex mocks first

If you're mocking a bunch of mocks in the same test suite, it's recommended to define the more concrete mocks first, and then the generic ones.

This approach usually avoids matching unexpected generic mocks (e.g: specific header, body payload...) instead of the generic ones that performs less complex matches.

Disable gock traffic interception once done

In other to minimize potential side effects within your test code, it's a good practice disabling gock once you are done with your HTTP testing logic.

A Go idiomatic approach for doing this can be using it in a defer statement, such as:

func TestGock (t *testing.T) {
	defer gock.Off()

	// ... my test code goes here
}

Intercept an http.Client just once

You don't need to intercept multiple times the same http.Client instance.

Just call gock.InterceptClient(client) once, typically at the beginning of your test scenarios.

Restore an http.Client after interception

NOTE: this is not required is you are using http.DefaultClient or http.DefaultTransport.

As a good testing pattern, you should call gock.RestoreClient(client) after running your test scenario, typically as after clean up hook.

You can also use a defer statement for doing it, as you do with gock.Off(), such as:

func TestGock (t *testing.T) {
	defer gock.Off()
	defer gock.RestoreClient(client)

	// ... my test code goes here
}

Examples

See examples directory for more featured use cases.

Simple mocking via tests

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)
}

Request headers matching

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)
}

Request param matching

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)
}

JSON body matching and response

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)
}

Mocking a custom http.Client and http.RoundTripper

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)
}

Enable real networking

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))
}

Debug intercepted http requests

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)
}

Hacking it!

You can easily hack gock defining custom matcher functions with own matching rules.

See add matcher functions and custom matching layer examples for further details.

License

MIT - Tomas Aparicio

More Repositories

1

imaginary

Fast, simple, scalable, Docker-ready HTTP microservice for high-level image processing
Go
5,543
star
2

toxy

Hackable HTTP proxy for resiliency testing and simulated network conditions
JavaScript
2,733
star
3

bimg

Go package for fast high-level image processing powered by libvips C library
Go
2,683
star
4

filetype

Fast, dependency-free Go package to infer binary file types based on the magic numbers header signature
Go
2,076
star
5

gentleman

Plugin-driven, extensible HTTP client toolkit for Go
Go
1,072
star
6

videoshow

Simple node.js utility to create video slideshows from images with optional audio and visual effects using ffmpeg
JavaScript
873
star
7

baloo

Expressive end-to-end HTTP API testing made easy in Go
Go
776
star
8

jshashes

Fast and dependency-free cryptographic hashing library for node.js and browsers (supports MD5, SHA1, SHA256, SHA512, RIPEMD, HMAC)
JavaScript
698
star
9

filetype.py

Small, dependency-free, fast Python package to infer binary file types checking the magic numbers signature
Python
642
star
10

nar

node.js application archive - create self-contained binary like executable applications that are ready to ship and run
LiveScript
428
star
11

rocky

Full-featured, middleware-oriented, programmatic HTTP and WebSocket proxy for node.js (deprecated)
JavaScript
371
star
12

pook

HTTP traffic mocking and testing made easy in Python
Python
329
star
13

paco

Small utility library for coroutine-driven asynchronous generic programming in Python
Python
202
star
14

semver.c

Semantic version in ANSI C
C
185
star
15

riprova

Versatile async-friendly retry package with multiple backoff strategies
Python
116
star
16

node-imaginary

Minimalist node.js command-line & programmatic API client for imaginary
JavaScript
106
star
17

youtube-video-api

Simplified programmatic and command-line interface for YouTube Video API. Built for node.js
JavaScript
67
star
18

siringa

Minimalist dependency injection library for Python that embraces type annotations syntax
Hy
54
star
19

audioconcat

Tiny node.js module to concat multiple audio files using ffmpeg
JavaScript
45
star
20

requireg

Resolve and require local & global modules in node.js like a boss
JavaScript
45
star
21

thread.js

Frictionless library to deal with multithread programming in the browser
JavaScript
41
star
22

grunt-stubby

Grunt task to setup a stub/mock server based on JSON/YAML/JS configuration files
JavaScript
26
star
23

hu

Small, generic functional helper library for node.js and browsers
wisp
20
star
24

gentleman-consul

Gentleman's plugin for Consul server discovery and optional configurable retry/backoff policies
Go
19
star
25

nightmare-google-oauth2

Nightmare plugin to retrieve a Google APIs OAuth2 token. Useful for server-to-server automation
JavaScript
19
star
26

balboa

Simple HTTP forward proxy
JavaScript
16
star
27

domlight

Spotlight DOM elements easily
JavaScript
16
star
28

resizr

Dead simple HTTP service written in Go for fast and easy image resizing from remote URLs
Go
16
star
29

google-oauth2-token

No headaches. Automation wins. Get a fresh OAuth2 token for Google APIs in just one command
JavaScript
16
star
30

angular-thread

AngularJS primitive bindings for thread.js
JavaScript
15
star
31

resilient-consul

Resilient.js middleware to use Consul for service discovery and balancing
JavaScript
14
star
32

gentleman-mock

HTTP mocking for gentleman's clients made easy. Uses gock under the hood
Go
14
star
33

rocky-consul

Rocky middleware for service discovery and dynamic traffic balancing using Consul
JavaScript
14
star
34

angular-resilient

Use $http as a resilient, failover and client-side balanced HTTP client
JavaScript
13
star
35

go-is-svg

Check if a given buffer is a valid SVG image in Go (golang)
Go
12
star
36

node-os-shim

Native OS module API shim for older node.js versions
JavaScript
12
star
37

stream-interceptor

Intercept, modify and/or ignore chunks data and events in any readable stream
JavaScript
11
star
38

gentleman-retry

gentleman's plugin providing retry policy capabilities in your HTTP clients
Go
11
star
39

bbscraper

Simple phpBB forum thread web scraper written in Python
Python
11
star
40

Sencha-WebSocket

WebSocket client abstraction library for Sencha JavaScript frameworks (DEPRECATED)
JavaScript
10
star
41

grunt-beautiful-docs

Generate beautiful markdown-based documentation using Grunt
CoffeeScript
9
star
42

findup

Find the first file matching in a current working directory or the nearest ancestor directory up to root using Go
Go
9
star
43

resolve-tree

Recursively resolve node.js modules and its dependencies looking into node_modules trees.
JavaScript
8
star
44

http-forward

Simple one-line proxy forward for incoming HTTP requests. Built for node.js/io.js
JavaScript
7
star
45

injecty

Micro library for dependency injection and inversion of control containers in node and browsers
wisp
6
star
46

sharedworkers-angular-poc

A simple proof of concept using Shared WebWorkers + Two-way data binding in AngularJS
CSS
6
star
47

toxy-ip

toxy rule to easily filter by IP addresses (supports CIDR, subnet, IP ranges...)
JavaScript
6
star
48

fw

Tiny library for asynchronous control-flow in node and browsers
wisp
6
star
49

pipefy

Transform a function into a pipeable writable stream in node/io.js
JavaScript
5
star
50

node-bintray

CLI and programmatic interface for Bintray built for node.js
CoffeeScript
5
star
51

generator-api-service

A Yeoman generator to build an opinionated but community-driven convention-focused, general purpose, resource-oriented HTTP service in node.js
JavaScript
4
star
52

htgen

Tiny hypertext markup code generator for node and browsers
LiveScript
4
star
53

node-authrc

authrc implementation for node
CoffeeScript
4
star
54

gulp-nar

Create and extract nar archives from Gulp
JavaScript
4
star
55

ng-exam

Are you a great AngularJS developer? (wip)
JavaScript
4
star
56

oml

Minimalist template engine built-on-top of the Oli language for node and browsers
JavaScript
4
star
57

buildspec

Declarative, featured, unopiniotated, CI-agnostic build configuration file
4
star
58

OPEW

[NOT MAINTAINED] OPEW is a powerful, complete, independent and extensible open source distribution stack for GNU/Linux (64 bits) based OS. Its goal is to provides a rich portable ready-to-run development environment focused on modern and robust programming languages in oder to satisfy the common needs for the web development.
Shell
4
star
59

promitto

Tiny promise library mostly compatible with Promise/A+ spec and ES6
wisp
3
star
60

heroku-buildpack-binary-download

Download and execute POSIX compatible binaries in Heroku apps
Shell
3
star
61

grunt-nar

Create and extract nar archives from Grunt
CoffeeScript
2
star
62

ASIR

ASIR course exercises for fun and profit
Shell
2
star
63

consul-cluster-test

Consul cluster test suite
Python
2
star
64

butler

A small, elegant and friendly library to deal elegantly with Service Workers (experimental)
JavaScript
2
star
65

node-cloudimage

Minimalist node/io.js CLI & programmatic stream-based interface for Cloudimage.io
JavaScript
2
star
66

mimeware

Simple node.js/io.js HTTP middleware to infer the proper MIME content type response header
JavaScript
2
star
67

bock

Browser next-generation HTTP traffic mock and proxy interceptor using Service Worker (experimental)
JavaScript
2
star
68

OPEW-bash-installer

Bash-based installer builder utility for the OPEW project
Shell
2
star
69

findup.rs

Find the first file matching in a current working directory or the nearest ancestor directory up to root
Rust
2
star
70

http-version

HTTP API version matching strategies as middleware for connect/express/rocky
JavaScript
2
star
71

nar-installer

Simple Bash script to easily install nar executable packages. Analog to npm install --global
Shell
2
star
72

http-api-versioning

Analysis of multiple HTTP API versioning design strategies
1
star
73

midware-pool

Tiny module to create a pool of connect-style domain-agnostic middleware layers in browsers and node.js
JavaScript
1
star
74

apachelog

Simple Go net/http compatible middleware for Apache style logging
Go
1
star
75

rocky-cli

Command-line interface for rocky. Supports TOML configuration file to easily set up your proxy
JavaScript
1
star
76

carcasse

Build structured, modular and object-oriented JavaScript projects
JavaScript
1
star
77

go-memstats

Human-friendly debugger to print in stdout the memory and GC stats
Go
1
star