Skip to content

Commit

Permalink
Support r.URL.Host in host matcher
Browse files Browse the repository at this point in the history
Previously, only r.Host from the incoming request was used to match
the expected mock host. This change supports r.URL.Host if r.Host
is not present.

Go http client docs specifies that both are valid:

```
For client requests Host optionally overrides the Host
header to send. If empty, the Request.Write method uses
the value of URL.Host. Host may contain an international
domain name.
```
  • Loading branch information
webbgeorge committed Mar 7, 2019
1 parent d2178ca commit 123bb44
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 123bb44

Please sign in to comment.