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,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])
}
}