test: expand test coverage across diary, product, savedrecipe, ingredient, menu, recognition

- Fix locale_test: add TestMain to pre-populate Supported map so zh/es tests pass
- Export pure functions for testability: ResolveWeekStart, MapCuisineSlug (menu + savedrecipe), MergeAndDeduplicate
- Introduce repository interfaces (DiaryRepository, ProductRepository, SavedRecipeRepository, IngredientSearcher) in each handler; NewHandler now accepts interfaces — concrete *Repository still satisfies them
- Add mock files: diary/mocks, product/mocks, savedrecipe/mocks
- Add handler unit tests (no DB) for diary (8), product (8), savedrecipe (8), ingredient (5)
- Add pure-function unit tests: menu/ResolveWeekStart (6), savedrecipe/MapCuisineSlug (5), recognition/MergeAndDeduplicate (6)
- Add repository integration tests (//go:build integration): diary (4), product (6)
- Extend recipe integration tests: GetByID_Found, GetByID_WithTranslation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
dbastrikin
2026-03-15 22:54:09 +02:00
parent 7c338c35f3
commit bfaca1a2c1
21 changed files with 1452 additions and 28 deletions

View File

@@ -1,6 +1,7 @@
package diary package diary
import ( import (
"context"
"encoding/json" "encoding/json"
"log/slog" "log/slog"
"net/http" "net/http"
@@ -9,13 +10,20 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
) )
// DiaryRepository is the data layer interface used by Handler.
type DiaryRepository interface {
ListByDate(ctx context.Context, userID, date string) ([]*Entry, error)
Create(ctx context.Context, userID string, req CreateRequest) (*Entry, error)
Delete(ctx context.Context, id, userID string) error
}
// Handler handles diary endpoints. // Handler handles diary endpoints.
type Handler struct { type Handler struct {
repo *Repository repo DiaryRepository
} }
// NewHandler creates a new Handler. // NewHandler creates a new Handler.
func NewHandler(repo *Repository) *Handler { func NewHandler(repo DiaryRepository) *Handler {
return &Handler{repo: repo} return &Handler{repo: repo}
} }

View File

@@ -0,0 +1,26 @@
package mocks
import (
"context"
"github.com/food-ai/backend/internal/domain/diary"
)
// MockDiaryRepository is a test double implementing diary.DiaryRepository.
type MockDiaryRepository struct {
ListByDateFn func(ctx context.Context, userID, date string) ([]*diary.Entry, error)
CreateFn func(ctx context.Context, userID string, req diary.CreateRequest) (*diary.Entry, error)
DeleteFn func(ctx context.Context, id, userID string) error
}
func (m *MockDiaryRepository) ListByDate(ctx context.Context, userID, date string) ([]*diary.Entry, error) {
return m.ListByDateFn(ctx, userID, date)
}
func (m *MockDiaryRepository) Create(ctx context.Context, userID string, req diary.CreateRequest) (*diary.Entry, error) {
return m.CreateFn(ctx, userID, req)
}
func (m *MockDiaryRepository) Delete(ctx context.Context, id, userID string) error {
return m.DeleteFn(ctx, id, userID)
}

View File

@@ -1,19 +1,25 @@
package ingredient package ingredient
import ( import (
"context"
"encoding/json" "encoding/json"
"log/slog" "log/slog"
"net/http" "net/http"
"strconv" "strconv"
) )
// IngredientSearcher is the data layer interface used by Handler.
type IngredientSearcher interface {
Search(ctx context.Context, query string, limit int) ([]*IngredientMapping, error)
}
// Handler handles ingredient HTTP requests. // Handler handles ingredient HTTP requests.
type Handler struct { type Handler struct {
repo *Repository repo IngredientSearcher
} }
// NewHandler creates a new Handler. // NewHandler creates a new Handler.
func NewHandler(repo *Repository) *Handler { func NewHandler(repo IngredientSearcher) *Handler {
return &Handler{repo: repo} return &Handler{repo: repo}
} }

View File

@@ -84,7 +84,7 @@ func (h *Handler) GetMenu(w http.ResponseWriter, r *http.Request) {
return return
} }
weekStart, err := resolveWeekStart(r.URL.Query().Get("week")) weekStart, err := ResolveWeekStart(r.URL.Query().Get("week"))
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, "invalid week parameter, expected YYYY-WNN") writeError(w, http.StatusBadRequest, "invalid week parameter, expected YYYY-WNN")
return return
@@ -120,7 +120,7 @@ func (h *Handler) GenerateMenu(w http.ResponseWriter, r *http.Request) {
} }
_ = json.NewDecoder(r.Body).Decode(&body) _ = json.NewDecoder(r.Body).Decode(&body)
weekStart, err := resolveWeekStart(body.Week) weekStart, err := ResolveWeekStart(body.Week)
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, "invalid week parameter") writeError(w, http.StatusBadRequest, "invalid week parameter")
return return
@@ -302,7 +302,7 @@ func (h *Handler) GenerateShoppingList(w http.ResponseWriter, r *http.Request) {
} }
_ = json.NewDecoder(r.Body).Decode(&body) _ = json.NewDecoder(r.Body).Decode(&body)
weekStart, err := resolveWeekStart(body.Week) weekStart, err := ResolveWeekStart(body.Week)
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, "invalid week parameter") writeError(w, http.StatusBadRequest, "invalid week parameter")
return return
@@ -342,7 +342,7 @@ func (h *Handler) GetShoppingList(w http.ResponseWriter, r *http.Request) {
return return
} }
weekStart, err := resolveWeekStart(r.URL.Query().Get("week")) weekStart, err := ResolveWeekStart(r.URL.Query().Get("week"))
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, "invalid week parameter") writeError(w, http.StatusBadRequest, "invalid week parameter")
return return
@@ -392,7 +392,7 @@ func (h *Handler) ToggleShoppingItem(w http.ResponseWriter, r *http.Request) {
return return
} }
weekStart, err := resolveWeekStart(r.URL.Query().Get("week")) weekStart, err := ResolveWeekStart(r.URL.Query().Get("week"))
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, "invalid week parameter") writeError(w, http.StatusBadRequest, "invalid week parameter")
return return
@@ -477,7 +477,7 @@ func recipeToCreateRequest(r ai.Recipe) dish.CreateRequest {
cr := dish.CreateRequest{ cr := dish.CreateRequest{
Name: r.Title, Name: r.Title,
Description: r.Description, Description: r.Description,
CuisineSlug: mapCuisineSlug(r.Cuisine), CuisineSlug: MapCuisineSlug(r.Cuisine),
ImageURL: r.ImageURL, ImageURL: r.ImageURL,
Difficulty: r.Difficulty, Difficulty: r.Difficulty,
PrepTimeMin: r.PrepTimeMin, PrepTimeMin: r.PrepTimeMin,
@@ -507,9 +507,9 @@ func recipeToCreateRequest(r ai.Recipe) dish.CreateRequest {
return cr return cr
} }
// mapCuisineSlug maps a free-form cuisine string (from Gemini) to a known slug. // MapCuisineSlug maps a free-form cuisine string (from Gemini) to a known slug.
// Falls back to "other". // Falls back to "other".
func mapCuisineSlug(cuisine string) string { func MapCuisineSlug(cuisine string) string {
known := map[string]string{ known := map[string]string{
"russian": "russian", "russian": "russian",
"italian": "italian", "italian": "italian",
@@ -538,8 +538,8 @@ func mapCuisineSlug(cuisine string) string {
return "other" return "other"
} }
// resolveWeekStart parses "YYYY-WNN" or returns current week's Monday. // ResolveWeekStart parses "YYYY-WNN" or returns current week's Monday.
func resolveWeekStart(week string) (string, error) { func ResolveWeekStart(week string) (string, error) {
if week == "" { if week == "" {
return currentWeekStart(), nil return currentWeekStart(), nil
} }

View File

@@ -1,6 +1,7 @@
package product package product
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"log/slog" "log/slog"
@@ -10,13 +11,22 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
) )
// ProductRepository is the data layer interface used by Handler.
type ProductRepository interface {
List(ctx context.Context, userID string) ([]*Product, error)
Create(ctx context.Context, userID string, req CreateRequest) (*Product, error)
BatchCreate(ctx context.Context, userID string, items []CreateRequest) ([]*Product, error)
Update(ctx context.Context, id, userID string, req UpdateRequest) (*Product, error)
Delete(ctx context.Context, id, userID string) error
}
// Handler handles /products HTTP requests. // Handler handles /products HTTP requests.
type Handler struct { type Handler struct {
repo *Repository repo ProductRepository
} }
// NewHandler creates a new Handler. // NewHandler creates a new Handler.
func NewHandler(repo *Repository) *Handler { func NewHandler(repo ProductRepository) *Handler {
return &Handler{repo: repo} return &Handler{repo: repo}
} }

View File

@@ -0,0 +1,36 @@
package mocks
import (
"context"
"github.com/food-ai/backend/internal/domain/product"
)
// MockProductRepository is a test double implementing product.ProductRepository.
type MockProductRepository struct {
ListFn func(ctx context.Context, userID string) ([]*product.Product, error)
CreateFn func(ctx context.Context, userID string, req product.CreateRequest) (*product.Product, error)
BatchCreateFn func(ctx context.Context, userID string, items []product.CreateRequest) ([]*product.Product, error)
UpdateFn func(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error)
DeleteFn func(ctx context.Context, id, userID string) error
}
func (m *MockProductRepository) List(ctx context.Context, userID string) ([]*product.Product, error) {
return m.ListFn(ctx, userID)
}
func (m *MockProductRepository) Create(ctx context.Context, userID string, req product.CreateRequest) (*product.Product, error) {
return m.CreateFn(ctx, userID, req)
}
func (m *MockProductRepository) BatchCreate(ctx context.Context, userID string, items []product.CreateRequest) ([]*product.Product, error) {
return m.BatchCreateFn(ctx, userID, items)
}
func (m *MockProductRepository) Update(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error) {
return m.UpdateFn(ctx, id, userID, req)
}
func (m *MockProductRepository) Delete(ctx context.Context, id, userID string) error {
return m.DeleteFn(ctx, id, userID)
}

View File

@@ -134,7 +134,7 @@ func (h *Handler) RecognizeProducts(w http.ResponseWriter, r *http.Request) {
} }
wg.Wait() wg.Wait()
merged := mergeAndDeduplicate(allItems) merged := MergeAndDeduplicate(allItems)
enriched := h.enrichItems(r.Context(), merged) enriched := h.enrichItems(r.Context(), merged)
writeJSON(w, http.StatusOK, map[string]any{"items": enriched}) writeJSON(w, http.StatusOK, map[string]any{"items": enriched})
} }
@@ -258,9 +258,9 @@ func (h *Handler) saveClassification(ctx context.Context, c *ai.IngredientClassi
return saved return saved
} }
// mergeAndDeduplicate combines results from multiple images. // MergeAndDeduplicate combines results from multiple images.
// Items sharing the same name (case-insensitive) have their quantities summed. // Items sharing the same name (case-insensitive) have their quantities summed.
func mergeAndDeduplicate(batches [][]ai.RecognizedItem) []ai.RecognizedItem { func MergeAndDeduplicate(batches [][]ai.RecognizedItem) []ai.RecognizedItem {
seen := make(map[string]*ai.RecognizedItem) seen := make(map[string]*ai.RecognizedItem)
var order []string var order []string

View File

@@ -1,6 +1,7 @@
package savedrecipe package savedrecipe
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"log/slog" "log/slog"
@@ -12,13 +13,21 @@ import (
const maxBodySize = 1 << 20 // 1 MB const maxBodySize = 1 << 20 // 1 MB
// SavedRecipeRepository is the data layer interface used by Handler.
type SavedRecipeRepository interface {
Save(ctx context.Context, userID string, req SaveRequest) (*UserSavedRecipe, error)
List(ctx context.Context, userID string) ([]*UserSavedRecipe, error)
GetByID(ctx context.Context, userID, id string) (*UserSavedRecipe, error)
Delete(ctx context.Context, userID, id string) error
}
// Handler handles HTTP requests for saved recipes. // Handler handles HTTP requests for saved recipes.
type Handler struct { type Handler struct {
repo *Repository repo SavedRecipeRepository
} }
// NewHandler creates a new Handler. // NewHandler creates a new Handler.
func NewHandler(repo *Repository) *Handler { func NewHandler(repo SavedRecipeRepository) *Handler {
return &Handler{repo: repo} return &Handler{repo: repo}
} }

View File

@@ -0,0 +1,31 @@
package mocks
import (
"context"
"github.com/food-ai/backend/internal/domain/savedrecipe"
)
// MockSavedRecipeRepository is a test double implementing savedrecipe.SavedRecipeRepository.
type MockSavedRecipeRepository struct {
SaveFn func(ctx context.Context, userID string, req savedrecipe.SaveRequest) (*savedrecipe.UserSavedRecipe, error)
ListFn func(ctx context.Context, userID string) ([]*savedrecipe.UserSavedRecipe, error)
GetByIDFn func(ctx context.Context, userID, id string) (*savedrecipe.UserSavedRecipe, error)
DeleteFn func(ctx context.Context, userID, id string) error
}
func (m *MockSavedRecipeRepository) Save(ctx context.Context, userID string, req savedrecipe.SaveRequest) (*savedrecipe.UserSavedRecipe, error) {
return m.SaveFn(ctx, userID, req)
}
func (m *MockSavedRecipeRepository) List(ctx context.Context, userID string) ([]*savedrecipe.UserSavedRecipe, error) {
return m.ListFn(ctx, userID)
}
func (m *MockSavedRecipeRepository) GetByID(ctx context.Context, userID, id string) (*savedrecipe.UserSavedRecipe, error) {
return m.GetByIDFn(ctx, userID, id)
}
func (m *MockSavedRecipeRepository) Delete(ctx context.Context, userID, id string) error {
return m.DeleteFn(ctx, userID, id)
}

View File

@@ -34,7 +34,7 @@ func (r *Repository) Save(ctx context.Context, userID string, req SaveRequest) (
cr := dish.CreateRequest{ cr := dish.CreateRequest{
Name: req.Title, Name: req.Title,
Description: req.Description, Description: req.Description,
CuisineSlug: mapCuisineSlug(req.Cuisine), CuisineSlug: MapCuisineSlug(req.Cuisine),
ImageURL: req.ImageURL, ImageURL: req.ImageURL,
Source: req.Source, Source: req.Source,
Difficulty: req.Difficulty, Difficulty: req.Difficulty,
@@ -373,9 +373,9 @@ func scanUSR(s rowScanner) (*UserSavedRecipe, error) {
return &r, err return &r, err
} }
// mapCuisineSlug maps a free-form cuisine string (from Gemini) to a known slug. // MapCuisineSlug maps a free-form cuisine string (from Gemini) to a known slug.
// Falls back to "other". // Falls back to "other".
func mapCuisineSlug(cuisine string) string { func MapCuisineSlug(cuisine string) string {
known := map[string]string{ known := map[string]string{
"russian": "russian", "russian": "russian",
"italian": "italian", "italian": "italian",

View File

@@ -0,0 +1,183 @@
package diary_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/food-ai/backend/internal/domain/diary"
diarymocks "github.com/food-ai/backend/internal/domain/diary/mocks"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
// alwaysAuthValidator injects a fixed user ID via the Auth middleware.
type alwaysAuthValidator struct{ userID string }
func (v *alwaysAuthValidator) ValidateAccessToken(_ string) (*middleware.TokenClaims, error) {
return &middleware.TokenClaims{UserID: v.userID}, nil
}
// buildRouter wraps handler methods with auth middleware on a chi router.
func buildRouter(handler *diary.Handler, userID string) *chi.Mux {
router := chi.NewRouter()
router.Use(middleware.Auth(&alwaysAuthValidator{userID: userID}))
router.Get("/diary", handler.GetByDate)
router.Post("/diary", handler.Create)
router.Delete("/diary/{id}", handler.Delete)
return router
}
func authorizedRequest(method, target string, body []byte) *http.Request {
request := httptest.NewRequest(method, target, bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer test-token")
request.Header.Set("Content-Type", "application/json")
return request
}
func TestGetByDate_MissingQueryParam(t *testing.T) {
handler := diary.NewHandler(&diarymocks.MockDiaryRepository{})
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/diary", nil))
if recorder.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", recorder.Code)
}
}
func TestGetByDate_Success(t *testing.T) {
mockRepo := &diarymocks.MockDiaryRepository{
ListByDateFn: func(ctx context.Context, userID, date string) ([]*diary.Entry, error) {
return []*diary.Entry{
{ID: "entry-1", Date: date, MealType: "breakfast", Name: "Oatmeal", Portions: 1},
}, nil
},
}
handler := diary.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/diary?date=2026-03-15", nil))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
var entries []diary.Entry
if decodeError := json.NewDecoder(recorder.Body).Decode(&entries); decodeError != nil {
t.Fatalf("decode response: %v", decodeError)
}
if len(entries) != 1 {
t.Errorf("expected 1 entry, got %d", len(entries))
}
}
func TestCreate_MissingDate(t *testing.T) {
handler := diary.NewHandler(&diarymocks.MockDiaryRepository{})
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(map[string]string{"name": "Oatmeal", "meal_type": "breakfast"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/diary", body))
if recorder.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", recorder.Code)
}
}
func TestCreate_MissingName(t *testing.T) {
handler := diary.NewHandler(&diarymocks.MockDiaryRepository{})
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(map[string]string{"date": "2026-03-15", "meal_type": "breakfast"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/diary", body))
if recorder.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", recorder.Code)
}
}
func TestCreate_MissingMealType(t *testing.T) {
handler := diary.NewHandler(&diarymocks.MockDiaryRepository{})
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(map[string]string{"date": "2026-03-15", "name": "Oatmeal"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/diary", body))
if recorder.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", recorder.Code)
}
}
func TestCreate_Success(t *testing.T) {
mockRepo := &diarymocks.MockDiaryRepository{
CreateFn: func(ctx context.Context, userID string, req diary.CreateRequest) (*diary.Entry, error) {
return &diary.Entry{
ID: "entry-1",
Date: req.Date,
MealType: req.MealType,
Name: req.Name,
Portions: 1,
Source: "manual",
CreatedAt: time.Now(),
}, nil
},
}
handler := diary.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(diary.CreateRequest{
Date: "2026-03-15",
MealType: "breakfast",
Name: "Oatmeal",
Portions: 1,
})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/diary", body))
if recorder.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", recorder.Code)
}
}
func TestDelete_NotFound(t *testing.T) {
mockRepo := &diarymocks.MockDiaryRepository{
DeleteFn: func(ctx context.Context, id, userID string) error {
return diary.ErrNotFound
},
}
handler := diary.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/diary/nonexistent-id", nil))
if recorder.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", recorder.Code)
}
}
func TestDelete_Success(t *testing.T) {
mockRepo := &diarymocks.MockDiaryRepository{
DeleteFn: func(ctx context.Context, id, userID string) error {
return nil
},
}
handler := diary.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/diary/entry-1", nil))
if recorder.Code != http.StatusNoContent {
t.Errorf("expected 204, got %d", recorder.Code)
}
}

View File

@@ -0,0 +1,118 @@
//go:build integration
package diary_test
import (
"context"
"testing"
"github.com/food-ai/backend/internal/domain/diary"
"github.com/food-ai/backend/internal/testutil"
)
func TestDiaryRepository_Create_Defaults(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := diary.NewRepository(pool)
requestContext := context.Background()
// portions=0 → repository sets 1; source="" → repository sets "manual"
entry, createError := repo.Create(requestContext, "test-user", diary.CreateRequest{
Date: "2026-03-15",
MealType: "breakfast",
Name: "Oatmeal",
Portions: 0,
Source: "",
})
if createError != nil {
t.Fatalf("create diary entry: %v", createError)
}
if entry.Portions != 1 {
t.Errorf("expected portions=1, got %v", entry.Portions)
}
if entry.Source != "manual" {
t.Errorf("expected source=manual, got %q", entry.Source)
}
}
func TestDiaryRepository_ListByDate(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := diary.NewRepository(pool)
requestContext := context.Background()
userID := "list-date-user"
date := "2026-03-15"
_, createError := repo.Create(requestContext, userID, diary.CreateRequest{
Date: date, MealType: "breakfast", Name: "Oatmeal",
})
if createError != nil {
t.Fatalf("create first entry: %v", createError)
}
_, createError = repo.Create(requestContext, userID, diary.CreateRequest{
Date: date, MealType: "lunch", Name: "Salad",
})
if createError != nil {
t.Fatalf("create second entry: %v", createError)
}
entries, listError := repo.ListByDate(requestContext, userID, date)
if listError != nil {
t.Fatalf("list by date: %v", listError)
}
if len(entries) != 2 {
t.Errorf("expected 2 entries, got %d", len(entries))
}
}
func TestDiaryRepository_ListByDate_OtherUserNotReturned(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := diary.NewRepository(pool)
requestContext := context.Background()
date := "2026-03-15"
_, createError := repo.Create(requestContext, "user-A", diary.CreateRequest{
Date: date, MealType: "breakfast", Name: "Eggs",
})
if createError != nil {
t.Fatalf("create entry for user-A: %v", createError)
}
entries, listError := repo.ListByDate(requestContext, "user-B", date)
if listError != nil {
t.Fatalf("list by date for user-B: %v", listError)
}
if len(entries) != 0 {
t.Errorf("expected 0 entries for user-B, got %d", len(entries))
}
}
func TestDiaryRepository_Delete_NotFound(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := diary.NewRepository(pool)
requestContext := context.Background()
deleteError := repo.Delete(requestContext, "00000000-0000-0000-0000-000000000000", "any-user")
if deleteError != diary.ErrNotFound {
t.Errorf("expected ErrNotFound, got %v", deleteError)
}
}
func TestDiaryRepository_Delete_WrongUser(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := diary.NewRepository(pool)
requestContext := context.Background()
entry, createError := repo.Create(requestContext, "owner-user", diary.CreateRequest{
Date: "2026-03-15", MealType: "dinner", Name: "Pasta",
})
if createError != nil {
t.Fatalf("create entry: %v", createError)
}
// Attempt to delete another user's entry — should return ErrNotFound.
deleteError := repo.Delete(requestContext, entry.ID, "different-user")
if deleteError != diary.ErrNotFound {
t.Errorf("expected ErrNotFound when deleting another user's entry, got %v", deleteError)
}
}

View File

@@ -0,0 +1,157 @@
package ingredient_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/food-ai/backend/internal/domain/ingredient"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
// mockIngredientSearcher is an inline mock for ingredient.IngredientSearcher.
type mockIngredientSearcher struct {
searchFn func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error)
}
func (m *mockIngredientSearcher) Search(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
return m.searchFn(ctx, query, limit)
}
type alwaysAuthValidator struct{ userID string }
func (v *alwaysAuthValidator) ValidateAccessToken(_ string) (*middleware.TokenClaims, error) {
return &middleware.TokenClaims{UserID: v.userID}, nil
}
func buildRouter(handler *ingredient.Handler) *chi.Mux {
router := chi.NewRouter()
router.Use(middleware.Auth(&alwaysAuthValidator{userID: "user-1"}))
router.Get("/ingredients/search", handler.Search)
return router
}
func authorizedRequest(target string) *http.Request {
request := httptest.NewRequest(http.MethodGet, target, bytes.NewReader(nil))
request.Header.Set("Authorization", "Bearer test-token")
return request
}
func TestSearch_EmptyQuery_ReturnsEmptyArray(t *testing.T) {
// When q is empty, the handler returns [] without calling the repository.
handler := ingredient.NewHandler(&mockIngredientSearcher{})
router := buildRouter(handler)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search"))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
if body := recorder.Body.String(); body != "[]" {
t.Errorf("expected body [], got %q", body)
}
}
func TestSearch_LimitTooLarge_UsesDefault(t *testing.T) {
// When limit > 50, the handler ignores it and uses default 10.
calledLimit := 0
mockRepo := &mockIngredientSearcher{
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
calledLimit = limit
return []*ingredient.IngredientMapping{}, nil
},
}
handler := ingredient.NewHandler(mockRepo)
router := buildRouter(handler)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple&limit=100"))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
if calledLimit != 10 {
t.Errorf("expected repo called with limit=10 (default), got %d", calledLimit)
}
}
func TestSearch_DefaultLimit(t *testing.T) {
// When no limit is supplied, the handler uses default 10.
calledLimit := 0
mockRepo := &mockIngredientSearcher{
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
calledLimit = limit
return []*ingredient.IngredientMapping{}, nil
},
}
handler := ingredient.NewHandler(mockRepo)
router := buildRouter(handler)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple"))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
if calledLimit != 10 {
t.Errorf("expected default limit 10, got %d", calledLimit)
}
}
func TestSearch_ValidLimit(t *testing.T) {
// limit=25 is within range and should be forwarded as-is.
calledLimit := 0
mockRepo := &mockIngredientSearcher{
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
calledLimit = limit
return []*ingredient.IngredientMapping{}, nil
},
}
handler := ingredient.NewHandler(mockRepo)
router := buildRouter(handler)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple&limit=25"))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
if calledLimit != 25 {
t.Errorf("expected limit 25, got %d", calledLimit)
}
}
func TestSearch_Success(t *testing.T) {
mockRepo := &mockIngredientSearcher{
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
return []*ingredient.IngredientMapping{
{ID: "ing-1", CanonicalName: "apple"},
}, nil
},
}
handler := ingredient.NewHandler(mockRepo)
router := buildRouter(handler)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple"))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
var mappings []ingredient.IngredientMapping
if decodeError := json.NewDecoder(recorder.Body).Decode(&mappings); decodeError != nil {
t.Fatalf("decode response: %v", decodeError)
}
if len(mappings) != 1 {
t.Errorf("expected 1 result, got %d", len(mappings))
}
if mappings[0].CanonicalName != "apple" {
t.Errorf("expected canonical_name=apple, got %q", mappings[0].CanonicalName)
}
}

View File

@@ -3,11 +3,21 @@ package locale_test
import ( import (
"context" "context"
"net/http" "net/http"
"os"
"testing" "testing"
"github.com/food-ai/backend/internal/infra/locale" "github.com/food-ai/backend/internal/infra/locale"
) )
func TestMain(m *testing.M) {
// Populate Supported map with all known languages before running tests.
// In production this is done by locale.LoadFromDB at startup.
for _, code := range []string{"en", "ru", "es", "de", "fr", "it", "pt", "zh", "ja", "ko", "ar", "hi"} {
locale.Supported[code] = true
}
os.Exit(m.Run())
}
func TestParse(t *testing.T) { func TestParse(t *testing.T) {
tests := []struct { tests := []struct {
name string name string

View File

@@ -0,0 +1,61 @@
package menu_test
import (
"testing"
"github.com/food-ai/backend/internal/domain/menu"
)
func TestResolveWeekStart_ValidFormat(t *testing.T) {
// ISO week 1 of 2026 starts on Monday 2025-12-29
result, resolveError := menu.ResolveWeekStart("2026-W01")
if resolveError != nil {
t.Fatalf("unexpected error: %v", resolveError)
}
if result != "2025-12-29" {
t.Errorf("ResolveWeekStart(2026-W01) = %q, want %q", result, "2025-12-29")
}
}
func TestResolveWeekStart_Week10(t *testing.T) {
// Week 10 of 2026 starts on Monday 2026-03-02
result, resolveError := menu.ResolveWeekStart("2026-W10")
if resolveError != nil {
t.Fatalf("unexpected error: %v", resolveError)
}
if result != "2026-03-02" {
t.Errorf("ResolveWeekStart(2026-W10) = %q, want %q", result, "2026-03-02")
}
}
func TestResolveWeekStart_InvalidFormat(t *testing.T) {
_, resolveError := menu.ResolveWeekStart("2026-01-05")
if resolveError == nil {
t.Fatal("expected error for date format input, got nil")
}
}
func TestResolveWeekStart_InvalidWeekNum(t *testing.T) {
_, resolveError := menu.ResolveWeekStart("2026-W99")
if resolveError == nil {
t.Fatal("expected error for week 99, got nil")
}
}
func TestResolveWeekStart_WeekZero(t *testing.T) {
_, resolveError := menu.ResolveWeekStart("2026-W00")
if resolveError == nil {
t.Fatal("expected error for week 0, got nil")
}
}
func TestResolveWeekStart_EmptyReturnsCurrentMonday(t *testing.T) {
// Empty string should return current week's Monday without error.
result, resolveError := menu.ResolveWeekStart("")
if resolveError != nil {
t.Fatalf("unexpected error: %v", resolveError)
}
if len(result) != 10 {
t.Errorf("expected date in YYYY-MM-DD format, got %q", result)
}
}

View File

@@ -0,0 +1,200 @@
package product_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/food-ai/backend/internal/domain/product"
productmocks "github.com/food-ai/backend/internal/domain/product/mocks"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
type alwaysAuthValidator struct{ userID string }
func (v *alwaysAuthValidator) ValidateAccessToken(_ string) (*middleware.TokenClaims, error) {
return &middleware.TokenClaims{UserID: v.userID}, nil
}
func buildRouter(handler *product.Handler, userID string) *chi.Mux {
router := chi.NewRouter()
router.Use(middleware.Auth(&alwaysAuthValidator{userID: userID}))
router.Get("/products", handler.List)
router.Post("/products", handler.Create)
router.Post("/products/batch", handler.BatchCreate)
router.Put("/products/{id}", handler.Update)
router.Delete("/products/{id}", handler.Delete)
return router
}
func authorizedRequest(method, target string, body []byte) *http.Request {
request := httptest.NewRequest(method, target, bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer test-token")
request.Header.Set("Content-Type", "application/json")
return request
}
func makeProduct(name string) *product.Product {
return &product.Product{
ID: "prod-1",
UserID: "user-1",
Name: name,
Quantity: 1,
Unit: "pcs",
StorageDays: 7,
AddedAt: time.Now(),
ExpiresAt: time.Now().AddDate(0, 0, 7),
DaysLeft: 7,
}
}
func TestList_Success(t *testing.T) {
mockRepo := &productmocks.MockProductRepository{
ListFn: func(ctx context.Context, userID string) ([]*product.Product, error) {
return []*product.Product{makeProduct("Milk")}, nil
},
}
handler := product.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/products", nil))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
}
func TestCreate_MissingName(t *testing.T) {
handler := product.NewHandler(&productmocks.MockProductRepository{})
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(map[string]any{"quantity": 1})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/products", body))
if recorder.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", recorder.Code)
}
}
func TestCreate_Success(t *testing.T) {
mockRepo := &productmocks.MockProductRepository{
CreateFn: func(ctx context.Context, userID string, req product.CreateRequest) (*product.Product, error) {
return makeProduct(req.Name), nil
},
}
handler := product.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(product.CreateRequest{Name: "Milk", Quantity: 1, Unit: "L"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/products", body))
if recorder.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", recorder.Code)
}
}
func TestBatchCreate_Success(t *testing.T) {
mockRepo := &productmocks.MockProductRepository{
BatchCreateFn: func(ctx context.Context, userID string, items []product.CreateRequest) ([]*product.Product, error) {
result := make([]*product.Product, len(items))
for index, item := range items {
result[index] = makeProduct(item.Name)
}
return result, nil
},
}
handler := product.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
body, _ := json.Marshal([]product.CreateRequest{
{Name: "Milk", Quantity: 1, Unit: "L"},
{Name: "Eggs", Quantity: 12, Unit: "pcs"},
})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/products/batch", body))
if recorder.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", recorder.Code)
}
}
func TestUpdate_NotFound(t *testing.T) {
mockRepo := &productmocks.MockProductRepository{
UpdateFn: func(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error) {
return nil, product.ErrNotFound
},
}
handler := product.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
namePtr := "NewName"
body, _ := json.Marshal(product.UpdateRequest{Name: &namePtr})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/products/nonexistent", body))
if recorder.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", recorder.Code)
}
}
func TestUpdate_Success(t *testing.T) {
mockRepo := &productmocks.MockProductRepository{
UpdateFn: func(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error) {
updated := makeProduct(*req.Name)
return updated, nil
},
}
handler := product.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
namePtr := "Oat Milk"
body, _ := json.Marshal(product.UpdateRequest{Name: &namePtr})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/products/prod-1", body))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
}
func TestDelete_NotFound(t *testing.T) {
mockRepo := &productmocks.MockProductRepository{
DeleteFn: func(ctx context.Context, id, userID string) error {
return product.ErrNotFound
},
}
handler := product.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/products/nonexistent", nil))
if recorder.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", recorder.Code)
}
}
func TestDelete_Success(t *testing.T) {
mockRepo := &productmocks.MockProductRepository{
DeleteFn: func(ctx context.Context, id, userID string) error {
return nil
},
}
handler := product.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/products/prod-1", nil))
if recorder.Code != http.StatusNoContent {
t.Errorf("expected 204, got %d", recorder.Code)
}
}

View File

@@ -0,0 +1,138 @@
//go:build integration
package product_test
import (
"context"
"testing"
"github.com/food-ai/backend/internal/domain/product"
"github.com/food-ai/backend/internal/testutil"
)
func TestProductRepository_Create_Defaults(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := product.NewRepository(pool)
requestContext := context.Background()
// storage_days=0 → 7; unit="" → "pcs"; quantity=0 → 1
created, createError := repo.Create(requestContext, "test-user", product.CreateRequest{
Name: "Milk",
StorageDays: 0,
Unit: "",
Quantity: 0,
})
if createError != nil {
t.Fatalf("create product: %v", createError)
}
if created.StorageDays != 7 {
t.Errorf("expected storage_days=7, got %d", created.StorageDays)
}
if created.Unit != "pcs" {
t.Errorf("expected unit=pcs, got %q", created.Unit)
}
if created.Quantity != 1 {
t.Errorf("expected quantity=1, got %v", created.Quantity)
}
}
func TestProductRepository_List_OrderByExpiry(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := product.NewRepository(pool)
requestContext := context.Background()
userID := "list-order-user"
// Create product with longer expiry first, shorter expiry second.
_, createError := repo.Create(requestContext, userID, product.CreateRequest{Name: "Milk", StorageDays: 14})
if createError != nil {
t.Fatalf("create Milk: %v", createError)
}
_, createError = repo.Create(requestContext, userID, product.CreateRequest{Name: "Butter", StorageDays: 3})
if createError != nil {
t.Fatalf("create Butter: %v", createError)
}
products, listError := repo.List(requestContext, userID)
if listError != nil {
t.Fatalf("list products: %v", listError)
}
if len(products) != 2 {
t.Fatalf("expected 2 products, got %d", len(products))
}
// Butter (3 days) should come before Milk (14 days).
if products[0].Name != "Butter" {
t.Errorf("expected first product Butter (expires sooner), got %q", products[0].Name)
}
}
func TestProductRepository_BatchCreate(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := product.NewRepository(pool)
requestContext := context.Background()
products, batchError := repo.BatchCreate(requestContext, "batch-user", []product.CreateRequest{
{Name: "Eggs", Quantity: 12, Unit: "pcs"},
{Name: "Flour", Quantity: 500, Unit: "g"},
})
if batchError != nil {
t.Fatalf("batch create: %v", batchError)
}
if len(products) != 2 {
t.Errorf("expected 2 products, got %d", len(products))
}
}
func TestProductRepository_Update_NotFound(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := product.NewRepository(pool)
requestContext := context.Background()
newName := "Ghost"
_, updateError := repo.Update(requestContext, "00000000-0000-0000-0000-000000000000", "any-user",
product.UpdateRequest{Name: &newName})
if updateError != product.ErrNotFound {
t.Errorf("expected ErrNotFound, got %v", updateError)
}
}
func TestProductRepository_Delete_WrongUser(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := product.NewRepository(pool)
requestContext := context.Background()
created, createError := repo.Create(requestContext, "owner-user", product.CreateRequest{Name: "Cheese"})
if createError != nil {
t.Fatalf("create product: %v", createError)
}
deleteError := repo.Delete(requestContext, created.ID, "other-user")
if deleteError != product.ErrNotFound {
t.Errorf("expected ErrNotFound when deleting another user's product, got %v", deleteError)
}
}
func TestProductRepository_ListForPrompt(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := product.NewRepository(pool)
requestContext := context.Background()
userID := "prompt-user"
_, createError := repo.Create(requestContext, userID, product.CreateRequest{
Name: "Tomatoes", Quantity: 4, Unit: "pcs", StorageDays: 5,
})
if createError != nil {
t.Fatalf("create product: %v", createError)
}
lines, listError := repo.ListForPrompt(requestContext, userID)
if listError != nil {
t.Fatalf("list for prompt: %v", listError)
}
if len(lines) != 1 {
t.Fatalf("expected 1 line, got %d", len(lines))
}
// Line should start with "- Tomatoes".
if len(lines[0]) < 11 || lines[0][:11] != "- Tomatoes " {
t.Errorf("unexpected prompt line format: %q", lines[0])
}
}

View File

@@ -6,16 +6,18 @@ import (
"context" "context"
"testing" "testing"
"github.com/food-ai/backend/internal/domain/dish"
"github.com/food-ai/backend/internal/domain/recipe" "github.com/food-ai/backend/internal/domain/recipe"
"github.com/food-ai/backend/internal/infra/locale"
"github.com/food-ai/backend/internal/testutil" "github.com/food-ai/backend/internal/testutil"
) )
func TestRecipeRepository_GetByID_NotFound(t *testing.T) { func TestRecipeRepository_GetByID_NotFound(t *testing.T) {
pool := testutil.SetupTestDB(t) pool := testutil.SetupTestDB(t)
repo := recipe.NewRepository(pool) repo := recipe.NewRepository(pool)
ctx := context.Background() requestContext := context.Background()
got, getError := repo.GetByID(ctx, "00000000-0000-0000-0000-000000000000") got, getError := repo.GetByID(requestContext, "00000000-0000-0000-0000-000000000000")
if getError != nil { if getError != nil {
t.Fatalf("unexpected error: %v", getError) t.Fatalf("unexpected error: %v", getError)
} }
@@ -27,10 +29,92 @@ func TestRecipeRepository_GetByID_NotFound(t *testing.T) {
func TestRecipeRepository_Count(t *testing.T) { func TestRecipeRepository_Count(t *testing.T) {
pool := testutil.SetupTestDB(t) pool := testutil.SetupTestDB(t)
repo := recipe.NewRepository(pool) repo := recipe.NewRepository(pool)
ctx := context.Background() requestContext := context.Background()
_, countError := repo.Count(ctx) _, countError := repo.Count(requestContext)
if countError != nil { if countError != nil {
t.Fatalf("count: %v", countError) t.Fatalf("count: %v", countError)
} }
} }
func TestRecipeRepository_GetByID_Found(t *testing.T) {
pool := testutil.SetupTestDB(t)
dishRepo := dish.NewRepository(pool)
recipeRepo := recipe.NewRepository(pool)
requestContext := context.Background()
recipeID, createError := dishRepo.Create(requestContext, dish.CreateRequest{
Name: "Test Pasta",
Description: "A simple pasta dish",
Source: "test",
Ingredients: []dish.IngredientInput{
{Name: "pasta", Amount: 200, Unit: "g"},
},
Steps: []dish.StepInput{
{Number: 1, Description: "Boil water"},
},
})
if createError != nil {
t.Fatalf("create dish+recipe: %v", createError)
}
found, getError := recipeRepo.GetByID(requestContext, recipeID)
if getError != nil {
t.Fatalf("get recipe: %v", getError)
}
if found == nil {
t.Fatal("expected recipe to be found, got nil")
}
if found.ID != recipeID {
t.Errorf("expected ID %q, got %q", recipeID, found.ID)
}
if len(found.Ingredients) != 1 {
t.Errorf("expected 1 ingredient, got %d", len(found.Ingredients))
}
if found.Ingredients[0].Name != "pasta" {
t.Errorf("expected ingredient name 'pasta', got %q", found.Ingredients[0].Name)
}
if len(found.Steps) != 1 {
t.Errorf("expected 1 step, got %d", len(found.Steps))
}
}
func TestRecipeRepository_GetByID_WithTranslation(t *testing.T) {
pool := testutil.SetupTestDB(t)
dishRepo := dish.NewRepository(pool)
recipeRepo := recipe.NewRepository(pool)
baseContext := context.Background()
recipeID, createError := dishRepo.Create(baseContext, dish.CreateRequest{
Name: "Pasta Bolognese",
Description: "Classic Italian pasta",
Source: "test",
})
if createError != nil {
t.Fatalf("create dish+recipe: %v", createError)
}
// Without translation context, the recipe should return English content.
enContext := locale.WithLang(baseContext, "en")
recipeEN, getError := recipeRepo.GetByID(enContext, recipeID)
if getError != nil {
t.Fatalf("get recipe (en): %v", getError)
}
if recipeEN == nil {
t.Fatal("expected recipe, got nil")
}
// With a language not having a translation, fallback to English should occur.
ruContext := locale.WithLang(baseContext, "ru")
recipeRU, getError := recipeRepo.GetByID(ruContext, recipeID)
if getError != nil {
t.Fatalf("get recipe (ru): %v", getError)
}
if recipeRU == nil {
t.Fatal("expected recipe with ru context, got nil")
}
// Both should refer to the same recipe ID.
if recipeEN.ID != recipeRU.ID {
t.Errorf("expected same recipe ID, got %q vs %q", recipeEN.ID, recipeRU.ID)
}
}

View File

@@ -0,0 +1,90 @@
package recognition_test
import (
"testing"
"github.com/food-ai/backend/internal/adapters/ai"
"github.com/food-ai/backend/internal/domain/recognition"
)
func TestMergeAndDeduplicate_SingleBatch(t *testing.T) {
batches := [][]ai.RecognizedItem{
{
{Name: "apple", Quantity: 2, Unit: "pcs", Confidence: 0.9},
{Name: "banana", Quantity: 3, Unit: "pcs", Confidence: 0.8},
},
}
result := recognition.MergeAndDeduplicate(batches)
if len(result) != 2 {
t.Fatalf("expected 2 items, got %d", len(result))
}
}
func TestMergeAndDeduplicate_Duplicate(t *testing.T) {
batches := [][]ai.RecognizedItem{
{{Name: "apple", Quantity: 2, Unit: "pcs", Confidence: 0.7}},
{{Name: "apple", Quantity: 3, Unit: "pcs", Confidence: 0.8}},
}
result := recognition.MergeAndDeduplicate(batches)
if len(result) != 1 {
t.Fatalf("expected 1 item after dedup, got %d", len(result))
}
if result[0].Quantity != 5 {
t.Errorf("expected quantity 5 (2+3), got %v", result[0].Quantity)
}
if result[0].Confidence != 0.8 {
t.Errorf("expected confidence 0.8 (higher), got %v", result[0].Confidence)
}
}
func TestMergeAndDeduplicate_CaseInsensitive(t *testing.T) {
batches := [][]ai.RecognizedItem{
{{Name: "Apple", Quantity: 1, Unit: "pcs", Confidence: 0.9}},
{{Name: "apple", Quantity: 2, Unit: "pcs", Confidence: 0.7}},
}
result := recognition.MergeAndDeduplicate(batches)
if len(result) != 1 {
t.Fatalf("expected 1 item (case-insensitive dedup), got %d", len(result))
}
if result[0].Quantity != 3 {
t.Errorf("expected quantity 3, got %v", result[0].Quantity)
}
}
func TestMergeAndDeduplicate_KeepsHigherConfidence(t *testing.T) {
batches := [][]ai.RecognizedItem{
{{Name: "milk", Quantity: 1, Unit: "L", Confidence: 0.5}},
{{Name: "milk", Quantity: 1, Unit: "L", Confidence: 0.95}},
}
result := recognition.MergeAndDeduplicate(batches)
if len(result) != 1 {
t.Fatalf("expected 1 item, got %d", len(result))
}
if result[0].Confidence != 0.95 {
t.Errorf("expected confidence 0.95, got %v", result[0].Confidence)
}
}
func TestMergeAndDeduplicate_Empty(t *testing.T) {
result := recognition.MergeAndDeduplicate([][]ai.RecognizedItem{})
if len(result) != 0 {
t.Errorf("expected empty result, got %d items", len(result))
}
}
func TestMergeAndDeduplicate_NilBatches(t *testing.T) {
batches := [][]ai.RecognizedItem{nil, nil}
result := recognition.MergeAndDeduplicate(batches)
if len(result) != 0 {
t.Errorf("expected empty result for nil batches, got %d items", len(result))
}
}

View File

@@ -0,0 +1,186 @@
package savedrecipe_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/food-ai/backend/internal/domain/savedrecipe"
savedrecipemocks "github.com/food-ai/backend/internal/domain/savedrecipe/mocks"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
type alwaysAuthValidator struct{ userID string }
func (v *alwaysAuthValidator) ValidateAccessToken(_ string) (*middleware.TokenClaims, error) {
return &middleware.TokenClaims{UserID: v.userID}, nil
}
func buildRouter(handler *savedrecipe.Handler, userID string) *chi.Mux {
router := chi.NewRouter()
router.Use(middleware.Auth(&alwaysAuthValidator{userID: userID}))
router.Post("/saved-recipes", handler.Save)
router.Get("/saved-recipes", handler.List)
router.Get("/saved-recipes/{id}", handler.GetByID)
router.Delete("/saved-recipes/{id}", handler.Delete)
return router
}
func authorizedRequest(method, target string, body []byte) *http.Request {
request := httptest.NewRequest(method, target, bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer test-token")
request.Header.Set("Content-Type", "application/json")
return request
}
func makeUserSavedRecipe(id string) *savedrecipe.UserSavedRecipe {
return &savedrecipe.UserSavedRecipe{
ID: id,
UserID: "user-1",
RecipeID: "recipe-1",
SavedAt: time.Now(),
DishName: "Pasta Carbonara",
Ingredients: []savedrecipe.RecipeIngredient{},
Steps: []savedrecipe.RecipeStep{},
Tags: []string{},
}
}
func TestSave_MissingTitleAndRecipeID(t *testing.T) {
handler := savedrecipe.NewHandler(&savedrecipemocks.MockSavedRecipeRepository{})
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(map[string]string{"cuisine": "italian"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/saved-recipes", body))
if recorder.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", recorder.Code)
}
}
func TestSave_WithTitle(t *testing.T) {
mockRepo := &savedrecipemocks.MockSavedRecipeRepository{
SaveFn: func(ctx context.Context, userID string, req savedrecipe.SaveRequest) (*savedrecipe.UserSavedRecipe, error) {
return makeUserSavedRecipe("saved-1"), nil
},
}
handler := savedrecipe.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(savedrecipe.SaveRequest{Title: "My Recipe"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/saved-recipes", body))
if recorder.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", recorder.Code)
}
}
func TestSave_WithRecipeID(t *testing.T) {
mockRepo := &savedrecipemocks.MockSavedRecipeRepository{
SaveFn: func(ctx context.Context, userID string, req savedrecipe.SaveRequest) (*savedrecipe.UserSavedRecipe, error) {
return makeUserSavedRecipe("saved-2"), nil
},
}
handler := savedrecipe.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(savedrecipe.SaveRequest{RecipeID: "recipe-42"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/saved-recipes", body))
if recorder.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", recorder.Code)
}
}
func TestList_Success(t *testing.T) {
mockRepo := &savedrecipemocks.MockSavedRecipeRepository{
ListFn: func(ctx context.Context, userID string) ([]*savedrecipe.UserSavedRecipe, error) {
return []*savedrecipe.UserSavedRecipe{makeUserSavedRecipe("saved-1")}, nil
},
}
handler := savedrecipe.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/saved-recipes", nil))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
}
func TestGetByID_NotFound(t *testing.T) {
mockRepo := &savedrecipemocks.MockSavedRecipeRepository{
GetByIDFn: func(ctx context.Context, userID, id string) (*savedrecipe.UserSavedRecipe, error) {
return nil, nil
},
}
handler := savedrecipe.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/saved-recipes/nonexistent", nil))
if recorder.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", recorder.Code)
}
}
func TestGetByID_Success(t *testing.T) {
mockRepo := &savedrecipemocks.MockSavedRecipeRepository{
GetByIDFn: func(ctx context.Context, userID, id string) (*savedrecipe.UserSavedRecipe, error) {
return makeUserSavedRecipe(id), nil
},
}
handler := savedrecipe.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/saved-recipes/saved-1", nil))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
}
func TestDelete_NotFound(t *testing.T) {
mockRepo := &savedrecipemocks.MockSavedRecipeRepository{
DeleteFn: func(ctx context.Context, userID, id string) error {
return savedrecipe.ErrNotFound
},
}
handler := savedrecipe.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/saved-recipes/nonexistent", nil))
if recorder.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", recorder.Code)
}
}
func TestDelete_Success(t *testing.T) {
mockRepo := &savedrecipemocks.MockSavedRecipeRepository{
DeleteFn: func(ctx context.Context, userID, id string) error {
return nil
},
}
handler := savedrecipe.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/saved-recipes/saved-1", nil))
if recorder.Code != http.StatusNoContent {
t.Errorf("expected 204, got %d", recorder.Code)
}
}

View File

@@ -0,0 +1,71 @@
package savedrecipe_test
import (
"testing"
"github.com/food-ai/backend/internal/domain/savedrecipe"
)
func TestMapCuisineSlug_KnownCuisines(t *testing.T) {
tests := []struct {
input string
want string
}{
{"italian", "italian"},
{"french", "french"},
{"russian", "russian"},
{"chinese", "chinese"},
{"japanese", "japanese"},
{"korean", "korean"},
{"mexican", "mexican"},
{"mediterranean", "mediterranean"},
{"indian", "indian"},
{"thai", "thai"},
{"american", "american"},
{"georgian", "georgian"},
{"spanish", "spanish"},
{"german", "german"},
{"middle_eastern", "middle_eastern"},
{"turkish", "turkish"},
{"greek", "greek"},
{"vietnamese", "vietnamese"},
}
for _, tc := range tests {
result := savedrecipe.MapCuisineSlug(tc.input)
if result != tc.want {
t.Errorf("MapCuisineSlug(%q) = %q, want %q", tc.input, result, tc.want)
}
}
}
func TestMapCuisineSlug_GenericFallsToOther(t *testing.T) {
for _, input := range []string{"asian", "european"} {
result := savedrecipe.MapCuisineSlug(input)
if result != "other" {
t.Errorf("MapCuisineSlug(%q) = %q, want %q", input, result, "other")
}
}
}
func TestMapCuisineSlug_Unknown(t *testing.T) {
result := savedrecipe.MapCuisineSlug("peruvian")
if result != "other" {
t.Errorf("MapCuisineSlug(peruvian) = %q, want %q", result, "other")
}
}
func TestMapCuisineSlug_Empty(t *testing.T) {
result := savedrecipe.MapCuisineSlug("")
if result != "other" {
t.Errorf("MapCuisineSlug() = %q, want %q", result, "other")
}
}
func TestMapCuisineSlug_CaseSensitive(t *testing.T) {
// The function does NOT lowercase — "ITALIAN" is unknown and falls back to "other".
result := savedrecipe.MapCuisineSlug("ITALIAN")
if result != "other" {
t.Errorf("MapCuisineSlug(ITALIAN) = %q, want %q", result, "other")
}
}