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

Overview

gock Build Status 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 delay simulation (beta).
  • Extensible and hackable API.
  • Dependency free.

Installation

go get -u gopkg.in/h2non/gock.v1

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 (
  "github.com/nbio/st"
  "gopkg.in/h2non/gock.v1"
  "io/ioutil"
  "net/http"
  "testing"
)

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 (
  "github.com/nbio/st"
  "gopkg.in/h2non/gock.v1"
  "io/ioutil"
  "net/http"
  "testing"
)

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 (
  "github.com/nbio/st"
  "gopkg.in/h2non/gock.v1"
  "io/ioutil"
  "net/http"
  "testing"
)

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"
  "github.com/nbio/st"
  "gopkg.in/h2non/gock.v1"
  "io/ioutil"
  "net/http"
  "testing"
)

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 (
  "github.com/nbio/st"
  "gopkg.in/h2non/gock.v1"
  "io/ioutil"
  "net/http"
  "testing"
)

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"
  "gopkg.in/h2non/gock.v1"
  "io/ioutil"
  "net/http"
)

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"
	"gopkg.in/h2non/gock.v1"
	"net/http"
)

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

Comments
  • Add example for networking partially enabled

    Add example for networking partially enabled

    I have some integration tests that I would like to allow real networking for my local server. But any request from that local server should be mocked. With the current version it isn't working because the mocked request will hang up forever. Seems this is the same problem from https://github.com/h2non/gock/issues/18. And following the suggestions from that issue I could get it working. Removing the mutex.Lock makes the hanging go away. But I'm not sure this is the right solution. Although I'm also not sure mutex.Lock is really necessary in that RoundTrip. At least the real Go implementation doesn't have any mutex.Lock that I could find https://golang.org/src/net/http/transport.go?s=11576:11638#L309

    opened by maxcnunes 10
  • AddMatch

    AddMatch

    AddMatch only use once in a go program?

    package main

    import ( "fmt" "net/http" "regexp" "gopkg.in/h2non/gock.v1" )

    func test_a() { defer gock.Off()

    gock.New("http://httpbin.org").Get("/").
    	AddMatcher(func(req *http.Request, ereq *gock.Request) (bool, error) {
    	matched, err := regexp.MatchString("/aa/[A-Za-z0-9]{6}/ii/[A-Za-z0-9]{6}/calculator", req.URL.Path)
    	return matched && "GET" == req.Method, err
    }).
    	Reply(204).
    	SetHeader("Server", "gock")
    
    res, err := http.Get("http://httpbin.org/aa/123456/ii/123456/calculator")
    if err != nil {
    	fmt.Errorf("Error: %s", err)
    }
    
    fmt.Printf("Status: %d\n", res.StatusCode)
    fmt.Printf("Server header: %s\n", res.Header.Get("Server"))
    

    }

    func test_b() { defer gock.Off() gock.New("http://httpbin.org"). Get("/application"). Reply(200). SetHeader("Server", "gockbin")

    res, err := http.Get("http://httpbin.org/application")
    if err != nil {
    	fmt.Errorf("Error: %s", err)
    }
    fmt.Printf("Status: %d\n", res.StatusCode)
    fmt.Printf("Server header: %s\n", res.Header.Get("Server"))
    

    }

    func main() { test_a() test_b() }

    question 
    opened by wshelly 8
  • Is possible to enable verbose mode to see all requests which cross Gock?

    Is possible to enable verbose mode to see all requests which cross Gock?

    Hi,

    is possible to enable verbose mode to see all requests which cross Gock? If not, I suggest to add it, it is very useful to debug.

    Best regards, Stéphane

    enhancement 
    opened by harobed 7
  • gock: cannot match any request

    gock: cannot match any request

    I keep getting this error no matter what I do with this mock. This is the mock:

    gock.New("http://www.espn.com").
            Get("/nfl/player/gamelog/_/id/16733/year/2015/").
            Reply(200).
            File("testdata/espn_gamelog_2015.html")
    

    And this is the error I get: Failed to query ESPN: Get http://espn.go.com/nfl/player/gamelog/_/id/16733/year/2015/: gock: cannot match any request"

    As you can see it's the exact same URL. What's wrong?

    question 
    opened by fgblomqvist 7
  • Allow connections to an httptest Server

    Allow connections to an httptest Server

    Hi,

    I'm finding gock extremely useful, however I have a test where I need to make a real call to an httptest Server which will then spawn a couple of requests which gock should intercept. However, I can't seem to find a way to do it. I tried enabling networking and filtering, which makes it work, but it won't call the actual server, it just mocks that call, too.

    It("receives a complete trigger [DOC]", func() {
      defer gock.DisableNetworking()
      defer gock.DisableNetworkingFilters()
      gock.EnableNetworking()
      var a args
      a.Host = docServer.URL
      a.Path = "/triggers"
      a.Body = completeTrigger
      a.Method = "POST"
      a.Headers = map[string]string{
        "Authorization": "Token token=" + configuration.Config.AppToken,
        "Content-Type":  middleware.MimeType,
        "Accept":        middleware.MimeType,
      }
      gock.NetworkingFilter(func(req *http.Request) bool {
        return req.URL.String() == docServer.URL
      })
      gock.New(docServer.URL).
        Post("/triggers").
        Reply(201)
    
      // here are the actual mocks I need
    
      resp, err := a.run()
      Expect(err).ToNot(HaveOccurred())
      Expect(resp.StatusCode).To(Equal(201))
      Expect(gock.IsDone())
    })
    

    The first Expect will generate this error:

    Expected error:
        <*url.Error | 0xc4204040f0>: {
            Op: "Post",
            URL: "http://127.0.0.1:59186/triggers",
            Err: {
                s: "gock: cannot match any request",
            },
        }
        Post http://127.0.0.1:59186/triggers: gock: cannot match any request
    not to have occurred
    

    Am I missing something?

    Thanks a lot for your help!

    opened by michele 5
  • Support for custom mime types

    Support for custom mime types

    I'm having trouble trying to write a mock that matches POST requests based on the request body and the issue seems to be a result of gock being a bit too strict when it comes to validating mime types.

    From reading the source code I noticed that gock checks to see if the request content type header value matches a fixed list of supported mime types: https://github.com/h2non/gock/blob/f77fde839b2a8bd6e8de3e89f2a47a2baa1fb6ce/matchers.go#L21-L28 but the problem is that the API i'm writing a mock for uses a custom json mime type like application/vnd.apiname.v1+json, so it never matches.

    Do you have any suggestions on how I could workaround this?

    opened by cakejelly 4
  • Multiple mocks for the same path

    Multiple mocks for the same path

    package main
    
    import (
    	"fmt"
    	"gopkg.in/h2non/gock.v1"
    	"net/http"
    )
    
    func main() {
    	defer gock.Off()
    
    	gock.New("https://blah.com").Path("/path").
    		AddMatcher(func(request *http.Request, request2 *gock.Request) (b bool, e error) {
    			fmt.Println("Matcher001")
    			return false, nil
    		}).
    		Reply(200)
    
    	gock.New("https://blah.com").Path("/path").
    		AddMatcher(func(request *http.Request, request2 *gock.Request) (b bool, e error) {
    			fmt.Println("Matcher002")
    			return false, nil
    		}).
    		Reply(200)
    
    	gock.New("https://blah.com").Path("/path").
    		AddMatcher(func(request *http.Request, request2 *gock.Request) (b bool, e error) {
    			fmt.Println("FinalMatcher")
    			return true, nil
    		}).
    		Reply(200)
    
    	http.Get("https://blah.com/path")
    }
    

    Expected Output:

    Matcher001
    Matcher002
    FinalMatcher
    

    Actual Output:

    Matcher001
    Matcher001
    Matcher001
    
    opened by danny-cheung 4
  • Multiple response headers with same name are not set on http response

    Multiple response headers with same name are not set on http response

    I am trying to set multiple cookies with the same name on the gock response, but it always seems to only set the first cookie on the response object.

    Am I doing something wrong - is there a better way to set cookies?

    The mergeHeaders function appears to be the culprit. I have a solution and test here: https://github.com/steinfletcher/gock/commit/75ea39d311ffa5c435ffb9a015de2480c980ff55

    Thanks

    bug enhancement 
    opened by steinfletcher 4
  • feat(matchers): Add custom body type matcher

    feat(matchers): Add custom body type matcher

    PR to add the custom body type matcher that was proposed in https://github.com/h2non/gock/issues/87

    The logic is pretty simple - If a user passes a non-empty mime type to the BodyType function, then the Content-Type header on the http request must be the same for there to be a match. If there's no mime type passed then it falls back to the the existing logic of checking against the hardcoded list of supported mime types.

    One thing I'm a bit unsure of - I discovered MatchType and now I feel like adding this additional method will be confusing to people, since there will be two separate methods for matching based on the Content-Type header but the behaviour is different.

    @h2non Any thoughts on this?

    opened by cakejelly 3
  • Are you open to adding context expiration/cancellation support?

    Are you open to adding context expiration/cancellation support?

    Our HTTP proxy application uses contexts pretty extensively to implement timeouts. We also use (and love) gock throughout our unit tests.

    I recently added some unit tests around timeouts and noticed in the process that gock does not support context expiration or cancellation. This makes the behavior different than what you'd get using the full HTTP stack. For an example, look here: https://play.golang.org/p/rKOuNFphpBU (note that you can't run the non-gock version from the Playground)

    I looked into the code and I think adding context support is a pretty easy change in response.go. Would you be open to a PR for that?

    Thanks!

    enhancement 
    opened by wfscot 3
  • when i access the uri twice in one test, i must gock.New(Uri) twice too

    when i access the uri twice in one test, i must gock.New(Uri) twice too

    my func is

    { defer gock.Off() gock.New("https//url.com").Get("path").Reply(200) gock.New("https//url.com").Get("path").Reply(200) gock.Observe(gock.DumpRequest) // some test in the func maybe access url twice or more }

    if i use once, other access got Matches: false why

    enhancement 
    opened by seanjoe 3
  • test code with EnableNetworking does not pass through header info

    test code with EnableNetworking does not pass through header info

    Using the example in the README:

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

    The response I get is

    ➜  test go run gock.go
    Status: 201
    Server header: gunicorn/19.9.0
    Body: {
      "args": {},
      "headers": {
        "Accept-Encoding": "gzip",
        "Host": "httpbin.org",
        "User-Agent": "Go-http-client/1.1",
        "X-Amzn-Trace-Id": "Root=1-637bb59b-7debf317641b7b092a0d1887"
      },
      "origin": "64.94.4.36",
      "url": "http://httpbin.org/get"
    }
    

    Note the server header is gunicorn/19.9.0 instead of gock

    opened by domino14 0
  • TestResponderPreExpiredContext fails with go1.16 and up

    TestResponderPreExpiredContext fails with go1.16 and up

    Starting with go1.16, TestResponderPreExpiredContext fails quite often, up to 80% of the time on my computer:

    --- FAIL: TestResponderPreExpiredContext (0.00s)
        st.go:41: 
            responder_test.go:118: should be == 
             	have: (<nil>) <nil>
            	want: (context.deadlineExceededError) context deadline exceeded
        st.go:41: 
            responder_test.go:119: should be == 
             	have: (bool) false
            	want: (bool) true
    

    With go1.15, TestResponderPreExpiredContext seemingly never fails.

    Tested with gock.v1 v1.1.2 and the newer commit cd5aaaacd302f278fae7cbe9747fa56c859016fe on Debian sid.

    opened by anthonyfok 0
  • Mocking InsecureSkipVerify requests

    Mocking InsecureSkipVerify requests

    If i attempt to mock the following request it does not work. However, if I change client to the following it passes. Any idea what I'm doing wrong?

    client := &http.Client{}
    
    gock.New("https://0.0.0.0").
            Post("/api/auth/token/login/").
            MatchHeader("Content-Type", "application/json; chartset=UTF-8").
            JSON(map[string]string{"foo": "bar"}).
            Reply(200).
            BodyString(`{"foo": "foo"}`)
    
    body := bytes.NewBuffer([]byte(`{"foo":"bar"}`))
    tr := &http.Transport{
            TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    
    client := &http.Client{Transport: tr}
    req, err := http.NewRequest("POST", "https://0.0.0.0/api/auth/token/login/", body)
    req.Header.Set("Content-Type", "application/json; chartset=UTF-8")
    resp, err := client.Do(req)
    if err != nil {
            fmt.Printf("error building request: %v", err)
    }
    

    Error is:

    error building request: Post "https://0.0.0.0/api/auth/token/login/": dial tcp 0.0.0.0:443: connect: connection refused
    
    opened by retr0h 1
  • gock issue while mocking Prometheus with URL escaped query parameters

    gock issue while mocking Prometheus with URL escaped query parameters

    It seems there is an issue while mocking Prometheus URLs with gock. Prometheus URLs contain a query which is written in PromQL. The resulting URLs look similar to http://localhost:9090/api/v1/query?query=scalar(anyMetric)

    This test fails as long as the MatchParam() is present in Line 18 in main_test.go

    // file : main.go
    
    package main
    
    import (
    	"log"
    	"net/http"
    	"net/url"
    )
    
    func main() {
    
    	err := fetchMetrics()
    	log.Println(err)
    }
    
    func fetchMetrics() error {
    	promURL := &url.URL{
    		Scheme: "http",
    		Host:   "prometheus-k8s.monitoring:9090",
    		Path:   "/api/v1/query",
    	}
    	q := promURL.Query()
    	q.Set("query", "scalar(testMetric)")
    	promURL.RawQuery = q.Encode()
    
    	resp, err := http.Get(promURL.String())
    	if err != nil || resp.StatusCode != http.StatusOK {
    		return err
    	}
    
    	return nil
    }
    
    // file : main_test.go
    
    package main
    
    import (
    	"log"
    	"net/url"
    	"testing"
    
    	"gopkg.in/h2non/gock.v1"
    )
    
    func TestFetchMetrics(t *testing.T) {
    	defer gock.Off()
    
    	promQuery := "scalar(testMetric)"
    
    	gock.New("http://prometheus-k8s.monitoring:9090").
    		Get("/api/v1/query").
    		MatchParam("query", url.QueryEscape(promQuery)).
    		// MatchParam("query", promQuery).
    		Reply(200)
    
    	err := fetchMetrics()
    	if err != nil {
    		log.Println(err)
    		t.Fail()
    	}
    
    }
    

    I tried passing promQuery variable as a normal string as well as a URL encoded string but the test fails in both the scenarios. Test command -

    go test -count 1 -v .
    

    Is this a issue due to gock ?

    opened by Ahmad-Faizan 0
  • Mocked response with 301 status code and location header returns an error

    Mocked response with 301 status code and location header returns an error

    When I mocked a response just with 301 status code, I got an error with a message: 301 response missing Location header. After adding the location header, there was another error with a message: gock: cannot match any request.

    The code is shown as below:

    
    import (
    	"net/http"
    	"testing"
    
    	"github.com/stretchr/testify/assert"
    	"gopkg.in/h2non/gock.v1"
    )
    
    func TestWithLocationHeader(t *testing.T) {
    	defer gock.Off()
    
    	gock.New("https://domain.com").
    		Get("/path").
    		Reply(301).
    		SetHeader("Location", "https://domain.com/newpath")
    
    	_, err := http.Get("https://domain.com/path")
    
    	assert.Equal(t, "Get \"https://domain.com/newpath\": gock: cannot match any request", err.Error())
    }
    
    func TestWithoutLocationHeader(t *testing.T) {
    	defer gock.Off()
    
    	gock.New("https://domain.com").
    		Get("/path").
    		Reply(301)
    
    	_, err := http.Get("https://domain.com/path")
    
    	assert.Equal(t, "Get \"https://domain.com/path\": 301 response missing Location header", err.Error())
    }
    
    opened by wxm112 0
  • How to test google api using gock?

    How to test google api using gock?

    Hi, I am working with Google Analytics API , and need to create unit testing for that using gock. Is it possible?

    how to mock this part ?? analyticsService, _ := analytics.NewService(ctx, option.WithCredentialsJSON(cred))

    it asks me to put the real private key on Credential JSON or I will get this following error: private key should be a PEM or plain PKCS1 or PKCS8; parse error: asn1: structure error: tags don't match (16 vs {class:0 tag:8 length:1214 isCompound:true}) {optional:false explicit:false application:false private:false defaultValue:<nil> tag:<nil> stringType:0 timeType:0 set:false omitEmpty:false} pkcs1PrivateKey

    Thank you.

    opened by layla004 0
Releases(v1.2.0)
  • v1.2.0(Oct 20, 2022)

  • v1.1.2(Aug 3, 2021)

  • v1.1.1(Jul 14, 2021)

  • v1.1.0(Jun 2, 2021)

  • v1.0.16(Nov 23, 2020)

  • v1.0.15(Jul 3, 2019)

    v1.0.15 / 2019-07-03

    • NewMatcher() will now return objects that completely separate one another. (#55)
    • add request Options (#49)
    • fix typo: function -> func (#52)
    • feat(docs): change note
    • feat(docs): add net/http support
    • Add Basic Auth (#47)
    • Update LICENSE (#46)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.14(Jan 31, 2019)

  • v1.0.12(Nov 13, 2018)

  • v1.0.11(Oct 29, 2018)

    v1.0.11 / 2018-10-29

    • Do not reset response body (#40)
    • refactor(travis): remove unsupported versions for golint based on Go release policy support
    • feat(gock): add gock.Observe to support inspection of the outgoing intercepted HTTP traffic (#38)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.10(Sep 9, 2018)

  • v1.0.9(Jun 14, 2018)

  • v1.0.8(Feb 28, 2018)

    Changes

    v1.0.8 / 2018-02-28

    • chore(LICENSE): update year ;)
    • feat(docs): add additional tips and examples
    • feat(gock): ignore already intercepted http.Client
    Source code(tar.gz)
    Source code(zip)
  • v1.0.7(Dec 21, 2017)

    Changes

    • Make MatchHost case insensitive. (#31)
    • refactor(docs): remove codesponsor :(
    • add example when request reply with error (#28)
    • feat(docs): add sponsor ad
    • Add example networking partially enabled (#23)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.6(Jul 28, 2017)

  • v1.0.5(Jul 26, 2017)

    Changes

    v1.0.5 / 2017-07-26

    • feat(#25, #24): use content type only if missing while matching JSON/XML
    • feat(#24): add CleanUnmatchedRequests() and OffAll() public functions
    • feat(version): bump to v1.0.5
    • fix(store): use proper indent style
    • fix(mutex): use different mutex for store
    • feat(travis): add Go 1.8 CI support
    Source code(tar.gz)
    Source code(zip)
  • v1.0.4(Feb 14, 2017)

    v1.0.4 / 2017-02-14

    • Update README to include most up to date version (#17)
    • Update MatchBody() to compare if key + value pairs of JSON match regardless of order they are in. (#16)
    • feat(examples): add new example for unmatch case
    • refactor(docs): add pook reference
    Source code(tar.gz)
    Source code(zip)
  • v1.0.3(Nov 17, 2016)

  • v1.0.1(Sep 7, 2016)

Full-featured test framework for Go! Assertions, mocking, input testing, output capturing, and much more! 🍕

testza ?? Testza is like pizza for Go - you could life without it, but why should you? Get The Module | Documentation | Contributing | Code of Conduct

Marvin Wendt 408 Nov 15, 2022
A simple and expressive HTTP server mocking library for end-to-end tests in Go.

mockhttp A simple and expressive HTTP server mocking library for end-to-end tests in Go. Installation go get -d github.com/americanas-go/mockhttp Exa

Americanas Go 6 Dec 19, 2021
Database testing made easy in Go.

dbtest Database testing made easy in Go. Features Declarative Define the minimum test specification in a YAML-based DSL, then all tests can be generat

Luo Peng 19 Oct 31, 2022
HTTP mocking for Golang

httpmock Easy mocking of http responses from external resources. Install Currently supports Go 1.7 - 1.15. v1 branch has to be used instead of master.

Jared Morse 1.5k Nov 19, 2022
HTTP mocking to test API services for chaos scenarios

GAOS HTTP mocking to test API services for chaos scenarios Gaos, can create and provide custom mock restful services via using your fully-customizable

Trendyol Open Source 211 Nov 5, 2022
Lightweight HTTP mocking in Go (aka golang)

httpmock This library builds on Go's built-in httptest library, adding a more mockable interface that can be used easily with other mocking tools like

null 78 Nov 2, 2022
Go Interface Mocking Tool

Charlatan Percolate's Go Interface Mocking Tool. Please read our introductory blog post. Installation go get github.com/percolate/charlatan Usage c

Percolate 199 Nov 3, 2022
GoMock is a mocking framework for the Go programming language.

gomock GoMock is a mocking framework for the Go programming language. It integrates well with Go's built-in testing package, but can be used in other

Go 8.2k Nov 27, 2022
A clipboard-based mocking framework for Go that gets out of your way.

A clipboard-based mocking framework for Go that gets out of your way. This tool has been built with inspiration lovingly taken from Moq, and fuelled b

Roger Guldbrandsen 41 Nov 18, 2022
Interface mocking tool for go generate

Interface mocking tool for go generate. What is Moq? Moq is a tool that generates a struct from any interface. The struct can be used in test code as

Mat Ryer 1.4k Nov 22, 2022
HTTP mock for Golang: record and replay HTTP/HTTPS interactions for offline testing

govcr A Word Of Warning I'm in the process of partly rewriting govcr to offer better support for cassette mutations. This is necessary because when I

Seb C 137 Nov 18, 2022
siusiu (suite-suite harmonics) a suite used to manage the suite, designed to free penetration testing engineers from learning and using various security tools, reducing the time and effort spent by penetration testing engineers on installing tools, remembering how to use tools.

siusiu (suite-suite harmonics) a suite used to manage the suite, designed to free penetration testing engineers from learning and using various security tools, reducing the time and effort spent by penetration testing engineers on installing tools, remembering how to use tools.

Re 290 Nov 26, 2022
A yaml data-driven testing format together with golang testing library

Specimen Yaml-based data-driven testing Specimen is a yaml data format for data-driven testing. This enforces separation between feature being tested

Design it, Run it 1 Nov 24, 2022
Quick and Easy server testing/validation

Goss - Quick and Easy server validation Goss in 45 seconds Note: For an even faster way of doing this, see: autoadd Note: For testing docker container

Simon Bäumer 26 Oct 7, 2022
Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

go-testdeep Extremely flexible golang deep comparison, extends the go testing package. Latest news Synopsis Description Installation Functions Availab

Maxime Soulé 329 Nov 26, 2022
End-to-end HTTP and REST API testing for Go.

httpexpect Concise, declarative, and easy to use end-to-end HTTP and REST API testing for Go (golang). Basically, httpexpect is a set of chainable bui

Victor Gaydov 2k Nov 24, 2022
HTTP load testing tool and library. It's over 9000!

Vegeta Vegeta is a versatile HTTP load testing tool built out of a need to drill HTTP services with a constant request rate. It can be used both as a

Tomás Senart 20.5k Nov 23, 2022
Golang HTTP client testing framework

flute Golang HTTP client testing framework Presentation https://speakerdeck.com/szksh/flute-golang-http-client-testing-framework Overview flute is the

Shunsuke Suzuki 17 Sep 27, 2022
Ditto is a CLI testing tool that helps you verify if multiple HTTP endpoints have the same outputs.

Ditto is a CLI testing tool that helps you verify if multiple HTTP endpoints have the same outputs.

Cristopher 1 Nov 24, 2021