Skip to content

Commit

Permalink
feat(matchers): Support custom MIME types
Browse files Browse the repository at this point in the history
  • Loading branch information
cakejelly committed Jul 6, 2021
1 parent f77fde8 commit ce9d2d4
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
9 changes: 7 additions & 2 deletions matchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func MatchBody(req *http.Request, ereq *Request) (bool, error) {
}

// Only can match certain MIME body types
if !supportedType(req) {
if !supportedType(req, ereq) {
return false, nil
}

Expand Down Expand Up @@ -214,12 +214,17 @@ func MatchBody(req *http.Request, ereq *Request) (bool, error) {
return false, nil
}

func supportedType(req *http.Request) bool {
func supportedType(req *http.Request, ereq *Request) bool {
mime := req.Header.Get("Content-Type")
if mime == "" {
return true
}

mimeToMatch := ereq.Header.Get("Content-Type")
if mimeToMatch != "" {
return mime == mimeToMatch
}

for _, kind := range BodyTypes {
if match, _ := regexp.MatchString(kind, mime); match {
return true
Expand Down
27 changes: 27 additions & 0 deletions matchers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,30 @@ func TestMatchBody(t *testing.T) {
st.Expect(t, matches, test.matches)
}
}

func TestMatchBody_MatchType(t *testing.T) {
body := `{"foo":"bar"}`
cases := []struct {
body string
requestContentType string
customBodyType string
matches bool
}{
{body, "application/vnd.apiname.v1+json", "foobar", false},
{body, "application/vnd.apiname.v1+json", "application/vnd.apiname.v1+json", true},
{body, "application/json", "foobar", false},
{body, "application/json", "", true},
{"", "", "", true},
}

for _, test := range cases {
req := &http.Request{
Header: http.Header{"Content-Type": []string{test.requestContentType}},
Body: createReadCloser([]byte(test.body)),
}
ereq := NewRequest().BodyString(test.body).MatchType(test.customBodyType)
matches, err := MatchBody(req, ereq)
st.Expect(t, err, nil)
st.Expect(t, matches, test.matches)
}
}
2 changes: 1 addition & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func (r *Request) XML(data interface{}) *Request {
}

// MatchType defines the request Content-Type MIME header field.
// Supports type alias. E.g: json, xml, form, text...
// Supports custom MIME types and type aliases. E.g: json, xml, form, text...
func (r *Request) MatchType(kind string) *Request {
mime := BodyTypeAliases[kind]
if mime != "" {
Expand Down

0 comments on commit ce9d2d4

Please sign in to comment.