Skip to content

Commit

Permalink
Merge branch 'main' into post-serve-actions
Browse files Browse the repository at this point in the history
  • Loading branch information
walkerus authored Aug 10, 2023
2 parents f61a83a + 5556269 commit e90f641
Show file tree
Hide file tree
Showing 15 changed files with 754 additions and 388 deletions.
80 changes: 44 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
# go-wiremock

[![Actions Status](https://github.com/walkerus/go-wiremock/workflows/build/badge.svg)](https://github.com/walkerus/go-wiremock/actions?query=workflow%3Abuild)
[![Go Report Card](https://goreportcard.com/badge/github.com/walkerus/go-wiremock)](https://goreportcard.com/report/github.com/walkerus/go-wiremock)

The simple package to stub HTTP resource using [WireMock admin](http://wiremock.org/docs/api/)

## Documentation

[![GoDoc](https://godoc.org/github.com/walkerus/go-wiremock?status.svg)](http://godoc.org/github.com/walkerus/go-wiremock)

## Usage

```shell
docker run -it --rm -p 8080:8080 wiremock/wiremock
```

```go
package main

import (
"net/http"
"testing"

"github.com/walkerus/go-wiremock"
Expand All @@ -23,60 +28,63 @@ import (
func TestSome(t *testing.T) {
wiremockClient := wiremock.NewClient("http://0.0.0.0:8080")
defer wiremockClient.Reset()

// stubbing POST http://0.0.0.0:8080/example
wiremockClient.StubFor(wiremock.Post(wiremock.URLPathEqualTo("/example")).
WithQueryParam("firstName", wiremock.EqualTo("Jhon")).
WithQueryParam("lastName", wiremock.NotMatching("Black")).
WithBodyPattern(wiremock.EqualToJson(`{"meta": "information"}`)).
WithHeader("x-session", wiremock.Matching("^\\S+fingerprint\\S+$")).
WillReturnJSON(
map[string]interface{}{
"code": 400,
WithQueryParam("firstName", wiremock.EqualTo("John")).
WithQueryParam("lastName", wiremock.NotMatching("Black")).
WithBodyPattern(wiremock.EqualToJson(`{"meta": "information"}`)).
WithHeader("x-session", wiremock.Matching("^\\S+fingerprint\\S+$")).
WillReturnResponse(
wiremock.NewResponse().
WithJSONBody(map[string]interface{}{
"code": 400,
"detail": "detail",
},
map[string]string{"Content-Type": "application/json"},
400,
).
AtPriority(1))
}).
WithHeader("Content-Type", "application/json").
WithStatus(http.StatusBadRequest),
).
AtPriority(1))

// scenario
defer wiremockClient.ResetAllScenarios()
wiremockClient.StubFor(wiremock.Get(wiremock.URLPathEqualTo("/status")).
WillReturnJSON(
map[string]interface{}{
"status": nil,
},
map[string]string{"Content-Type": "application/json"},
200,
).
InScenario("Set status").
WillReturnResponse(
wiremock.NewResponse().
WithJSONBody(map[string]interface{}{
"status": nil,
}).
WithHeader("Content-Type", "application/json").
WithStatus(http.StatusOK),
).
InScenario("Set status").
WhenScenarioStateIs(wiremock.ScenarioStateStarted))

wiremockClient.StubFor(wiremock.Post(wiremock.URLPathEqualTo("/state")).
WithBodyPattern(wiremock.EqualToJson(`{"status": "started"}`)).
InScenario("Set status").
WillSetStateTo("Status started"))
WithBodyPattern(wiremock.EqualToJson(`{"status": "started"}`)).
InScenario("Set status").
WillSetStateTo("Status started"))

statusStub := wiremock.Get(wiremock.URLPathEqualTo("/status")).
WillReturnJSON(
map[string]interface{}{
"status": "started",
},
map[string]string{"Content-Type": "application/json"},
200,
).
InScenario("Set status").
WhenScenarioStateIs("Status started")
WillReturnResponse(
wiremock.NewResponse().
WithJSONBody(map[string]interface{}{
"status": "started",
}).
WithHeader("Content-Type", "application/json").
WithStatus(http.StatusOK),
).
InScenario("Set status").
WhenScenarioStateIs("Status started")
wiremockClient.StubFor(statusStub)

//testing code...

verifyResult, _ := wiremockClient.Verify(statusStub.Request(), 1)
if !verifyResult {
//...
//...
}

wiremockClient.DeleteStub(statusStub)
}
```
12 changes: 6 additions & 6 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
)

Expand Down Expand Up @@ -37,7 +37,7 @@ func (c *Client) StubFor(stubRule *StubRule) error {
defer res.Body.Close()

if res.StatusCode != http.StatusCreated {
bodyBytes, err := ioutil.ReadAll(res.Body)
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("read response error: %s", err.Error())
}
Expand Down Expand Up @@ -77,7 +77,7 @@ func (c *Client) Reset() error {
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(res.Body)
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("read response error: %s", err.Error())
}
Expand All @@ -97,7 +97,7 @@ func (c *Client) ResetAllScenarios() error {
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(res.Body)
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("read response error: %s", err.Error())
}
Expand All @@ -121,7 +121,7 @@ func (c *Client) GetCountRequests(r *Request) (int64, error) {
}
defer res.Body.Close()

bodyBytes, err := ioutil.ReadAll(res.Body)
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
return 0, fmt.Errorf("get count requests: read response error: %s", err.Error())
}
Expand Down Expand Up @@ -167,7 +167,7 @@ func (c *Client) DeleteStubByID(id string) error {
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(res.Body)
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("read response error: %s", err.Error())
}
Expand Down
25 changes: 18 additions & 7 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package wiremock
import (
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"testing"
Expand All @@ -22,9 +23,14 @@ func TestStubRule_ToJson(t *testing.T) {
}

postStubRule := Post(URLPathEqualTo("/example")).
WithQueryParam("firstName", EqualTo("Jhon")).
WithHost(EqualTo("localhost")).
WithScheme("http").
WithPort(8080).
WithQueryParam("firstName", EqualTo("John").Or(EqualTo("Jack"))).
WithQueryParam("lastName", NotMatching("Black")).
WithQueryParam("nickname", EqualToIgnoreCase("jhonBlack")).
WithQueryParam("nickname", EqualToIgnoreCase("johnBlack")).
WithQueryParam("address", Includes(EqualTo("1"), Contains("2"), NotContains("3"))).
WithQueryParam("id", Contains("1").And(NotContains("2"))).
WithBodyPattern(EqualToJson(`{"meta": "information"}`, IgnoreArrayOrder, IgnoreExtraElements)).
WithBodyPattern(Contains("information")).
WithMultipartPattern(
Expand All @@ -38,17 +44,19 @@ func TestStubRule_ToJson(t *testing.T) {
WithCookie("absentcookie", Absent()).
WithHeader("x-session", Matching("^\\S+@\\S+$")).
WithCookie("session", EqualToXml("<xml>")).
WillReturn(
`{"code": 400, "detail": "detail"}`,
map[string]string{"Content-Type": "application/json"},
400,
WillReturnResponse(
NewResponse().
WithStatus(http.StatusBadRequest).
WithHeader("Content-Type", "application/json").
WithBody(`{"code": 400, "detail": "detail"}`).
WithFault(FaultConnectionResetByPeer).
WithFixedDelay(time.Second * 5),
).
WithPostServeAction("webhook", Webhook().
WithMethod("POST").
WithURL("http://my-target-host/callback").
WithHeader("Content-Type", "application/json").
WithBody(`{ "result": "SUCCESS" }`)).
WithFixedDelayMilliseconds(time.Second * 5).
AtPriority(1).
InScenario("Scenario").
WhenScenarioStateIs("Started").
Expand All @@ -58,15 +66,18 @@ func TestStubRule_ToJson(t *testing.T) {
if err != nil {
t.Fatalf("failed to read expected-template.json %v", err)
}

rawResult, err := json.Marshal(postStubRule)
if err != nil {
t.Fatalf("StubRole json.Marshal error: %v", err)
}

var expected map[string]interface{}
err = json.Unmarshal([]byte(fmt.Sprintf(string(rawExpectedRequestBody), postStubRule.uuid, postStubRule.uuid)), &expected)
if err != nil {
t.Fatalf("StubRole json.Unmarshal error: %v", err)
}

var parsedResult map[string]interface{}
err = json.Unmarshal(rawResult, &parsedResult)
if err != nil {
Expand Down
58 changes: 58 additions & 0 deletions delay.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package wiremock

import "encoding/json"

type DelayInterface interface {
ParseDelay() map[string]interface{}
}

type fixedDelay struct {
milliseconds int64
}

func (d fixedDelay) ParseDelay() map[string]interface{} {
return map[string]interface{}{
"type": "fixed",
"milliseconds": d.milliseconds,
}
}

type logNormalRandomDelay struct {
median int64
sigma float64
}

func (d logNormalRandomDelay) ParseDelay() map[string]interface{} {
return map[string]interface{}{
"type": "lognormal",
"median": d.median,
"sigma": d.sigma,
}
}

type uniformRandomDelay struct {
lower int64
upper int64
}

func (d uniformRandomDelay) ParseDelay() map[string]interface{} {
return map[string]interface{}{
"type": "uniform",
"lower": d.lower,
"upper": d.upper,
}
}

type chunkedDribbleDelay struct {
numberOfChunks int64
totalDuration int64
}

func (d chunkedDribbleDelay) MarshalJSON() ([]byte, error) {
jsonMap := map[string]interface{}{
"numberOfChunks": d.numberOfChunks,
"totalDuration": d.totalDuration,
}

return json.Marshal(jsonMap)
}
14 changes: 7 additions & 7 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Some might consider it a service virtualization tool or a mock server.
HTTP request:
POST /example?firstName=Jhon&lastName=Any string other than "Gray" HTTP/1.1
POST /example?firstName=John&lastName=Any string other than "Gray" HTTP/1.1
Host: 0.0.0.0:8080
x-session: somefingerprintsome
Content-Type: application/json
Expand All @@ -26,14 +26,15 @@ Stub:
client := wiremock.NewClient("http://0.0.0.0:8080")
client.StubFor(wiremock.Post(wiremock.URLPathEqualTo("/example")).
WithQueryParam("firstName", wiremock.EqualTo("Jhon")).
WithQueryParam("firstName", wiremock.EqualTo("John")).
WithQueryParam("lastName", wiremock.NotMatching("Gray")).
WithBodyPattern(wiremock.EqualToJson(`{"meta": "information"}`)).
WithHeader("x-session", wiremock.Matching("^\\S+fingerprint\\S+$")).
WillReturn(
`{"code": 400, "detail": "detail"}`,
map[string]string{"Content-Type": "application/json"},
400,
WillReturnResponse(
wiremock.NewResponse().
WithStatus(http.StatusBadRequest).
WithHeader("Content-Type", "application/json").
WithBody(`{"code": 400, "detail": "detail"}`),
).
AtPriority(1))
Expand Down Expand Up @@ -61,6 +62,5 @@ You can verify if a request has been made that matches the mapping.
client.StubFor(exampleStubRule)
// ...
client.Verify(exampleStubRule.Request(), 1)
*/
package wiremock
Loading

0 comments on commit e90f641

Please sign in to comment.