func TestFitToSize(t *testing.T) { service := &img.Service{ Reader: &readerMock{}, Processor: &resizerMock{}, } test.Service = service.FitToSizeUrl testCases := []test.TestCase{ {"http://localhost/fit?url=http://site.com/img.png&size=300x200", http.StatusOK, "Success", func(w *httptest.ResponseRecorder, t *testing.T) { if w.Header().Get("Cache-Control") != "public, max-age=86400" { t.Errorf("Expected to get Cache-Control header") } if w.Header().Get("Content-Length") != "3" { t.Errorf("Expected to get Content-Length header equal to 3 but got [%s]", w.Header().Get("Content-Length")) } }}, {"http://localhost/fit?size=300x200", http.StatusBadRequest, "Param url is required", nil}, {"http://localhost/fit?url=http://site.com/img.png", http.StatusBadRequest, "Param size is required", nil}, {"http://localhost/fit?url=NO_SUCH_IMAGE&size=300x200", http.StatusInternalServerError, "Read error", nil}, {"http://localhost/fit?url=http://site.com/img.png&size=BADSIZE", http.StatusBadRequest, "size param should be in format WxH", nil}, {"http://localhost/fit?url=http://site.com/img.png&size=300", http.StatusBadRequest, "size param should be in format WxH", nil}, } test.RunRequests(testCases, t) }
func ExampleRunRequests() { //This is service that we want to test. It should be a type of http.HandlerFunc. test.Service = func(resp http.ResponseWriter, req *http.Request) { resp.Write([]byte("OK")) } test.T = &testing.T{} //Creating set of tests that we want to run. //Each test is a struct that contains endpoint, expected response status, description, optional handler. testCases := []test.TestCase{ { Url: "http://localhost:8080", Description: "Should return 200", }, { Url: "http://localhost:8080", Description: "Should return OK in body", Handler: func(w *httptest.ResponseRecorder, t *testing.T) { if w.Body.String() != "OK" { t.Errorf("Expected %s but got %s", "OK", w.Body.String()) } }, }, { Request: test.NewRequest("GET", "http://localhost:8080", nil), Description: "Should return 200", }, } //Running all test cases. test.RunRequests(testCases) }
func TestHealth(t *testing.T) { test.Service = health.Health test.T = t testCases := []test.TestCase{ { Url: "http://localhost/health", Description: "Should return OK in body", Handler: func(w *httptest.ResponseRecorder, t *testing.T) { expectedResponse := "OK" if w.Body.String() != expectedResponse { t.Errorf("Expected %s but got %s", expectedResponse, w.Body.String()) } }, }, } test.RunRequests(testCases) }