Skip to content

Instantly share code, notes, and snippets.

@SteveBate
Last active August 29, 2015 14:16
Show Gist options
  • Save SteveBate/bb5e77deb635dfa24290 to your computer and use it in GitHub Desktop.
Save SteveBate/bb5e77deb635dfa24290 to your computer and use it in GitHub Desktop.
Simplifying testing in Go via a few help functions
// Given a simple web server sample:
func main() {
config := "this is some config"
http.Handle("/", HandleDefaultRoute(config))
http.ListenAndServe(":8080", nil)
}
func HandleDefaultRoute(config string) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if config == "" {
rw.WriteHeader(http.StatusBadRequest)
return
}
rw.Write([]byte(config))
}
}
// We can write small, easy to read tests:
func Test_default_route_with_valid_config(t *testing.T) {
respRec, req := NewRecordabelGetRequest(t, "/")
HandleDefaultRoute("this is a test")(respRec, req)
equals(t, http.StatusOK, respRec.Code)
}
func Test_default_route_with_invalid_config(t *testing.T) {
respRec, req := NewRecordabelGetRequest(t, "/")
HandleDefaultRoute("")(respRec, req)
equals(t, http.StatusBadRequest, respRec.Code)
}
// Using some utility functions as described below:
func NewRecordabelGetRequest(t *testing.T, route string) (*httptest.ResponseRecorder, *http.Request) {
respRec := httptest.NewRecorder()
req, err := http.NewRequest("GET", route, nil)
if err != nil {
t.Fatal(err)
}
return respRec, req
}
func NewRecordabelPostRequest(t *testing.T, route string, dto interface{}) (*httptest.ResponseRecorder, *http.Request) {
b := make([]byte, 0)
buf := bytes.NewBuffer(b)
json.NewEncoder(buf).Encode(&dto)
respRec := httptest.NewRecorder()
req, err := http.NewRequest("POST", route, buf)
if err != nil {
t.Fatal(err)
}
return respRec, req
}
// assert fails the test if the condition is false.
func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
if !condition {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
tb.FailNow()
}
}
// ok fails the test if an err is not nil.
func ok(tb testing.TB, err error) {
if err != nil {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
tb.FailNow()
}
}
// equals fails the test if exp is not equal to act.
func equals(tb testing.TB, exp, act interface{}) {
if !reflect.DeepEqual(exp, act) {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
tb.FailNow()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment