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

Different JSON array body matches #81

Open
stevenferrer opened this issue Jan 27, 2021 · 1 comment
Open

Different JSON array body matches #81

stevenferrer opened this issue Jan 27, 2021 · 1 comment
Labels

Comments

@stevenferrer
Copy link

stevenferrer commented Jan 27, 2021

First, thank you for making this amazing project!

I've noticed that when I try to match a request body that is an array, the requests are still matching even though the mock and request body are clearly different.

baseURL := "http://foo.com"
gock.New(baseURL).
    Post("/bar").
    MatchType("json").
    BodyString(`[{"foo":"bar"},{"fizz":"buzz"}]`).
    Reply(http.StatusOK).
    JSON(map[string]interface{})

req, _ := http.NewRequest(http.MethodPost, baseURL+"/bar", bytes.NewBuffer([]byte(`[{"foo":"baz"}]`)))
res, err := http.DefaultClient.Do(req)

On the code, before getting into the lines where the json.Unmarshal is called, I've noticed that the matcher already returns true in the regexp.MatchString part.

I've tried to come-up with a fix, but it seems that it's gonna be difficult without knowing whether the request body contains regular expressions or just a normal JSON.

@h2non h2non added the question label Jan 28, 2021
@denysvitali
Copy link

I just noticed the same and was confused for a second.

My input:

Request Body

{"data": {"a": "b"}}

Expected Body

{"a": "b"}

The issue happens here:

gock/matchers.go

Lines 188 to 198 in 48ac21d

bodyStr := castToString(body)
matchStr := castToString(ereq.BodyBuffer)
if bodyStr == matchStr {
return true, nil
}
// Match request body by regexp
match, _ := regexp.MatchString(matchStr, bodyStr)
if match == true {
return true, nil
}

bodyStr has value of {"data": {"a": "b"}}
matchStr has a value of {"a": "b"}

This sadly makes the request match, and thus makes some of my tests pass although they should fail with an unmatched request error :(

I would suggest to not match the body by regex, at all, unless the user really wants to (maybe we can create a method for that, like MatchBodyRegex or similar.

Having a MatchBody method that sneakly does regex matching is error prone and can cause huge issues, especially in such an important mocking library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants