Skip to content

Commit

Permalink
added HandlerTestCaseFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
kyokomi committed Oct 21, 2015
1 parent 6c97fb6 commit 1b4e289
Show file tree
Hide file tree
Showing 4 changed files with 159 additions and 42 deletions.
69 changes: 53 additions & 16 deletions hhth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"io"
"net/http"
"net/http/httptest"

"net/url"
)

Expand All @@ -16,37 +15,47 @@ type HTTPHandlerTestHelper interface {
SetHeader(key, value string)
SetForm(key, value string)

AddTestCase(testCases ...HandlerTestCase)
SetTestCase(testCases ...HandlerTestCase)
AddTestCaseFunc(testCases ...HandlerTestCaseFunc)
SetTestCaseFunc(testCaseFunc ...HandlerTestCaseFunc)

// method
Get(urlStr string, testCases ...HandlerTestCase) Response
Post(urlStr string, bodyType string, body io.Reader, testCases ...HandlerTestCase) Response
Get(urlStr string, testCases ...HandlerTestCaseFunc) Response
Post(urlStr string, bodyType string, body io.Reader, testCases ...HandlerTestCaseFunc) Response
}

var _ HTTPHandlerTestHelper = (*httpHandlerTestHelper)(nil)

func New(handler http.Handler) HTTPHandlerTestHelper {
return &httpHandlerTestHelper{
handler: handler,
headers: map[string]string{},
form: map[string]string{},

method: "",
url: "",
headers: map[string]string{},
form: map[string]string{},
testCases: []HandlerTestCase{},
}
}

type httpHandlerTestHelper struct {
handler http.Handler

method string
url string
headers map[string]string
form map[string]string
method string
url string
headers map[string]string
form map[string]string
testCases []HandlerTestCase
}

func (h *httpHandlerTestHelper) Get(urlStr string, testCases ...HandlerTestCase) Response {
func (h *httpHandlerTestHelper) Get(urlStr string, testCases ...HandlerTestCaseFunc) Response {
h.method = "GET"
h.url = urlStr
return h.do(nil, testCases...)
}

func (h *httpHandlerTestHelper) Post(urlStr string, bodyType string, body io.Reader, testCases ...HandlerTestCase) Response {
func (h *httpHandlerTestHelper) Post(urlStr string, bodyType string, body io.Reader, testCases ...HandlerTestCaseFunc) Response {
h.method = "POST"
h.url = urlStr
h.SetHeader("Content-Type", bodyType)
Expand All @@ -61,11 +70,33 @@ func (h *httpHandlerTestHelper) SetForm(key, value string) {
h.form[key] = value
}

func (h *httpHandlerTestHelper) do(body io.Reader, testCases ...HandlerTestCase) *response {
func (h *httpHandlerTestHelper) SetTestCase(testCases ...HandlerTestCase) {
h.testCases = testCases
}

func (h *httpHandlerTestHelper) AddTestCase(testCases ...HandlerTestCase) {
h.testCases = append(h.testCases, testCases...)
}

func (h *httpHandlerTestHelper) SetTestCaseFunc(testCaseFunc ...HandlerTestCaseFunc) {
dst := make([]HandlerTestCase, len(testCaseFunc))
for idx, tf := range testCaseFunc {
dst[idx] = HandlerTestCase(tf)
}
h.testCases = dst
}

func (h *httpHandlerTestHelper) AddTestCaseFunc(testCaseFunc ...HandlerTestCaseFunc) {
for _, tf := range testCaseFunc {
h.testCases = append(h.testCases, HandlerTestCase(tf))
}
}

func (h *httpHandlerTestHelper) do(body io.Reader, testCases ...HandlerTestCaseFunc) Response {
resp := httptest.NewRecorder()
req, err := http.NewRequest(h.method, h.url, body)
if err != nil {
return &response{err: err, response: nil}
return NewErrorResponse(err)
}

if req.Form == nil {
Expand All @@ -82,11 +113,17 @@ func (h *httpHandlerTestHelper) do(body io.Reader, testCases ...HandlerTestCase)

h.handler.ServeHTTP(resp, req)

for _, testCase := range testCases {
execTestCases := make([]HandlerTestCase, len(h.testCases), len(h.testCases)+len(testCases))
copy(execTestCases, h.testCases)
for idx, tc := range testCases {
execTestCases[idx+len(h.testCases)-1] = HandlerTestCase(tc)
}

for _, testCase := range execTestCases {
if err := testCase.Execute(resp); err != nil {
return &response{err: err, response: nil}
return NewErrorResponse(err)
}
}

return &response{err: nil, response: resp}
return NewResponse(resp)
}
117 changes: 91 additions & 26 deletions hhth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,62 +7,80 @@ import (
"net/url"
"testing"

"net/http/httptest"

"github.com/kyokomi/hhth"
)

func TestHogeHandler(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)

resp := hhtHelper.Get("/hoge",
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("text/plain; charset=utf-8"),
hhth.TestCaseContentLength(len("hogehoge")),
)

resp := hhtHelper.Get("/hoge")
if resp.Error() != nil {
t.Errorf("error %s", resp.Error())
}
fmt.Println(resp.String())
}

func TestError(t *testing.T) {
func TestErrorStatusCode(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)

respError1 := hhtHelper.Get("/hoge",
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusFound), // error
hhth.TestCaseContentType("text/plain; charset=utf-8"),
hhth.TestCaseContentLength(len("hogehoge")),
)
respError1 := hhtHelper.Get("/hoge")
if respError1.Error() == nil {
t.Error("error not error")
} else {
t.Logf("OK %s", respError1.Error())
}
}

respError2 := hhtHelper.Get("/hoge",
func TestErrorContentType(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("application/json; charset=UTF-8"), // error
hhth.TestCaseContentLength(len("hogehoge")),
)

respError2 := hhtHelper.Get("/hoge")
if respError2.Error() == nil {
t.Error("error not error")
} else {
t.Logf("OK %s", respError2.Error())
}

respError3 := hhtHelper.Get("/hoge",
}
func TestErrorContentLength(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("text/plain; charset=utf-8"),
hhth.TestCaseContentLength(len("hogehogeaaaaa")), // error
)

respError3 := hhtHelper.Get("/hoge")
if respError3.Error() == nil {
t.Error("error not error")
} else {
t.Logf("OK %s", respError3.Error())
}
}

func TestHogeJSONHandler(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)

resp := hhtHelper.Get("/hoge.json",
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("application/json; charset=UTF-8"),
)

resp := hhtHelper.Get("/hoge.json")
if resp.Error() != nil {
t.Errorf("error %s", resp.Error())
}
Expand All @@ -77,13 +95,13 @@ func TestHogeJSONHandler(t *testing.T) {

func TestHogeHeaderHandler(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)

hhtHelper.SetHeader("X-App-Hoge", "hoge-header")

resp := hhtHelper.Get("/header",
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("text/plain; charset=utf-8"),
)
hhtHelper.SetHeader("X-App-Hoge", "hoge-header")

resp := hhtHelper.Get("/header")
if resp.Error() != nil {
t.Errorf("error %s", resp.Error())
}
Expand All @@ -92,15 +110,17 @@ func TestHogeHeaderHandler(t *testing.T) {

func TestPostHandler(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("text/plain; charset=utf-8"),
)

formData := url.Values{}
formData.Set("name", "hoge")
formData.Set("age", "19")

resp := hhtHelper.Post("/post", "application/x-www-form-urlencoded",
bytes.NewBufferString(formData.Encode()),
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("text/plain; charset=utf-8"),
)
if resp.Error() != nil {
t.Errorf("error %s", resp.Error())
Expand All @@ -110,13 +130,14 @@ func TestPostHandler(t *testing.T) {

func TestGetFormHandler(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)

hhtHelper.SetForm("name", "hoge")

resp := hhtHelper.Get("/get-form",
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
hhth.TestCaseContentType("text/plain; charset=utf-8"),
)

hhtHelper.SetForm("name", "hoge")

resp := hhtHelper.Get("/get-form")
if resp.Error() != nil {
t.Errorf("error %s", resp.Error())
}
Expand Down Expand Up @@ -158,6 +179,49 @@ func TestJSONParseError(t *testing.T) {
}
}

func TestCustomTestCase(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)
hhtHelper.SetTestCase(
hhth.TestCaseStatusCode(http.StatusOK),
)
hhtHelper.AddTestCase(hhth.TestCaseContentType("text/plain; charset=utf-8"))

resp := hhtHelper.Get("/hoge")
if resp.Error() != nil {
t.Errorf("error %s", resp.Error())
}
fmt.Println(resp.String())
}

func TestCustomTestCaseFunc(t *testing.T) {
hhtHelper := hhth.New(http.DefaultServeMux)
hhtHelper.SetTestCaseFunc(
func(resp *httptest.ResponseRecorder) error {
if resp.Header().Get("X-Hoge-Version") != "1.0.0" {
return fmt.Errorf("error header version %s", resp.Header().Get("X-Hoge-Version"))
}
return nil
},
)
hhtHelper.AddTestCaseFunc(func(resp *httptest.ResponseRecorder) error {
if resp.Header().Get("Content-Type") != "text/plain; charset=utf-8" {
return fmt.Errorf("error header Content-Type %s", resp.Header().Get("Content-Type"))
}
return nil
})

resp := hhtHelper.Get("/hoge", func(resp *httptest.ResponseRecorder) error {
if resp.Code != http.StatusOK {
return fmt.Errorf("error http code %d", resp.Code)
}
return nil
})
if resp.Error() != nil {
t.Errorf("error %s", resp.Error())
}
fmt.Println(resp.String())
}

func init() {
http.HandleFunc("/hoge", hogeHandler)
http.HandleFunc("/hoge.json", hogeJSONHandler)
Expand All @@ -174,7 +238,8 @@ func hogeHandler(w http.ResponseWriter, r *http.Request) {
}

w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Hoge-Version", "1.0.0")
w.Write([]byte("hogehoge"))
}

Expand All @@ -190,7 +255,7 @@ func getFormHandler(w http.ResponseWriter, r *http.Request) {
}

w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("get-form"))
}

Expand All @@ -201,7 +266,7 @@ func hogeJSONHandler(w http.ResponseWriter, r *http.Request) {
}

w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write([]byte(`{"name": "hogehoge", "age": 20}`))
}

Expand All @@ -212,7 +277,7 @@ func errorJSONHandler(w http.ResponseWriter, r *http.Request) {
}

w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write([]byte(`{"name": "hogehoge", "age": 20`)) // json parse error
}

Expand All @@ -229,7 +294,7 @@ func headerHandler(w http.ResponseWriter, r *http.Request) {
}

w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("header ok " + xAppHoge))
}

Expand All @@ -250,7 +315,7 @@ func postHandler(w http.ResponseWriter, r *http.Request) {
}

w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("post ok " + r.PostForm.Encode()))
}

Expand Down
8 changes: 8 additions & 0 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ type Response interface {
JSON(v interface{}) error
}

func NewResponse(resp *httptest.ResponseRecorder) Response {
return &response{err: nil, response: resp}
}

func NewErrorResponse(err error) Response {
return &response{err: err, response: nil}
}

type response struct {
err error
response *httptest.ResponseRecorder
Expand Down
Loading

0 comments on commit 1b4e289

Please sign in to comment.