client_recipe_validation_test.go

 1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
 2//
 3// SPDX-License-Identifier: LicenseRef-MutuaL-1.2
 4
 5package cooked
 6
 7import (
 8	"context"
 9	"net/http"
10	"testing"
11)
12
13func TestListRecipesACIDAPIClientResponses1AcceptsEmptyRecipesList(t *testing.T) {
14	client, closeServer := newTestClient(t, rawRecipeListTestHandler(
15		t,
16		"/api/user/returned-user/recipes",
17		"{\"recipes\":[]}",
18	))
19	defer closeServer()
20
21	recipes, err := client.ListRecipes(context.Background(), 1, 10)
22	if err != nil {
23		t.Fatalf("ListRecipes() error = %v", err)
24	}
25	if len(recipes) != 0 {
26		t.Fatalf("recipes length = %d, want 0", len(recipes))
27	}
28}
29
30func TestListRecipesACIDAPIClientResponses1RejectsMissingRecipesField(t *testing.T) {
31	client, closeServer := newTestClient(t, rawRecipeListTestHandler(
32		t,
33		"/api/user/returned-user/recipes",
34		`{}`,
35	))
36	defer closeServer()
37
38	_, err := client.ListRecipes(context.Background(), 1, 10)
39	if err == nil {
40		t.Fatal("ListRecipes() error = nil, want missing recipes error")
41	}
42}
43
44func TestSearchRecipesACIDAPIClientResponses1RejectsRecipeCardsWithoutIDOrTitle(t *testing.T) {
45	tests := []struct {
46		name string
47		body string
48	}{
49		{name: "missing id", body: "{\"recipes\":[{\"title\":\"Pasta\"}]}"},
50		{name: "blank title", body: "{\"recipes\":[{\"id\":\"recipe-1\",\"title\":\"   \"}]}"},
51	}
52
53	for _, tt := range tests {
54		t.Run(tt.name, func(t *testing.T) {
55			client, closeServer := newTestClient(t, rawRecipeListTestHandler(
56				t,
57				"/api/user/returned-user/recipes/search",
58				tt.body,
59			))
60			defer closeServer()
61
62			_, err := client.SearchRecipes(context.Background(), "pasta", 1)
63			if err == nil {
64				t.Fatal("SearchRecipes() error = nil, want invalid recipe card error")
65			}
66		})
67	}
68}
69
70func rawRecipeListTestHandler(t *testing.T, path, body string) http.HandlerFunc {
71	t.Helper()
72
73	return func(w http.ResponseWriter, r *http.Request) {
74		switch r.URL.Path {
75		case "/api/public/login":
76			writeLoginResponse(t, w)
77		case path:
78			w.Header().Set("Content-Type", "application/json")
79			if _, err := w.Write([]byte(body)); err != nil {
80				t.Fatalf("write raw recipe list response: %v", err)
81			}
82		default:
83			t.Fatalf("unexpected path %s", r.URL.Path)
84		}
85	}
86}