refactor: move all tests to backend/tests/ as black-box packages
All test files relocated from internal/X/ to tests/X/ and converted to package X_test, using only the public API of each package. - tests/auth/: jwt, service, handler integration tests - tests/middleware/: auth, request_id, recovery tests - tests/user/: calories, service, repository integration tests - tests/locale/: locale tests (already package locale_test, just moved) - tests/ingredient/: repository integration tests - tests/recipe/: repository integration tests mockUserRepo in tests/user/service_test.go redefined locally with fully-qualified user.* types. Unexported auth.refreshRequest replaced with a local testRefreshRequest struct in the integration test. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
193
backend/tests/middleware/auth_test.go
Normal file
193
backend/tests/middleware/auth_test.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package middleware_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/food-ai/backend/internal/middleware"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// testJWTClaims mirrors auth.Claims for test token generation without importing auth.
|
||||
type testJWTClaims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Plan string `json:"plan"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func generateTestToken(secret string, userID, plan string, duration time.Duration) string {
|
||||
claims := testJWTClaims{
|
||||
UserID: userID,
|
||||
Plan: plan,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, _ := token.SignedString([]byte(secret))
|
||||
return tokenString
|
||||
}
|
||||
|
||||
// testAccessValidator implements middleware.AccessTokenValidator for tests.
|
||||
type testAccessValidator struct {
|
||||
secret string
|
||||
}
|
||||
|
||||
func (v *testAccessValidator) ValidateAccessToken(tokenStr string) (*middleware.TokenClaims, error) {
|
||||
token, parseError := jwt.ParseWithClaims(tokenStr, &testJWTClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
}
|
||||
return []byte(v.secret), nil
|
||||
})
|
||||
if parseError != nil {
|
||||
return nil, parseError
|
||||
}
|
||||
claims, ok := token.Claims.(*testJWTClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
return &middleware.TokenClaims{UserID: claims.UserID, Plan: claims.Plan}, nil
|
||||
}
|
||||
|
||||
// failingValidator always returns an error.
|
||||
type failingValidator struct{}
|
||||
|
||||
func (v *failingValidator) ValidateAccessToken(tokenStr string) (*middleware.TokenClaims, error) {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
func TestAuth_ValidToken(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
token := generateTestToken("test-secret", "user-1", "free", 15*time.Minute)
|
||||
|
||||
handler := middleware.Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.UserIDFromCtx(r.Context())
|
||||
if userID != "user-1" {
|
||||
t.Errorf("expected user-1, got %s", userID)
|
||||
}
|
||||
plan := middleware.UserPlanFromCtx(r.Context())
|
||||
if plan != "free" {
|
||||
t.Errorf("expected free, got %s", plan)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_MissingHeader(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
|
||||
handler := middleware.Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_InvalidBearerFormat(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
|
||||
handler := middleware.Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Basic abc123")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_ExpiredToken(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
token := generateTestToken("test-secret", "user-1", "free", -1*time.Second)
|
||||
|
||||
handler := middleware.Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_InvalidToken(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
|
||||
handler := middleware.Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer invalid-token")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_PaidPlan(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
token := generateTestToken("test-secret", "user-1", "paid", 15*time.Minute)
|
||||
|
||||
handler := middleware.Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
plan := middleware.UserPlanFromCtx(r.Context())
|
||||
if plan != "paid" {
|
||||
t.Errorf("expected paid, got %s", plan)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_EmptyBearer(t *testing.T) {
|
||||
handler := middleware.Auth(&failingValidator{})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer ")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
51
backend/tests/middleware/recovery_test.go
Normal file
51
backend/tests/middleware/recovery_test.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package middleware_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/food-ai/backend/internal/middleware"
|
||||
)
|
||||
|
||||
func TestRecovery_NoPanic(t *testing.T) {
|
||||
handler := middleware.Recovery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecovery_CatchesPanic(t *testing.T) {
|
||||
handler := middleware.Recovery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
panic("test panic")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecovery_CatchesPanicWithError(t *testing.T) {
|
||||
handler := middleware.Recovery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
panic(42)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
61
backend/tests/middleware/request_id_test.go
Normal file
61
backend/tests/middleware/request_id_test.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package middleware_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/food-ai/backend/internal/middleware"
|
||||
)
|
||||
|
||||
func TestRequestID_GeneratesNew(t *testing.T) {
|
||||
handler := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := middleware.RequestIDFromCtx(r.Context())
|
||||
if id == "" {
|
||||
t.Error("expected non-empty request ID in context")
|
||||
}
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Header().Get("X-Request-ID") == "" {
|
||||
t.Error("expected X-Request-ID in response header")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestID_PreservesExisting(t *testing.T) {
|
||||
handler := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := middleware.RequestIDFromCtx(r.Context())
|
||||
if id != "existing-id" {
|
||||
t.Errorf("expected 'existing-id', got %q", id)
|
||||
}
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("X-Request-ID", "existing-id")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Header().Get("X-Request-ID") != "existing-id" {
|
||||
t.Error("expected preserved X-Request-ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestID_UniquePerRequest(t *testing.T) {
|
||||
var ids []string
|
||||
handler := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ids = append(ids, middleware.RequestIDFromCtx(r.Context()))
|
||||
}))
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
}
|
||||
|
||||
if ids[0] == ids[1] || ids[1] == ids[2] {
|
||||
t.Error("expected unique IDs for each request")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user