package notices import ( "context" "encoding/json" "net/http" "net/http/httptest" "testing" "time" "github.com/wangjia/pangolin/server/internal/codes" ) func TestListAndMarkRead(t *testing.T) { db := openDB(t) seedU(t, db, 1, "u1") st := NewStore(db) _, _ = st.InsertBroadcast(context.Background(), "news", "hello", "hello", "", "", "", time.Now().UTC(), nil) h := NewHandler(st) req := httptest.NewRequest(http.MethodGet, "/v1/notices", nil) req = req.WithContext(context.WithValue(req.Context(), codes.CtxKeyUserID, int64(1))) w := httptest.NewRecorder() h.List(w, req) if w.Code != 200 { t.Fatalf("code=%d body=%s", w.Code, w.Body) } var got struct { Notices []map[string]any `json:"notices"` UnreadCount int `json:"unread_count"` } _ = json.Unmarshal(w.Body.Bytes(), &got) if len(got.Notices) != 1 || got.UnreadCount != 1 { t.Fatalf("got %+v", got) } if got.Notices[0]["type"] != "news" || got.Notices[0]["unread"] != true { t.Fatalf("字段契约: %+v", got.Notices[0]) } // read → 再查 unread 清零 req2 := httptest.NewRequest(http.MethodPost, "/v1/notices/read", nil) req2 = req2.WithContext(context.WithValue(req2.Context(), codes.CtxKeyUserID, int64(1))) w2 := httptest.NewRecorder() h.MarkRead(w2, req2) if w2.Code != 200 { t.Fatalf("read code=%d", w2.Code) } w3 := httptest.NewRecorder() h.List(w3, req) _ = json.Unmarshal(w3.Body.Bytes(), &got) if got.UnreadCount != 0 { t.Fatalf("read 后 unread_count=%d", got.UnreadCount) } } func TestListUnauthorized(t *testing.T) { db := openDB(t) h := NewHandler(NewStore(db)) w := httptest.NewRecorder() h.List(w, httptest.NewRequest(http.MethodGet, "/v1/notices", nil)) if w.Code != http.StatusUnauthorized { t.Fatalf("code=%d want 401", w.Code) } }