// Homework 45, problem 3: Test a counter API. Solution. package main import ( "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) // send runs one request through the routes and returns what was written. func send(method string, target string, body string) *httptest.ResponseRecorder { request := httptest.NewRequest(method, target, strings.NewReader(body)) recorder := httptest.NewRecorder() routes().ServeHTTP(recorder, request) return recorder } // readValue decodes a {"value": N} body, and stops the test if it cannot. func readValue(t *testing.T, response *httptest.ResponseRecorder) int { t.Helper() var reply valueReply err := json.Unmarshal(response.Body.Bytes(), &reply) if err != nil { t.Fatalf("the body %q is not a value: %v", response.Body, err) } return reply.Value } func TestGetStartsAtZero(t *testing.T) { count = &counter{} response := send("GET", "/api/counter", "") if response.Code != http.StatusOK { t.Fatalf("status = %d, want %d", response.Code, http.StatusOK) } if got := response.Header().Get("Content-Type"); got != "application/json" { t.Errorf("Content-Type = %q, want application/json", got) } if got := readValue(t, response); got != 0 { t.Errorf("value = %d, want 0", got) } } func TestAddThenGet(t *testing.T) { count = &counter{} response := send("POST", "/api/counter/add", `{"by": 5}`) if response.Code != http.StatusOK { t.Fatalf("first add: status = %d, want %d", response.Code, http.StatusOK) } if got := readValue(t, response); got != 5 { t.Errorf("first add: value = %d, want 5", got) } send("POST", "/api/counter/add", `{"by": 3}`) response = send("GET", "/api/counter", "") if got := readValue(t, response); got != 8 { t.Errorf("value = %d, want 8", got) } } func TestAddRejectsBadInput(t *testing.T) { tests := []struct { name string body string }{ {"not JSON", `hello`}, {"unknown field", `{"by": 5, "times": 2}`}, {"zero", `{"by": 0}`}, {"too big", `{"by": 101}`}, {"text", `{"by": "five"}`}, {"empty body", ``}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { count = &counter{} response := send("POST", "/api/counter/add", test.body) if response.Code != http.StatusBadRequest { t.Errorf("status = %d, want %d", response.Code, http.StatusBadRequest) } if count.Value() != 0 { t.Errorf("the counter changed to %d", count.Value()) } }) } }