{"id":13367094,"url":"https://github.com/h2non/Gock","last_synced_at":"2025-03-12T18:31:51.841Z","repository":{"id":39422323,"uuid":"52977552","full_name":"h2non/gock","owner":"h2non","description":"HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽","archived":false,"fork":false,"pushed_at":"2024-09-24T10:01:06.000Z","size":196,"stargazers_count":2147,"open_issues_count":44,"forks_count":109,"subscribers_count":20,"default_branch":"master","last_synced_at":"2025-03-11T23:01:37.012Z","etag":null,"topics":["api","assertions","expectations","go","http","http-api","http-server","http-transactions","https","interception","mock","mocking","stubs","testing"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/h2non/gock","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/h2non.png","metadata":{"files":{"readme":"README.md","changelog":"History.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-03-02T16:20:26.000Z","updated_at":"2025-03-09T18:41:53.000Z","dependencies_parsed_at":"2023-12-28T19:37:44.812Z","dependency_job_id":"99796a8c-0d3c-46f4-a7c9-42100cdb91a5","html_url":"https://github.com/h2non/gock","commit_stats":{"total_commits":184,"total_committers":29,"mean_commits":6.344827586206897,"dds":"0.17934782608695654","last_synced_commit":"076e53961a8cfd552f8048c6e8ab580af96c2721"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/h2non%2Fgock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/h2non%2Fgock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/h2non%2Fgock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/h2non%2Fgock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/h2non","download_url":"https://codeload.github.com/h2non/gock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243271418,"owners_count":20264454,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","assertions","expectations","go","http","http-api","http-server","http-transactions","https","interception","mock","mocking","stubs","testing"],"created_at":"2024-07-30T00:01:38.485Z","updated_at":"2025-03-12T18:31:51.795Z","avatar_url":"https://github.com/h2non.png","language":"Go","readme":"# gock [![GitHub release](https://img.shields.io/badge/version-v1.0-orange.svg?style=flat)](https://github.com/h2non/gock/releases) [![GoDoc](https://godoc.org/github.com/h2non/gock?status.svg)](https://godoc.org/github.com/h2non/gock) [![Coverage Status](https://coveralls.io/repos/github/h2non/gock/badge.svg?branch=master)](https://coveralls.io/github/h2non/gock?branch=master) [![Go Report Card](https://img.shields.io/badge/go_report-A+-brightgreen.svg)](https://goreportcard.com/report/github.com/h2non/gock) [![license](https://img.shields.io/badge/license-MIT-blue.svg)]()\n\nVersatile HTTP mocking made easy in [Go](https://golang.org) that works with any `net/http` based stdlib implementation.\n\nHeavily inspired by [nock](https://github.com/node-nock/nock).\nThere is also its Python port, [pook](https://github.com/h2non/pook).\n\nTo get started, take a look to the [examples](#examples).\n\n## Features\n\n- Simple, expressive, fluent API.\n- Semantic API DSL for declarative HTTP mock declarations.\n- Built-in helpers for easy JSON/XML mocking.\n- Supports persistent and volatile TTL-limited mocks.\n- Full regular expressions capable HTTP request mock matching.\n- Designed for both testing and runtime scenarios.\n- Match request by method, URL params, headers and bodies.\n- Extensible and pluggable HTTP matching rules.\n- Ability to switch between mock and real networking modes.\n- Ability to filter/map HTTP requests for accurate mock matching.\n- Supports map and filters to handle mocks easily.\n- Wide compatible HTTP interceptor using `http.RoundTripper` interface.\n- Works with any `net/http` compatible client, such as [gentleman](https://github.com/h2non/gentleman).\n- Network timeout/cancelation delay simulation.\n- Extensible and hackable API.\n- Dependency free.\n\n## Installation\n\n```bash\ngo get -u github.com/h2non/gock\n```\n\n## API\n\nSee [godoc reference](https://godoc.org/github.com/h2non/gock) for detailed API documentation.\n\n## How it mocks\n\n1. Intercepts any HTTP outgoing request via `http.DefaultTransport` or custom `http.Transport` used by any `http.Client`.\n2. Matches outgoing HTTP requests against a pool of defined HTTP mock expectations in FIFO declaration order.\n3. If at least one mock matches, it will be used in order to compose the mock HTTP response.\n4. 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.\n\n## Tips\n\n#### Testing\n\nDeclare your mocks before you start declaring the concrete test logic:\n\n```go\nfunc TestFoo(t *testing.T) {\n  defer gock.Off() // Flush pending mocks after test execution\n\n  gock.New(\"http://server.com\").\n    Get(\"/bar\").\n    Reply(200).\n    JSON(map[string]string{\"foo\": \"bar\"})\n\n  // Your test code starts here...\n}\n```\n\n#### Race conditions\n\nIf you're running concurrent code, be aware that your mocks are declared first to avoid unexpected\nrace conditions while configuring `gock` or intercepting custom HTTP clients.\n\n`gock` is not fully thread-safe, but sensible parts are.\nAny help making `gock` more reliable in this sense is appreciated.\n\n#### Define complex mocks first\n\nIf you're mocking a bunch of mocks in the same test suite, it's recommended to define the more\nconcrete mocks first, and then the generic ones.\n\nThis approach usually avoids matching unexpected generic mocks (e.g: specific header, body payload...) instead of the generic ones that performs less complex matches.\n\n#### Disable `gock` traffic interception once done\n\nIn other to minimize potential side effects within your test code, it's a good practice\ndisabling `gock` once you are done with your HTTP testing logic.\n\nA Go idiomatic approach for doing this can be using it in a `defer` statement, such as:\n\n```go\nfunc TestGock (t *testing.T) {\n\tdefer gock.Off()\n\n\t// ... my test code goes here\n}\n```\n\n#### Intercept an `http.Client` just once\n\nYou don't need to intercept multiple times the same `http.Client` instance.\n\nJust call `gock.InterceptClient(client)` once, typically at the beginning of your test scenarios.\n\n#### Restore an `http.Client` after interception\n\n**NOTE**: this is not required is you are using `http.DefaultClient` or `http.DefaultTransport`.\n\nAs a good testing pattern, you should call `gock.RestoreClient(client)` after running your test scenario, typically as after clean up hook.\n\nYou can also use a `defer` statement for doing it, as you do with `gock.Off()`, such as:\n\n```go\nfunc TestGock (t *testing.T) {\n\tdefer gock.Off()\n\tdefer gock.RestoreClient(client)\n\n\t// ... my test code goes here\n}\n```\n\n## Examples\n\nSee [examples](https://github.com/h2non/gock/tree/master/_examples) directory for more featured use cases.\n\n#### Simple mocking via tests\n\n```go\npackage test\n\nimport (\n  \"io/ioutil\"\n  \"net/http\"\n  \"testing\"\n\n  \"github.com/nbio/st\"\n  \"github.com/h2non/gock\"\n)\n\nfunc TestSimple(t *testing.T) {\n  defer gock.Off()\n\n  gock.New(\"http://foo.com\").\n    Get(\"/bar\").\n    Reply(200).\n    JSON(map[string]string{\"foo\": \"bar\"})\n\n  res, err := http.Get(\"http://foo.com/bar\")\n  st.Expect(t, err, nil)\n  st.Expect(t, res.StatusCode, 200)\n\n  body, _ := ioutil.ReadAll(res.Body)\n  st.Expect(t, string(body)[:13], `{\"foo\":\"bar\"}`)\n\n  // Verify that we don't have pending mocks\n  st.Expect(t, gock.IsDone(), true)\n}\n```\n\n#### Request headers matching\n\n```go\npackage test\n\nimport (\n  \"io/ioutil\"\n  \"net/http\"\n  \"testing\"\n\n  \"github.com/nbio/st\"\n  \"github.com/h2non/gock\"\n)\n\nfunc TestMatchHeaders(t *testing.T) {\n  defer gock.Off()\n\n  gock.New(\"http://foo.com\").\n    MatchHeader(\"Authorization\", \"^foo bar$\").\n    MatchHeader(\"API\", \"1.[0-9]+\").\n    HeaderPresent(\"Accept\").\n    Reply(200).\n    BodyString(\"foo foo\")\n\n  req, err := http.NewRequest(\"GET\", \"http://foo.com\", nil)\n  req.Header.Set(\"Authorization\", \"foo bar\")\n  req.Header.Set(\"API\", \"1.0\")\n  req.Header.Set(\"Accept\", \"text/plain\")\n\n  res, err := (\u0026http.Client{}).Do(req)\n  st.Expect(t, err, nil)\n  st.Expect(t, res.StatusCode, 200)\n  body, _ := ioutil.ReadAll(res.Body)\n  st.Expect(t, string(body), \"foo foo\")\n\n  // Verify that we don't have pending mocks\n  st.Expect(t, gock.IsDone(), true)\n}\n```\n\n#### Request param matching\n\n```go\npackage test\n\nimport (\n  \"io/ioutil\"\n  \"net/http\"\n  \"testing\"\n\n  \"github.com/nbio/st\"\n  \"github.com/h2non/gock\"\n)\n\nfunc TestMatchParams(t *testing.T) {\n  defer gock.Off()\n\n  gock.New(\"http://foo.com\").\n    MatchParam(\"page\", \"1\").\n    MatchParam(\"per_page\", \"10\").\n    Reply(200).\n    BodyString(\"foo foo\")\n\n  req, err := http.NewRequest(\"GET\", \"http://foo.com?page=1\u0026per_page=10\", nil)\n\n  res, err := (\u0026http.Client{}).Do(req)\n  st.Expect(t, err, nil)\n  st.Expect(t, res.StatusCode, 200)\n  body, _ := ioutil.ReadAll(res.Body)\n  st.Expect(t, string(body), \"foo foo\")\n\n  // Verify that we don't have pending mocks\n  st.Expect(t, gock.IsDone(), true)\n}\n```\n\n#### JSON body matching and response\n\n```go\npackage test\n\nimport (\n  \"bytes\"\n  \"io/ioutil\"\n  \"net/http\"\n  \"testing\"\n\t\n\t\"github.com/nbio/st\"\n  \"github.com/h2non/gock\"\n)\n\nfunc TestMockSimple(t *testing.T) {\n  defer gock.Off()\n\n  gock.New(\"http://foo.com\").\n    Post(\"/bar\").\n    MatchType(\"json\").\n    JSON(map[string]string{\"foo\": \"bar\"}).\n    Reply(201).\n    JSON(map[string]string{\"bar\": \"foo\"})\n\n  body := bytes.NewBuffer([]byte(`{\"foo\":\"bar\"}`))\n  res, err := http.Post(\"http://foo.com/bar\", \"application/json\", body)\n  st.Expect(t, err, nil)\n  st.Expect(t, res.StatusCode, 201)\n\n  resBody, _ := ioutil.ReadAll(res.Body)\n  st.Expect(t, string(resBody)[:13], `{\"bar\":\"foo\"}`)\n\n  // Verify that we don't have pending mocks\n  st.Expect(t, gock.IsDone(), true)\n}\n```\n\n#### Mocking a custom http.Client and http.RoundTripper\n\n```go\npackage test\n\nimport (\n  \"io/ioutil\"\n  \"net/http\"\n  \"testing\"\n\n  \"github.com/nbio/st\"\n  \"github.com/h2non/gock\"\n)\n\nfunc TestClient(t *testing.T) {\n  defer gock.Off()\n\n  gock.New(\"http://foo.com\").\n    Reply(200).\n    BodyString(\"foo foo\")\n\n  req, err := http.NewRequest(\"GET\", \"http://foo.com\", nil)\n  client := \u0026http.Client{Transport: \u0026http.Transport{}}\n  gock.InterceptClient(client)\n\n  res, err := client.Do(req)\n  st.Expect(t, err, nil)\n  st.Expect(t, res.StatusCode, 200)\n  body, _ := ioutil.ReadAll(res.Body)\n  st.Expect(t, string(body), \"foo foo\")\n\n  // Verify that we don't have pending mocks\n  st.Expect(t, gock.IsDone(), true)\n}\n```\n\n#### Enable real networking\n\n```go\npackage main\n\nimport (\n  \"fmt\"\n  \"io/ioutil\"\n  \"net/http\"\n\n  \"github.com/h2non/gock\"\n)\n\nfunc main() {\n  defer gock.Off()\n  defer gock.DisableNetworking()\n\n  gock.EnableNetworking()\n  gock.New(\"http://httpbin.org\").\n    Get(\"/get\").\n    Reply(201).\n    SetHeader(\"Server\", \"gock\")\n\n  res, err := http.Get(\"http://httpbin.org/get\")\n  if err != nil {\n    fmt.Errorf(\"Error: %s\", err)\n  }\n\n  // The response status comes from the mock\n  fmt.Printf(\"Status: %d\\n\", res.StatusCode)\n  // The server header comes from mock as well\n  fmt.Printf(\"Server header: %s\\n\", res.Header.Get(\"Server\"))\n  // Response body is the original\n  body, _ := ioutil.ReadAll(res.Body)\n  fmt.Printf(\"Body: %s\", string(body))\n}\n```\n\n#### Debug intercepted http requests\n\n```go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\n  \"github.com/h2non/gock\"\n)\n\nfunc main() {\n\tdefer gock.Off()\n\tgock.Observe(gock.DumpRequest)\n\n\tgock.New(\"http://foo.com\").\n\t\tPost(\"/bar\").\n\t\tMatchType(\"json\").\n\t\tJSON(map[string]string{\"foo\": \"bar\"}).\n\t\tReply(200)\n\n\tbody := bytes.NewBuffer([]byte(`{\"foo\":\"bar\"}`))\n\thttp.Post(\"http://foo.com/bar\", \"application/json\", body)\n}\n\n```\n\n## Hacking it!\n\nYou can easily hack `gock` defining custom matcher functions with own matching rules.\n\nSee [add matcher functions](https://github.com/h2non/gock/blob/master/_examples/add_matchers/matchers.go) and [custom matching layer](https://github.com/h2non/gock/blob/master/_examples/custom_matcher/matcher.go) examples for further details.\n\n## License\n\nMIT - Tomas Aparicio\n","funding_links":[],"categories":["测试","測試"],"sub_categories":["高级控制台界面","高級控制台界面"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fh2non%2FGock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fh2non%2FGock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fh2non%2FGock/lists"}