Skip to content

Instantly share code, notes, and snippets.

@mindon
Last active May 17, 2018 10:39
Show Gist options
  • Select an option

  • Save mindon/7f3189dc306cd7f28a2d1f953055a925 to your computer and use it in GitHub Desktop.

Select an option

Save mindon/7f3189dc306cd7f28a2d1f953055a925 to your computer and use it in GitHub Desktop.
A helper func for http request testing
// http request testing helper
// author: Mindon Feng <mindon@gmail.com>
// site: https://mindon.github.io
package mindon
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
// request verify helper
func _verifyResp(targetUri string, cond *bytes.Buffer, hdl http.HandlerFunc, expected interface{}) error {
method := "GET"
if cond.Len() > 0 {
method = "POST"
}
req, err := http.NewRequest(method, targetUri, cond)
if err != nil {
return err
}
w := httptest.NewRecorder()
hdl(w, req)
resp := w.Result()
raw, _ := ioutil.ReadAll(resp.Body)
body := string(raw)
switch expected.(type) {
case int:
if status := w.Code; status != expected.(int) {
return errors.New(fmt.Sprintf("request status code: got %d want %d\n%s",
status, expected.(int), targetUri))
}
return nil
}
if status := w.Code; status != http.StatusOK {
// fmt.Println(body)
return errors.New(fmt.Sprintf("request status code: got %d want %d\n%s",
status, http.StatusOK, targetUri))
}
switch expected.(type) {
case string:
if body != expected.(string) {
return errors.New(fmt.Sprintf("unexpected body: got %v want %v",
body, expected))
}
case func(string) error:
return expected.(func(string) error)(body)
case func(string, http.Header) error:
return expected.(func(string, http.Header) error)(body, w.Header())
default:
}
return nil
}
func hdlTobeTesting(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("okay"))
}
func hdl500(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Testing 500", http.StatusInternalServerError)
}
func TestDemo(t *testing.T) {
cond := bytes.Buffer{}
err := _verifyResp("hello/mindon", &cond, hdlTobeTesting, "okay")
if err != nil {
t.Fatal(err)
}
err := _verifyResp("hello/mindon", &cond, hdl500, http.StatusInternalServerError)
if err != nil {
t.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment