Skip to content

Instantly share code, notes, and snippets.

@temirov
Created October 9, 2018 19:46
Show Gist options
  • Save temirov/d7292663b10d93d40b7584af8c6928b1 to your computer and use it in GitHub Desktop.
Save temirov/d7292663b10d93d40b7584af8c6928b1 to your computer and use it in GitHub Desktop.
ServiceApi test
package serviceapi_test
import (
"lib/serviceapi"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
const (
address = ":8081"
cr = "\n"
)
type TestCase struct {
status int
expectedResponse string
handler func(http.ResponseWriter, *http.Request)
uri string
}
var cases = []TestCase{
TestCase{
status: http.StatusFound,
expectedResponse: "<a href=\"" + serviceapi.HealthCheckPath + "\">Found</a>.\n" + cr,
handler: serviceapi.Root,
uri: serviceapi.RootPath,
},
TestCase{
status: http.StatusOK,
expectedResponse: serviceapi.PingResponse + cr,
handler: serviceapi.Ping,
uri: serviceapi.PingPath,
},
TestCase{
status: http.StatusOK,
expectedResponse: serviceapi.OkResponse + cr,
handler: serviceapi.HealthCheck,
uri: serviceapi.HealthCheckPath,
},
TestCase{
status: http.StatusNotFound,
expectedResponse: "404 page not found" + cr,
handler: serviceapi.Root,
uri: serviceapi.RootPath + "unknown",
},
}
func check(e error) {
if e != nil {
panic(e)
}
}
func TestServiceApiHandles(t *testing.T) {
for _, item := range cases {
request, err := http.NewRequest("GET", item.uri, nil)
check(err)
recorder := httptest.NewRecorder()
handler := http.HandlerFunc(item.handler)
handler.ServeHTTP(recorder, request)
if recorder.Code != item.status {
t.Errorf("wrong status code: got %v want %v for %#v", recorder.Code, item.status, item)
}
if recorder.Body.String() != item.expectedResponse {
t.Errorf("unexpected body: got %v want %v for %#v", recorder.Body.String(), item.expectedResponse, item)
}
}
}
func TestServeMux(t *testing.T) {
server := httptest.NewServer(serviceapi.Handlers())
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
for _, item := range cases {
url := server.URL + item.uri
request, err := http.NewRequest("GET", url, nil)
check(err)
response, err := client.Do(request)
check(err)
defer func() {
err := response.Body.Close()
check(err)
}()
if response.StatusCode != item.status {
t.Errorf("wrong status code: got %v want %v for %#v", response.StatusCode, item.status, item)
}
bodyBytes, err := ioutil.ReadAll(response.Body)
check(err)
if bodyString := string(bodyBytes); bodyString != item.expectedResponse {
t.Errorf("unexpected body: got %v want %v for %#v", bodyString, item.expectedResponse, item)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment