1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
2//
3// SPDX-License-Identifier: LicenseRef-MutuaL-1.2
4
5package cooked
6
7import (
8 "context"
9 "encoding/json"
10 "net/http"
11 "net/http/httptest"
12 "net/url"
13 "testing"
14)
15
16func TestReadShoppingListACIDAuthenticationLogin3StoresCookies(t *testing.T) {
17 var sawSessionCookie bool
18 client, closeServer := newTestClient(t, shoppingListTestHandler(t, &sawSessionCookie))
19 defer closeServer()
20
21 shoppingList, err := client.ReadShoppingList(context.Background())
22 if err != nil {
23 t.Fatalf("ReadShoppingList() error = %v", err)
24 }
25
26 if !sawSessionCookie {
27 t.Fatal("shopping-list request did not receive session cookie")
28 }
29 if len(shoppingList.Aisles) != 1 || shoppingList.Aisles[0].ProductGroups[0].Name != "Pasta" {
30 t.Fatalf("shopping list = %#v, want one Pasta item", shoppingList)
31 }
32}
33
34func TestListRecipesACIDRecipesRead1ListsSavedRecipes(t *testing.T) {
35 client, closeServer := newTestClient(t, listRecipesTestHandler(t))
36 defer closeServer()
37
38 recipes, err := client.ListRecipes(context.Background(), 2, 5)
39 if err != nil {
40 t.Fatalf("ListRecipes() error = %v", err)
41 }
42
43 if len(recipes) != 1 {
44 t.Fatalf("recipes length = %d, want 1", len(recipes))
45 }
46 if recipes[0].ID != "recipe-1" || recipes[0].Title != "Pasta" {
47 t.Fatalf("recipe = %#v, want recipe-1 Pasta", recipes[0])
48 }
49}
50
51func TestSearchRecipesACIDRecipesRead2SearchesSavedRecipes(t *testing.T) {
52 client, closeServer := newTestClient(t, searchRecipesTestHandler(t))
53 defer closeServer()
54
55 recipes, err := client.SearchRecipes(context.Background(), "pasta & tomato", 3)
56 if err != nil {
57 t.Fatalf("SearchRecipes() error = %v", err)
58 }
59
60 if len(recipes) != 1 {
61 t.Fatalf("recipes length = %d, want 1", len(recipes))
62 }
63 if recipes[0].ID != "recipe-1" || recipes[0].Title != "Pasta" {
64 t.Fatalf("recipe = %#v, want recipe-1 Pasta", recipes[0])
65 }
66}
67
68func TestReadRecipeMetadataACIDRecipesRead6ReadsMetadata(t *testing.T) {
69 client, closeServer := newTestClient(t, recipeMetadataTestHandler(t))
70 defer closeServer()
71
72 metadata, err := client.ReadRecipeMetadata(context.Background(), "recipe/with space")
73 if err != nil {
74 t.Fatalf("ReadRecipeMetadata() error = %v", err)
75 }
76
77 if metadata.Title != "Pasta with Tomato Sauce" {
78 t.Fatalf("metadata title = %q, want Pasta with Tomato Sauce", metadata.Title)
79 }
80 if len(metadata.ImageURLs) != 1 || metadata.ImageURLs[0] != "https://example.invalid/pasta.jpg" {
81 t.Fatalf("metadata image URLs = %#v, want one pasta image", metadata.ImageURLs)
82 }
83 if metadata.Owner != "returned-user" || !metadata.EditPermission {
84 t.Fatalf("metadata owner/edit = %q/%v, want returned-user/true", metadata.Owner, metadata.EditPermission)
85 }
86}
87
88func TestReadRecipeContentACIDRecipesRead7And8ReadsContentAndPortions(t *testing.T) {
89 client, closeServer := newTestClient(t, recipeContentTestHandler(t))
90 defer closeServer()
91
92 content, err := client.ReadRecipeContent(context.Background(), "recipe/with space")
93 if err != nil {
94 t.Fatalf("ReadRecipeContent() error = %v", err)
95 }
96
97 if content.Content != "# Pasta\n\n- 200g pasta\n\n1. Boil pasta." {
98 t.Fatalf("content = %q, want recipe markdown", content.Content)
99 }
100 if content.Portions != 2 {
101 t.Fatalf("portions = %d, want 2", content.Portions)
102 }
103}
104
105func TestPreviewRecipeTextACIDRecipesPreviewText1To4PreviewsWithoutSaving(t *testing.T) {
106 var previewCalls int
107 client, closeServer := newTestClient(t, previewRecipeTextTestHandler(t, &previewCalls))
108 defer closeServer()
109
110 preview, err := client.PreviewRecipeText(context.Background(), "Pasta", "Boil pasta.")
111 if err != nil {
112 t.Fatalf("PreviewRecipeText() error = %v", err)
113 }
114
115 if previewCalls != 1 {
116 t.Fatalf("preview calls = %d, want 1", previewCalls)
117 }
118 if preview.Title != "Pasta with Tomato Sauce" {
119 t.Fatalf("preview title = %q, want Pasta with Tomato Sauce", preview.Title)
120 }
121 if preview.Markdown != "# Pasta\n\n1. Boil pasta." {
122 t.Fatalf("preview markdown = %q, want recipe markdown", preview.Markdown)
123 }
124 if preview.Portions != 2 {
125 t.Fatalf("preview portions = %d, want 2", preview.Portions)
126 }
127}
128
129func TestSavePreparedRecipeACIDRecipesSave2And9And13SavesMarkdownAsDescription(t *testing.T) {
130 var saveCalls int
131 client, closeServer := newTestClient(t, savePreparedRecipeTestHandler(t, &saveCalls))
132 defer closeServer()
133
134 recipeID, err := client.SavePreparedRecipe(context.Background(), "Pasta", "# Pasta\n\n1. Boil pasta.", 2)
135 if err != nil {
136 t.Fatalf("SavePreparedRecipe() error = %v", err)
137 }
138
139 if saveCalls != 1 {
140 t.Fatalf("save calls = %d, want 1", saveCalls)
141 }
142 if recipeID != "recipe-1" {
143 t.Fatalf("recipe ID = %q, want recipe-1", recipeID)
144 }
145}
146
147func TestUpdateRecipeContentACIDRecipesSave8And9And13UpdatesExistingRecipe(t *testing.T) {
148 var updateCalls int
149 client, closeServer := newTestClient(t, updateRecipeContentTestHandler(t, &updateCalls))
150 defer closeServer()
151
152 err := client.UpdateRecipeContent(context.Background(), "recipe/with space", "# Pasta\n\n1. Boil pasta.", 4)
153 if err != nil {
154 t.Fatalf("UpdateRecipeContent() error = %v", err)
155 }
156
157 if updateCalls != 1 {
158 t.Fatalf("update calls = %d, want 1", updateCalls)
159 }
160}
161
162func TestDeleteRecipeDeletesSavedRecipe(t *testing.T) {
163 var deleteCalls int
164 client, closeServer := newTestClient(t, deleteRecipeTestHandler(t, &deleteCalls))
165 defer closeServer()
166
167 err := client.DeleteRecipe(context.Background(), "recipe/with space")
168 if err != nil {
169 t.Fatalf("DeleteRecipe() error = %v", err)
170 }
171
172 if deleteCalls != 1 {
173 t.Fatalf("delete calls = %d, want 1", deleteCalls)
174 }
175}
176
177func TestClearShoppingListACIDShoppingListClear1ClearsAllItems(t *testing.T) {
178 var clearCalls int
179 client, closeServer := newTestClient(t, clearShoppingListTestHandler(t, &clearCalls))
180 defer closeServer()
181
182 err := client.ClearShoppingList(context.Background())
183 if err != nil {
184 t.Fatalf("ClearShoppingList() error = %v", err)
185 }
186
187 if clearCalls != 1 {
188 t.Fatalf("clear calls = %d, want 1", clearCalls)
189 }
190}
191
192func TestAddShoppingListIngredientsACIDShoppingListAdd1To4AddsIngredients(t *testing.T) {
193 var addCalls int
194 client, closeServer := newTestClient(t, addShoppingListIngredientsTestHandler(t, &addCalls))
195 defer closeServer()
196
197 result, err := client.AddShoppingListIngredients(
198 context.Background(),
199 "200g pasta\n1 cup tomato sauce",
200 "recipe-1",
201 )
202 if err != nil {
203 t.Fatalf("AddShoppingListIngredients() error = %v", err)
204 }
205
206 if addCalls != 1 {
207 t.Fatalf("add calls = %d, want 1", addCalls)
208 }
209 if result.AddedCount != 2 {
210 t.Fatalf("added count = %d, want 2", result.AddedCount)
211 }
212 if len(result.Ingredients) != 2 || result.Ingredients[0] != "200g pasta" {
213 t.Fatalf("added ingredients = %#v, want two added ingredients", result.Ingredients)
214 }
215}
216
217func TestRemoveShoppingListProductGroupsACIDShoppingListRemove1RemovesProductGroups(t *testing.T) {
218 var removeCalls int
219 client, closeServer := newTestClient(t, removeShoppingListProductGroupsTestHandler(t, &removeCalls))
220 defer closeServer()
221
222 err := client.RemoveShoppingListProductGroups(context.Background(), []string{"pasta", "tomato"})
223 if err != nil {
224 t.Fatalf("RemoveShoppingListProductGroups() error = %v", err)
225 }
226
227 if removeCalls != 1 {
228 t.Fatalf("remove calls = %d, want 1", removeCalls)
229 }
230}
231
232func TestReplaceShoppingListSelectionACIDShoppingListSelection1And8ReplacesSelectedSet(t *testing.T) {
233 var replaceCalls int
234 client, closeServer := newTestClient(t, replaceShoppingListSelectionTestHandler(t, &replaceCalls))
235 defer closeServer()
236
237 err := client.ReplaceShoppingListSelection(context.Background(), []string{"pasta", "tomato"})
238 if err != nil {
239 t.Fatalf("ReplaceShoppingListSelection() error = %v", err)
240 }
241
242 if replaceCalls != 1 {
243 t.Fatalf("replace calls = %d, want 1", replaceCalls)
244 }
245}
246
247func TestUserPathEscapesAuthenticatedUsername(t *testing.T) {
248 client := &Client{authenticatedUsername: "user/name"}
249
250 got := client.userPath("/api/user/{username}/shopping-list")
251 if got != "/api/user/user%2Fname/shopping-list" {
252 t.Fatalf("userPath() = %q, want escaped username", got)
253 }
254}
255
256func TestNewRequestPreservesEscapedUserPathWithQuery(t *testing.T) {
257 baseURL, err := url.Parse("https://example.invalid")
258 if err != nil {
259 t.Fatalf("parse base URL: %v", err)
260 }
261 client := &Client{baseURL: baseURL}
262
263 request, err := client.newRequest(
264 context.Background(),
265 http.MethodGet,
266 "/api/user/user%2Fname/recipes?page=2&page-count=5",
267 nil,
268 )
269 if err != nil {
270 t.Fatalf("newRequest() error = %v", err)
271 }
272
273 if request.URL.String() != "https://example.invalid/api/user/user%2Fname/recipes?page=2&page-count=5" {
274 t.Fatalf("request URL = %q, want escaped username preserved", request.URL.String())
275 }
276}
277
278func newTestClient(t *testing.T, handler http.HandlerFunc) (*Client, func()) {
279 t.Helper()
280
281 server := httptest.NewServer(handler)
282 baseURL, err := url.Parse(server.URL)
283 if err != nil {
284 server.Close()
285 t.Fatalf("parse server URL: %v", err)
286 }
287 client, err := NewClient(baseURL, "configured-user", "configured-password")
288 if err != nil {
289 server.Close()
290 t.Fatalf("NewClient() error = %v", err)
291 }
292
293 return client, server.Close
294}
295
296func shoppingListTestHandler(t *testing.T, sawSessionCookie *bool) http.HandlerFunc {
297 t.Helper()
298
299 return func(w http.ResponseWriter, r *http.Request) {
300 switch r.URL.Path {
301 case "/api/public/login":
302 requireLoginRequest(t, r)
303 writeLoginResponse(t, w)
304 case "/api/user/returned-user/shopping-list":
305 requireSessionCookie(t, r)
306 *sawSessionCookie = true
307 writeShoppingListResponse(t, w)
308 default:
309 t.Fatalf("unexpected path %s", r.URL.Path)
310 }
311 }
312}
313
314func listRecipesTestHandler(t *testing.T) http.HandlerFunc {
315 t.Helper()
316
317 return func(w http.ResponseWriter, r *http.Request) {
318 switch r.URL.Path {
319 case "/api/public/login":
320 writeLoginResponse(t, w)
321 case "/api/user/returned-user/recipes":
322 requireQueryValue(t, r, "page", "2")
323 requireQueryValue(t, r, "page-count", "5")
324 writeRecipeListResponse(t, w)
325 default:
326 t.Fatalf("unexpected path %s", r.URL.Path)
327 }
328 }
329}
330
331func searchRecipesTestHandler(t *testing.T) http.HandlerFunc {
332 t.Helper()
333
334 return func(w http.ResponseWriter, r *http.Request) {
335 switch r.URL.Path {
336 case "/api/public/login":
337 writeLoginResponse(t, w)
338 case "/api/user/returned-user/recipes/search":
339 requireMethod(t, r, http.MethodGet, "search")
340 requireQueryValue(t, r, "q", "pasta & tomato")
341 requireQueryValue(t, r, "page", "3")
342 writeRecipeListResponse(t, w)
343 default:
344 t.Fatalf("unexpected path %s", r.URL.Path)
345 }
346 }
347}
348
349func recipeMetadataTestHandler(t *testing.T) http.HandlerFunc {
350 t.Helper()
351
352 return func(w http.ResponseWriter, r *http.Request) {
353 switch r.URL.EscapedPath() {
354 case "/api/public/login":
355 writeLoginResponse(t, w)
356 case "/api/recipe/recipe%2Fwith%20space/metadata":
357 requireMethod(t, r, http.MethodGet, "metadata")
358 requireSessionCookie(t, r)
359 writeRecipeMetadataResponse(t, w)
360 default:
361 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
362 }
363 }
364}
365
366func recipeContentTestHandler(t *testing.T) http.HandlerFunc {
367 t.Helper()
368
369 return func(w http.ResponseWriter, r *http.Request) {
370 switch r.URL.EscapedPath() {
371 case "/api/public/login":
372 writeLoginResponse(t, w)
373 case "/api/recipe/recipe%2Fwith%20space/content":
374 requireMethod(t, r, http.MethodGet, "content")
375 requireSessionCookie(t, r)
376 writeJSON(t, w, RecipeContent{Content: "# Pasta\n\n- 200g pasta\n\n1. Boil pasta.", Portions: 2})
377 default:
378 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
379 }
380 }
381}
382
383func previewRecipeTextTestHandler(t *testing.T, previewCalls *int) http.HandlerFunc {
384 t.Helper()
385
386 return func(w http.ResponseWriter, r *http.Request) {
387 switch r.URL.Path {
388 case "/api/public/login":
389 writeLoginResponse(t, w)
390 case "/api/new/from-text/preview":
391 requireMethod(t, r, http.MethodPost, "preview")
392 requireSessionCookie(t, r)
393 requirePreviewRecipeTextRequest(t, r)
394 (*previewCalls)++
395 writeJSON(t, w, RecipeTextPreview{
396 Title: "Pasta with Tomato Sauce",
397 Markdown: "# Pasta\n\n1. Boil pasta.",
398 Portions: 2,
399 })
400 default:
401 t.Fatalf("unexpected path %s", r.URL.Path)
402 }
403 }
404}
405
406func savePreparedRecipeTestHandler(t *testing.T, saveCalls *int) http.HandlerFunc {
407 t.Helper()
408
409 return func(w http.ResponseWriter, r *http.Request) {
410 switch r.URL.Path {
411 case "/api/public/login":
412 writeLoginResponse(t, w)
413 case "/api/recipe/import/save":
414 requireMethod(t, r, http.MethodPost, "save prepared recipe")
415 requireSessionCookie(t, r)
416 requireSavePreparedRecipeRequest(t, r)
417 (*saveCalls)++
418 writeJSON(t, w, saveRecipeResponse{RecipeID: "recipe-1"})
419 default:
420 t.Fatalf("unexpected path %s", r.URL.Path)
421 }
422 }
423}
424
425func updateRecipeContentTestHandler(t *testing.T, updateCalls *int) http.HandlerFunc {
426 t.Helper()
427
428 return func(w http.ResponseWriter, r *http.Request) {
429 switch r.URL.EscapedPath() {
430 case "/api/public/login":
431 writeLoginResponse(t, w)
432 case "/api/recipe/recipe%2Fwith%20space/content":
433 requireMethod(t, r, http.MethodPost, "update recipe content")
434 requireSessionCookie(t, r)
435 requireUpdateRecipeContentRequest(t, r)
436 (*updateCalls)++
437 w.WriteHeader(http.StatusNoContent)
438 default:
439 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
440 }
441 }
442}
443
444func deleteRecipeTestHandler(t *testing.T, deleteCalls *int) http.HandlerFunc {
445 t.Helper()
446
447 return func(w http.ResponseWriter, r *http.Request) {
448 switch r.URL.EscapedPath() {
449 case "/api/public/login":
450 writeLoginResponse(t, w)
451 case "/api/recipe/recipe%2Fwith%20space":
452 requireMethod(t, r, http.MethodDelete, "delete recipe")
453 requireSessionCookie(t, r)
454 (*deleteCalls)++
455 w.WriteHeader(http.StatusNoContent)
456 default:
457 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
458 }
459 }
460}
461
462func clearShoppingListTestHandler(t *testing.T, clearCalls *int) http.HandlerFunc {
463 t.Helper()
464
465 return func(w http.ResponseWriter, r *http.Request) {
466 switch r.URL.EscapedPath() {
467 case "/api/public/login":
468 writeLoginResponse(t, w)
469 case "/api/user/returned-user/shopping-list":
470 requireMethod(t, r, http.MethodDelete, "clear shopping list")
471 requireSessionCookie(t, r)
472 (*clearCalls)++
473 w.WriteHeader(http.StatusNoContent)
474 default:
475 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
476 }
477 }
478}
479
480func addShoppingListIngredientsTestHandler(t *testing.T, addCalls *int) http.HandlerFunc {
481 t.Helper()
482
483 return func(w http.ResponseWriter, r *http.Request) {
484 switch r.URL.EscapedPath() {
485 case "/api/public/login":
486 writeLoginResponse(t, w)
487 case "/api/user/shopping-list":
488 requireMethod(t, r, http.MethodPut, "add shopping-list ingredients")
489 requireSessionCookie(t, r)
490 requireAddShoppingListIngredientsRequest(t, r)
491 (*addCalls)++
492 writeAddShoppingListIngredientsResponse(t, w)
493 default:
494 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
495 }
496 }
497}
498
499func requireAddShoppingListIngredientsRequest(t *testing.T, r *http.Request) {
500 t.Helper()
501
502 var request struct {
503 Ingredients string `json:"ingredients"`
504 RecipeID string `json:"recipe-id"`
505 }
506 if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
507 t.Fatalf("decode add shopping-list ingredients request: %v", err)
508 }
509 if request.Ingredients != "200g pasta\n1 cup tomato sauce" {
510 t.Fatalf("ingredients = %q, want newline-separated ingredients", request.Ingredients)
511 }
512 if request.RecipeID != "recipe-1" {
513 t.Fatalf("recipe ID = %q, want recipe-1", request.RecipeID)
514 }
515}
516
517func writeAddShoppingListIngredientsResponse(t *testing.T, w http.ResponseWriter) {
518 t.Helper()
519
520 w.Header().Set("Content-Type", "application/json")
521 if _, err := w.Write([]byte(`{
522 "success": true,
523 "added-count": 2,
524 "ingredients": ["200g pasta", "1 cup tomato sauce"]
525 }`)); err != nil {
526 t.Fatalf("write add shopping-list ingredients response: %v", err)
527 }
528}
529
530func removeShoppingListProductGroupsTestHandler(t *testing.T, removeCalls *int) http.HandlerFunc {
531 t.Helper()
532
533 return func(w http.ResponseWriter, r *http.Request) {
534 switch r.URL.EscapedPath() {
535 case "/api/public/login":
536 writeLoginResponse(t, w)
537 case "/api/user/returned-user/shopping-list/product-groups":
538 requireMethod(t, r, http.MethodDelete, "remove shopping-list product groups")
539 requireSessionCookie(t, r)
540 requireRemoveShoppingListProductGroupsRequest(t, r)
541 (*removeCalls)++
542 w.WriteHeader(http.StatusNoContent)
543 default:
544 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
545 }
546 }
547}
548
549func replaceShoppingListSelectionTestHandler(t *testing.T, replaceCalls *int) http.HandlerFunc {
550 t.Helper()
551
552 return func(w http.ResponseWriter, r *http.Request) {
553 switch r.URL.EscapedPath() {
554 case "/api/public/login":
555 writeLoginResponse(t, w)
556 case "/api/user/returned-user/shopping-list/product-groups/selection":
557 requireMethod(t, r, http.MethodPut, "replace shopping-list selection")
558 requireSessionCookie(t, r)
559 requireReplaceShoppingListSelectionRequest(t, r)
560 (*replaceCalls)++
561 w.WriteHeader(http.StatusNoContent)
562 default:
563 t.Fatalf("unexpected path %s", r.URL.EscapedPath())
564 }
565 }
566}
567
568func requireRemoveShoppingListProductGroupsRequest(t *testing.T, r *http.Request) {
569 t.Helper()
570
571 var request struct {
572 IDs []string `json:"ids"`
573 }
574 if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
575 t.Fatalf("decode remove shopping-list product groups request: %v", err)
576 }
577 if len(request.IDs) != 2 || request.IDs[0] != "pasta" || request.IDs[1] != "tomato" {
578 t.Fatalf("remove IDs = %#v, want pasta and tomato", request.IDs)
579 }
580}
581
582func requireReplaceShoppingListSelectionRequest(t *testing.T, r *http.Request) {
583 t.Helper()
584
585 var request struct {
586 Selected []string `json:"selected"`
587 }
588 if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
589 t.Fatalf("decode replace shopping-list selection request: %v", err)
590 }
591 if len(request.Selected) != 2 || request.Selected[0] != "pasta" || request.Selected[1] != "tomato" {
592 t.Fatalf("selected IDs = %#v, want pasta and tomato", request.Selected)
593 }
594}
595
596func requirePreviewRecipeTextRequest(t *testing.T, r *http.Request) {
597 t.Helper()
598
599 var request previewRecipeTextRequest
600 if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
601 t.Fatalf("decode preview request: %v", err)
602 }
603 if request.RecipeName != "Pasta" || request.RecipeText != "Boil pasta." {
604 t.Fatalf("preview request = %#v, want configured title/text", request)
605 }
606}
607
608func requireSavePreparedRecipeRequest(t *testing.T, r *http.Request) {
609 t.Helper()
610
611 var request savePreparedRecipeRequest
612 if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
613 t.Fatalf("decode save prepared recipe request: %v", err)
614 }
615 if request.Title != "Pasta" {
616 t.Fatalf("save title = %q, want Pasta", request.Title)
617 }
618 if request.Description != "# Pasta\n\n1. Boil pasta." {
619 t.Fatalf("save description = %q, want markdown", request.Description)
620 }
621 if request.Portions != 2 {
622 t.Fatalf("save portions = %d, want 2", request.Portions)
623 }
624}
625
626func requireUpdateRecipeContentRequest(t *testing.T, r *http.Request) {
627 t.Helper()
628
629 var request updateRecipeContentRequest
630 if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
631 t.Fatalf("decode update recipe content request: %v", err)
632 }
633 if request.Description != "# Pasta\n\n1. Boil pasta." {
634 t.Fatalf("update description = %q, want markdown", request.Description)
635 }
636 if request.Portions != 4 {
637 t.Fatalf("update portions = %d, want 4", request.Portions)
638 }
639}
640
641func requireLoginRequest(t *testing.T, r *http.Request) {
642 t.Helper()
643 requireMethod(t, r, http.MethodPost, "login")
644
645 var request loginRequest
646 if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
647 t.Fatalf("decode login request: %v", err)
648 }
649 if request.Username != "configured-user" || request.Password != "configured-password" {
650 t.Fatalf("login request = %#v, want configured credentials", request)
651 }
652}
653
654func requireMethod(t *testing.T, r *http.Request, want string, label string) {
655 t.Helper()
656
657 if r.Method != want {
658 t.Fatalf("%s method = %s, want %s", label, r.Method, want)
659 }
660}
661
662func requireSessionCookie(t *testing.T, r *http.Request) {
663 t.Helper()
664
665 cookie, err := r.Cookie("cooked_session")
666 if err != nil {
667 t.Fatalf("missing session cookie: %v", err)
668 }
669 if cookie.Value != "session-value" {
670 t.Fatalf("session cookie = %q, want session-value", cookie.Value)
671 }
672}
673
674func requireQueryValue(t *testing.T, r *http.Request, name string, want string) {
675 t.Helper()
676
677 if got := r.URL.Query().Get(name); got != want {
678 t.Fatalf("%s query = %q, want %q", name, got, want)
679 }
680}
681
682func writeLoginResponse(t *testing.T, w http.ResponseWriter) {
683 t.Helper()
684
685 http.SetCookie(w, &http.Cookie{Name: "cooked_session", Value: "session-value", Path: "/"})
686 writeJSON(t, w, loginResponse{Username: "returned-user"})
687}
688
689func writeShoppingListResponse(t *testing.T, w http.ResponseWriter) {
690 t.Helper()
691
692 writeJSON(t, w, shoppingListResponse{
693 ShoppingList: ShoppingList{
694 Aisles: []Aisle{{
695 ID: "pantry",
696 Name: "Pantry",
697 ProductGroups: []ProductGroup{{
698 ID: "pasta",
699 Name: "Pasta",
700 Quantity: "200g",
701 }},
702 }},
703 },
704 Recipes: []string{"recipe-id"},
705 })
706}
707
708func writeRecipeListResponse(t *testing.T, w http.ResponseWriter) {
709 t.Helper()
710
711 writeJSON(t, w, recipeListResponse{
712 Recipes: []RecipeCard{{
713 ID: "recipe-1",
714 Title: "Pasta",
715 ThumbnailURL: "https://example.invalid/thumb.jpg",
716 }},
717 })
718}
719
720func writeRecipeMetadataResponse(t *testing.T, w http.ResponseWriter) {
721 t.Helper()
722
723 w.Header().Set("Content-Type", "application/json")
724 if _, err := w.Write([]byte(`{
725 "title": "Pasta with Tomato Sauce",
726 "image-urls": ["https://example.invalid/pasta.jpg"],
727 "owner": "returned-user",
728 "edit-permission": true
729 }`)); err != nil {
730 t.Fatalf("write metadata response: %v", err)
731 }
732}
733
734func writeJSON[
735 T loginResponse | shoppingListResponse | recipeListResponse | RecipeContent | RecipeTextPreview | saveRecipeResponse,
736](
737 t *testing.T,
738 w http.ResponseWriter,
739 value T,
740) {
741 t.Helper()
742
743 w.Header().Set("Content-Type", "application/json")
744 if err := json.NewEncoder(w).Encode(value); err != nil {
745 t.Fatalf("write JSON: %v", err)
746 }
747}