// Homework 46, challenge: One item, tested. package main import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "testing" "time" ) func TestList(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" || r.URL.Path != "/api/items" { t.Errorf("got %s %s, want GET /api/items", r.Method, r.URL.Path) } w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, `[{"id": 1, "name": "Rice", "quantity": 2}, {"id": 4, "name": "Tea", "quantity": 1}]`) })) defer server.Close() items, err := newAPIClient(server.URL).List(context.Background()) if err != nil { t.Fatalf("List: %v", err) } want := []item{{ID: 1, Name: "Rice", Quantity: 2}, {ID: 4, Name: "Tea", Quantity: 1}} if len(items) != len(want) { t.Fatalf("got %d items, want %d", len(items), len(want)) } for i := range want { if items[i] != want[i] { t.Errorf("item %d = %+v, want %+v", i, items[i], want[i]) } } } func TestAddSendsJSON(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if got := r.Header.Get("Content-Type"); got != "application/json" { t.Errorf("Content-Type = %q, want application/json", got) } var input itemInput err := json.NewDecoder(r.Body).Decode(&input) if err != nil { t.Errorf("the body is not JSON: %v", err) } if input.Name != "Rice" || input.Quantity != 2 { t.Errorf("the server got %+v, want Rice and 2", input) } w.WriteHeader(http.StatusCreated) fmt.Fprintln(w, `{"id": 7, "name": "Rice", "quantity": 2}`) })) defer server.Close() created, err := newAPIClient(server.URL).Add(context.Background(), "Rice", 2) if err != nil { t.Fatalf("Add: %v", err) } if created.ID != 7 { t.Errorf("ID = %d, want 7", created.ID) } } func TestErrorReplies(t *testing.T) { tests := []struct { name string status int body string wantMessage string }{ {"JSON error", http.StatusBadRequest, `{"error": "the name is empty"}`, "the name is empty"}, {"not found", http.StatusNotFound, `{"error": "no item has the id 9"}`, "no item has the id 9"}, {"plain text", http.StatusInternalServerError, "something broke", "Internal Server Error"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(test.status) fmt.Fprintln(w, test.body) })) defer server.Close() err := newAPIClient(server.URL).Delete(context.Background(), 9) var replyErr *apiError if !errors.As(err, &replyErr) { t.Fatalf("error = %v, want an *apiError", err) } if replyErr.Status != test.status { t.Errorf("Status = %d, want %d", replyErr.Status, test.status) } if replyErr.Message != test.wantMessage { t.Errorf("Message = %q, want %q", replyErr.Message, test.wantMessage) } }) } } func TestBadJSONReply(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "this is not JSON") })) defer server.Close() _, err := newAPIClient(server.URL).List(context.Background()) if err == nil { t.Fatal("List gave no error for a reply that is not JSON") } } func TestTimeout(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(500 * time.Millisecond) fmt.Fprintln(w, "[]") })) defer server.Close() client := newAPIClient(server.URL) client.httpClient.Timeout = 50 * time.Millisecond _, err := client.List(context.Background()) if !errors.Is(err, context.DeadlineExceeded) { t.Errorf("error = %v, want a timeout", err) } } // TestGet checks that Get asks for GET /api/items/4, and decodes the item that // the fake server sends back. func TestGet(t *testing.T) { t.Skip("TODO: write this test") } // TestGetNotFound checks that a 404 reply with {"error": "no item has the id 9"} // gives an *apiError with Status 404 and that message. func TestGetNotFound(t *testing.T) { t.Skip("TODO: write this test") }