Skip to content

Commit

Permalink
up: update some for testutil
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Apr 23, 2020
1 parent ef504a6 commit fbb4103
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
27 changes: 21 additions & 6 deletions testutil/httpmock.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"strings"
)

// some data.
Expand All @@ -12,10 +13,12 @@ type (
M map[string]string
// MD simple request data
MD struct {
// Body body
Body io.Reader
// Headers headers
Headers M
// Body body. eg: strings.NewReader("name=inhere")
Body io.Reader
// BodyString quick add body.
BodyString string
// BeforeSend callback
BeforeSend func(req *http.Request)
}
Expand All @@ -25,13 +28,25 @@ type (
// Usage:
// handler := router.New()
// res := MockRequest(handler, "GET", "/path", nil)
// // with data
// // with data 1
// body := strings.NewReader("string ...")
// res := MockRequest(handler, "POST", "/path", &MD{Body: "data", Headers: M{"x-head": "val"}})
// res := MockRequest(handler, "POST", "/path", &MD{
// Body: body,
// Headers: M{"x-head": "val"}
// })
// // with data 2
// res := MockRequest(handler, "POST", "/path", &MD{
// BodyString: "data string",
// Headers: M{"x-head": "val"}
// })
func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder {
var body io.Reader
if data != nil && data.Body != nil {
body = data.Body
if data != nil {
if data.Body != nil {
body = data.Body
} else if data.BodyString != "" {
body = strings.NewReader(data.BodyString)
}
}

// create fake request
Expand Down
17 changes: 15 additions & 2 deletions testutil/httpmock_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package testutil_test

import (
"io/ioutil"
"net/http"
"strings"
"testing"

"github.com/gookit/goutil/testutil"
Expand All @@ -11,9 +13,20 @@ import (
func TestMockRequest(t *testing.T) {
r := http.NewServeMux()
r.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("hello"))
_, _ = w.Write([]byte("hello!"))

if r.Body != nil {
bs, _ := ioutil.ReadAll(r.Body)
_, _ = w.Write(bs)
}
}))

w := testutil.MockRequest(r, "GET", "/", nil)
assert.Equal(t, "hello", w.Body.String())
assert.Equal(t, "hello!", w.Body.String())

w = testutil.MockRequest(r, "POST", "/", &testutil.MD{BodyString: "body"})
assert.Equal(t, "hello!body", w.Body.String())

w = testutil.MockRequest(r, "POST", "/", &testutil.MD{Body: strings.NewReader("BODY")})
assert.Equal(t, "hello!BODY", w.Body.String())
}

0 comments on commit fbb4103

Please sign in to comment.