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:
183
backend/tests/diary/handler_test.go
Normal file
183
backend/tests/diary/handler_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
118
backend/tests/diary/repository_integration_test.go
Normal file
118
backend/tests/diary/repository_integration_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
157
backend/tests/ingredient/handler_test.go
Normal file
157
backend/tests/ingredient/handler_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,21 @@ package locale_test
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"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) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
61
backend/tests/menu/resolve_week_start_test.go
Normal file
61
backend/tests/menu/resolve_week_start_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
200
backend/tests/product/handler_test.go
Normal file
200
backend/tests/product/handler_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
138
backend/tests/product/repository_integration_test.go
Normal file
138
backend/tests/product/repository_integration_test.go
Normal 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])
|
||||
}
|
||||
}
|
||||
@@ -6,16 +6,18 @@ import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/food-ai/backend/internal/domain/dish"
|
||||
"github.com/food-ai/backend/internal/domain/recipe"
|
||||
"github.com/food-ai/backend/internal/infra/locale"
|
||||
"github.com/food-ai/backend/internal/testutil"
|
||||
)
|
||||
|
||||
func TestRecipeRepository_GetByID_NotFound(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
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 {
|
||||
t.Fatalf("unexpected error: %v", getError)
|
||||
}
|
||||
@@ -27,10 +29,92 @@ func TestRecipeRepository_GetByID_NotFound(t *testing.T) {
|
||||
func TestRecipeRepository_Count(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := recipe.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
requestContext := context.Background()
|
||||
|
||||
_, countError := repo.Count(ctx)
|
||||
_, countError := repo.Count(requestContext)
|
||||
if countError != nil {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
90
backend/tests/recognition/merge_test.go
Normal file
90
backend/tests/recognition/merge_test.go
Normal 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))
|
||||
}
|
||||
}
|
||||
186
backend/tests/savedrecipe/handler_test.go
Normal file
186
backend/tests/savedrecipe/handler_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
71
backend/tests/savedrecipe/map_cuisine_slug_test.go
Normal file
71
backend/tests/savedrecipe/map_cuisine_slug_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user