Files
wx_service/internal/expiry/handler_branches_test.go

70 lines
1.9 KiB
Go

package expiry
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestHandler_HealthzAndBadPathBranches(t *testing.T) {
r := newTestRouter(t)
// 覆盖 healthz。
{
db := newTestDB(t)
handler := NewHandler(NewService(NewRepository(db)))
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
handler.Healthz(c)
if w.Code != http.StatusOK {
t.Fatalf("healthz status=%d", w.Code)
}
}
// 覆盖错误分支。
badIDDelete := requestJSON(t, r, http.MethodDelete, "/api/expiry/items/abc", nil)
if badIDDelete.Code != http.StatusBadRequest {
t.Fatalf("expected bad id 400, got %d", badIDDelete.Code)
}
badDateCreate := requestJSON(t, r, http.MethodPost, "/api/expiry/items", map[string]interface{}{
"name": "错误日期",
"category": "food",
"production_date": "2026/01/01",
"expiry_date": "2030-01-01",
})
if badDateCreate.Code != http.StatusBadRequest {
t.Fatalf("expected bad date 400, got %d", badDateCreate.Code)
}
badStatus := requestJSON(t, r, http.MethodPost, "/api/expiry/items/1/status", map[string]interface{}{
"status": "invalid",
})
if badStatus.Code != http.StatusBadRequest && badStatus.Code != http.StatusNotFound {
t.Fatalf("expected bad status 400/404, got %d", badStatus.Code)
}
badList := requestJSON(t, r, http.MethodGet, "/api/expiry/items?status=bad", nil)
if badList.Code != http.StatusBadRequest {
t.Fatalf("expected bad filter 400, got %d", badList.Code)
}
}
func TestHandler_HelperWriters(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
writeExpiryServerError(c)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected 500, got %d", w.Code)
}
w2 := httptest.NewRecorder()
c2, _ := gin.CreateTestContext(w2)
writeExpirySuccess(c2, "ok", gin.H{"x": 1})
if w2.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w2.Code)
}
}