Files
MealQuest/internal/server/recipesearch_test.go
T
dev_agentandClaude Opus 5.5 ceedc45309
CI / ci (push) Successful in 1m49s
CI / ci (pull_request) Successful in 1m48s
Grounding pipeline and recipe-search settings API
recipes.Grounder ties search, fetch/extract, Rank, the photo cache and
normalize_recipe together. Ground(ctx, dishName, query) reuses a stored
source_url among the top candidates without fetching, otherwise tries the
ranked recipes best first and stores the photo, recipe, ingredients and
steps in one transaction, returning Grounded{recipe_id, photo_id, method,
minutes_total, difficulty, source_url, site_name} or a typed
*ErrUngroundable listing every reason. GroundURL grounds a pasted URL the
same way; GroundMany grounds items 3 at a time with per-item results.

PhotoCache is split into DownloadPhoto (fetch, decode, size check, no
writes) and CachePhoto(ctx, tx, photo), which records the row in the
caller's transaction; RemovePhotoFiles cleans up after a rollback.

Migration 0007 adds photo_id, method, difficulty and minutes_total to
recipes, and api_key_last4 to recipe_search_settings. SearXNG is now
called at recipe_search_settings.base_url.

GET/PATCH /api/v1/settings/recipe-search (Brave key sealed with
secretbox, only api_key_set and api_key_last4 returned) and POST
/api/v1/settings/recipe-search/test (searches "chicken tikka masala",
returns the count, 409 not_configured or 502 search_failed).

Maestro task 53afd59c-6c35-4af7-904c-6c167d1ad69d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 15:06:39 -04:00

125 lines
4.5 KiB
Go

package server
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/recipes"
)
const (
recipeSearchPath = "/api/v1/settings/recipe-search"
recipeSearchTestPath = "/api/v1/settings/recipe-search/test"
testBraveKey = "BSA-secret-brave-key-9f3c"
)
// newRecipeSearchRouter returns a router serving search.
func newRecipeSearchRouter(t *testing.T, search *recipes.SearchSettingsService) http.Handler {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
r, err := NewRouter(logger, "dev", nil, stubAuth{}, stubSessions{}, newTestSettings(t), search, newTestRunner(t),
newTestPhotos(t), fstest.MapFS{"index.html": {Data: []byte(fixtureIndex)}})
if err != nil {
t.Fatal(err)
}
return r
}
func TestRecipeSearchSettingsAPI(t *testing.T) {
t.Parallel()
router := newRecipeSearchRouter(t, newTestSearch(t))
var bodies []string
call := func(method, target, body string) (*httptest.ResponseRecorder, map[string]any) {
t.Helper()
var r io.Reader
if body != "" {
r = strings.NewReader(body)
}
rec, decoded := serve(t, router, signedIn(method, target, r))
bodies = append(bodies, rec.Body.String())
return rec, decoded
}
rec, body := call(http.MethodGet, recipeSearchPath, "")
if rec.Code != http.StatusOK || body["provider"] != nil || body["api_key_set"] != false {
t.Errorf("GET unconfigured = %d %v", rec.Code, body)
}
rec, body = call(http.MethodPost, recipeSearchTestPath, "")
if rec.Code != http.StatusConflict || body["error"].(map[string]any)["code"] != "not_configured" {
t.Errorf("POST test unconfigured = %d %v", rec.Code, body)
}
for _, bad := range []string{
`{"provider":"google"}`,
`{"provider":"brave"}`,
`{"provider":"searxng","base_url":"not a url"}`,
`{"provider":"brave","api_key":null}`,
`{"provider":"brave","apikey":"x"}`,
} {
if rec, _ := call(http.MethodPatch, recipeSearchPath, bad); rec.Code != http.StatusBadRequest {
t.Errorf("PATCH %s = %d, want 400", bad, rec.Code)
}
}
rec, body = call(http.MethodPatch, recipeSearchPath, `{"provider":"brave","api_key":"`+testBraveKey+`"}`)
if rec.Code != http.StatusOK || body["provider"] != "brave" || body["api_key_set"] != true || body["api_key_last4"] != "9f3c" {
t.Errorf("PATCH Brave = %d %v", rec.Code, body)
}
if _, ok := body["api_key"]; ok {
t.Errorf("PATCH response has an api_key field: %v", body)
}
rec, body = call(http.MethodGet, recipeSearchPath, "")
if rec.Code != http.StatusOK || body["provider"] != "brave" || body["api_key_last4"] != "9f3c" {
t.Errorf("GET Brave = %d %v", rec.Code, body)
}
// SearXNG keeps the stored key; the test search goes to the instance.
searx := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"results":[{"url":"https://a.example/1"},{"url":"https://b.example/2"},{"url":"https://c.example/3"}]}`))
}))
t.Cleanup(searx.Close)
rec, body = call(http.MethodPatch, recipeSearchPath, `{"provider":"searxng","base_url":"`+searx.URL+`"}`)
if rec.Code != http.StatusOK || body["base_url"] != searx.URL || body["api_key_set"] != true {
t.Errorf("PATCH SearXNG = %d %v", rec.Code, body)
}
rec, body = call(http.MethodPost, recipeSearchTestPath, "")
if rec.Code != http.StatusOK || body["count"] != float64(3) || body["query"] != recipes.SearchTestQuery {
t.Errorf("POST test = %d %v, want count 3", rec.Code, body)
}
searx.Close()
rec, body = call(http.MethodPost, recipeSearchTestPath, "")
if rec.Code != http.StatusBadGateway || body["error"].(map[string]any)["code"] != "search_failed" {
t.Errorf("POST test against a stopped instance = %d %v, want 502 search_failed", rec.Code, body)
}
for _, b := range bodies {
if strings.Contains(b, testBraveKey) || strings.Contains(b, testBraveKey[:12]) {
t.Errorf("response holds the Brave key: %s", b)
}
}
}
func TestRecipeSearchSettingsNeedCSRF(t *testing.T) {
t.Parallel()
router := newRecipeSearchRouter(t, newTestSearch(t))
for _, method := range []string{http.MethodPatch, http.MethodPost} {
target := recipeSearchPath
if method == http.MethodPost {
target = recipeSearchTestPath
}
req := httptest.NewRequest(method, target, strings.NewReader(`{"provider":"brave","api_key":"`+testBraveKey+`"}`))
req.AddCookie(validSessionCookie)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("%s %s without CSRF token = %d, want 403", method, target, rec.Code)
}
}
}