Skip to content

Commit

Permalink
Use the mock for the URL with query if none matched specifically with…
Browse files Browse the repository at this point in the history
… the params
  • Loading branch information
norkans7 committed Feb 15, 2024
1 parent 219c5e9 commit e3317dd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
6 changes: 6 additions & 0 deletions httpx/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
"strings"

"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/stringsx"
Expand Down Expand Up @@ -43,6 +44,11 @@ func (r *MockRequestor) Do(client *http.Client, request *http.Request) (*http.Re

// find the most specific match against this URL
match := stringsx.GlobSelect(url, maps.Keys(r.mocks)...)

// no match, try again ignoring the URL params
if match == "" {
match = stringsx.GlobSelect(strings.Trim(url, "?"+request.URL.RawQuery), maps.Keys(r.mocks)...)
}
mockedResponses := r.mocks[match]

if len(mockedResponses) == 0 {
Expand Down
16 changes: 12 additions & 4 deletions httpx/mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ func TestMockRequestor(t *testing.T) {
server.URL + "/thing": {
httpx.NewMockResponse(205, nil, []byte("this is local")),
},
"http://example.com": {
httpx.NewMockResponse(200, nil, []byte("this should match ignoring the params requested")),
},
})

httpx.SetRequestor(requestor1)
Expand Down Expand Up @@ -95,17 +98,22 @@ func TestMockRequestor(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, 204, response.StatusCode)

req8, _ := http.NewRequest("GET", "http://example.com?id=1&active=yes", nil)
response, err = httpx.Do(http.DefaultClient, req8, nil, nil)
assert.NoError(t, err)
assert.Equal(t, 200, response.StatusCode)

assert.False(t, requestor1.HasUnused())

// panic if we've run out of mocks for a URL
req8, _ := http.NewRequest("GET", "http://google.com", nil)
assert.Panics(t, func() { httpx.Do(http.DefaultClient, req8, nil, nil) })
req9, _ := http.NewRequest("GET", "http://google.com", nil)
assert.Panics(t, func() { httpx.Do(http.DefaultClient, req9, nil, nil) })

requestor1.SetIgnoreLocal(true)

// now a request to the local server should actually get there
req9, _ := http.NewRequest("GET", server.URL+"/thing", nil)
response, err = httpx.Do(http.DefaultClient, req9, nil, nil)
req10, _ := http.NewRequest("GET", server.URL+"/thing", nil)
response, err = httpx.Do(http.DefaultClient, req10, nil, nil)
assert.NoError(t, err)
assert.Equal(t, 200, response.StatusCode)
}
Expand Down

0 comments on commit e3317dd

Please sign in to comment.