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

@@ -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)
}
}