Skip to content

Commit

Permalink
Merge pull request #27 from steinfletcher/feature/support-url-host-in…
Browse files Browse the repository at this point in the history
…-matcher

Support r.URL.Host in host matcher
  • Loading branch information
steinfletcher authored Mar 7, 2019
2 parents d2178ca + 123bb44 commit e24e986
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
3 changes: 3 additions & 0 deletions mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,9 @@ var pathMatcher Matcher = func(r *http.Request, spec *MockRequest) error {

var hostMatcher Matcher = func(r *http.Request, spec *MockRequest) error {
receivedHost := r.Host
if receivedHost == "" {
receivedHost = r.URL.Host
}
mockHost := spec.url.Host
if mockHost == "" {
return nil
Expand Down
38 changes: 29 additions & 9 deletions mocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -54,19 +55,38 @@ func TestMocks_NewEmptyUnmatchedMockError_ExpectedErrorsString(t *testing.T) {
}

func TestMocks_HostMatcher(t *testing.T) {
tests := []struct {
requestUrl string
tests := map[string]struct {
request *http.Request
mockUrl string
expectedError error
}{
{"http://test.com", "https://test.com", nil},
{"https://test.com", "https://testa.com", errors.New("received host test.com did not match mock host testa.com")},
{"https://test.com", "", nil},
"matching": {
request: httptest.NewRequest(http.MethodGet, "http://test.com", nil),
mockUrl: "https://test.com",
expectedError: nil,
},
"not matching": {
request: httptest.NewRequest(http.MethodGet, "https://test.com", nil),
mockUrl: "https://testa.com",
expectedError: errors.New("received host test.com did not match mock host testa.com"),
},
"no expected host": {
request: httptest.NewRequest(http.MethodGet, "https://test.com", nil),
mockUrl: "",
expectedError: nil,
},
"matching using URL host": {
request: &http.Request{URL: &url.URL{
Host: "test.com",
Path: "/",
}},
mockUrl: "https://test.com",
expectedError: nil,
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("%s %s", test.requestUrl, test.mockUrl), func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, test.requestUrl, nil)
matchError := hostMatcher(req, NewMock().Get(test.mockUrl))
for name, test := range tests {
t.Run(name, func(t *testing.T) {
matchError := hostMatcher(test.request, NewMock().Get(test.mockUrl))
assert.Equal(t, test.expectedError, matchError)
})
}
Expand Down

0 comments on commit e24e986

Please sign in to comment.