Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support unmatched requests and clear request log #7

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ 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")).
Expand All @@ -40,12 +40,12 @@ func TestSome(t *testing.T) {
// scenario
defer wiremockClient.ResetAllScenarios()
wiremockClient.StubFor(wiremock.Get(wiremock.URLPathEqualTo("/status")).
WillReturn(
`{"status": null}`,
map[string]string{"Content-Type": "application/json"},
200,
).
InScenario("Set status").
WillReturn(
`{"status": null}`,
map[string]string{"Content-Type": "application/json"},
200,
).
InScenario("Set status").
WhenScenarioStateIs(wiremock.ScenarioStateStarted))

wiremockClient.StubFor(wiremock.Post(wiremock.URLPathEqualTo("/state")).
Expand All @@ -54,22 +54,22 @@ func TestSome(t *testing.T) {
WillSetStateTo("Status started"))

statusStub := wiremock.Get(wiremock.URLPathEqualTo("/status")).
WillReturn(
`{"status": "started"}`,
map[string]string{"Content-Type": "application/json"},
200,
).
InScenario("Set status").
WhenScenarioStateIs("Status started")
WillReturn(
`{"status": "started"}`,
map[string]string{"Content-Type": "application/json"},
200,
).
InScenario("Set status").
WhenScenarioStateIs("Status started")
wiremockClient.StubFor(statusStub)

//testing code...

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

wiremockClient.DeleteStub(statusStub)
}
```
```
51 changes: 50 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func (c *Client) StubFor(stubRule *StubRule) error {
func (c *Client) Clear() error {
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/%s", c.url, wiremockAdminMappingsURN), nil)
if err != nil {
return fmt.Errorf("build cleare Request error: %s", err.Error())
return fmt.Errorf("build clear Request error: %s", err.Error())
}

res, err := (&http.Client{}).Do(req)
Expand Down Expand Up @@ -88,6 +88,26 @@ func (c *Client) Reset() error {
return nil
}

// ClearRequests resets the request log.
func (c *Client) ClearRequests() error {
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/%s/requests", c.url, wiremockAdminURN), nil)
if err != nil {
return fmt.Errorf("reset request log: Request error: %s", err.Error())
}

res, err := (&http.Client{}).Do(req)
if err != nil {
return fmt.Errorf("clear request log: Request error: %s", err.Error())
}
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
return fmt.Errorf("clear request log: bad response status: %d", res.StatusCode)
}

return nil
}

// ResetAllScenarios resets back to start of the state of all configured scenarios.
func (c *Client) ResetAllScenarios() error {
res, err := http.Post(fmt.Sprintf("%s/%s/scenarios/reset", c.url, wiremockAdminURN), "application/json", nil)
Expand Down Expand Up @@ -152,6 +172,35 @@ func (c *Client) Verify(r *Request, expectedCount int64) (bool, error) {
return actualCount == expectedCount, nil
}

// UnmatchedRequests returns the number of requests that didn't match any stub.
func (c *Client) UnmatchedRequests() (int, error) {
res, err := http.Get(fmt.Sprintf("%s/%s/requests/unmatched", c.url, wiremockAdminURN))
if err != nil {
return 0, fmt.Errorf("unmatched requests: %s", err.Error())
}
defer res.Body.Close()

bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return 0, fmt.Errorf("unmatched requests: read response error: %s", err.Error())
}

if res.StatusCode != http.StatusOK {
return 0, fmt.Errorf("unmatched requests: bad response status: %d, response: %s", res.StatusCode, string(bodyBytes))
}

var unmatchedRequestsResponse struct {
Requests []interface{}
}

err = json.Unmarshal(bodyBytes, &unmatchedRequestsResponse)
if err != nil {
return 0, fmt.Errorf("unmatched requests: read json error: %s", err.Error())
}

return len(unmatchedRequestsResponse.Requests), nil
}

// DeleteStubByID deletes stub by id.
func (c *Client) DeleteStubByID(id string) error {
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/%s/%s", c.url, wiremockAdminMappingsURN, id), nil)
Expand Down
9 changes: 9 additions & 0 deletions stub_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type URLMatcherInterface interface {
type response struct {
body string
headers map[string]string
transformers []string
status int64
fixedDelayMilliseconds time.Duration
}
Expand Down Expand Up @@ -101,6 +102,12 @@ func (s *StubRule) WithBasicAuth(username, password string) *StubRule {
return s
}

// WithTransformers adds transformers, enabling the use of templates in reply body
func (s *StubRule) WithTransformers(transformers ...string) *StubRule {
s.response.transformers = transformers
return s
}

// AtPriority sets priority and returns *StubRule
func (s *StubRule) AtPriority(priority int64) *StubRule {
s.priority = &priority
Expand Down Expand Up @@ -168,6 +175,7 @@ func (s *StubRule) MarshalJSON() ([]byte, error) {
Response struct {
Body string `json:"body,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Transformers []string `json:"transformers,omitempty"`
Status int64 `json:"status,omitempty"`
FixedDelayMilliseconds int `json:"fixedDelayMilliseconds,omitempty"`
} `json:"response"`
Expand All @@ -178,6 +186,7 @@ func (s *StubRule) MarshalJSON() ([]byte, error) {
jsonStubRule.NewScenarioState = s.newScenarioState
jsonStubRule.Response.Body = s.response.body
jsonStubRule.Response.Headers = s.response.headers
jsonStubRule.Response.Transformers = s.response.transformers
jsonStubRule.Response.Status = s.response.status
jsonStubRule.Response.FixedDelayMilliseconds = int(s.response.fixedDelayMilliseconds.Milliseconds())
jsonStubRule.Request = s.request
Expand Down