package test import ( "RenewCMS/api/handlers/article" "RenewCMS/api/middleware" "RenewCMS/api/pkg/apperr" validator "RenewCMS/api/pkg/validator" domainArticle "RenewCMS/internal/domain/article" "RenewCMS/internal/infrastructure/useCases" "bytes" "encoding/json" "log" "net/http" "net/http/httptest" "testing" "github.com/go-chi/chi/v5" "github.com/go-chi/jwtauth/v5" ) func newArticlePublishingRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux { userRepo := newVerifiedUserRepo() getUserUseCase := useCases.NewGetUserUseCase(userRepo) articleHandler := article.NewHandler( useCases.NewCreateArticleUseCase(articleRepo, &fakeBodyRenderer{}, discardRecorder, plainSites(), plainAuthors()), useCases.NewGetArticleUseCase(articleRepo, &fakeBodyRenderer{}), useCases.NewListArticlesUseCase(articleRepo, &fakeBodyRenderer{}, plainSites()), useCases.NewDeleteArticleUseCase(articleRepo, discardRecorder), useCases.NewUpdateArticleUseCase(articleRepo, &fakeBodyRenderer{}, discardRecorder, plainSites(), plainAuthors()), getUserUseCase, ) r := chi.NewRouter() r.Route("/v1", func(r chi.Router) { r.Route("/article", func(r chi.Router) { r.Group(func(r chi.Router) { r.Use(jwtauth.Verifier(token)) r.Get("/", articleHandler.ListArticles) r.Group(func(r chi.Router) { r.Use(jwtauth.Authenticator(token)) r.Use(middleware.RequireVerifiedUser(getUserUseCase)) r.Get("/{id}", articleHandler.GetArticle) r.Post("/", articleHandler.PostArticle) r.Delete("/{id}", articleHandler.DeleteArticle) r.Patch("/{id}/publish", articleHandler.PublishArticle) r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle) }) }) }) }) return r } func newPublishingTestArticleRepo() *mockArticleRepo { repo := newMockArticleRepo() repo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update", IsOnline: true} repo.articles[2] = domainArticle.Article{ID: 2, Title: "Draft: Kitchen Remodel", IsOnline: false} return repo } func setPublishingJwtCookie(t *testing.T, req *http.Request, token *jwtauth.JWTAuth) { t.Helper() _, tokenString, err := token.Encode(map[string]any{"user_id": uint32(1)}) if err != nil { t.Fatalf("failed to encode jwt: %v", err) } req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString}) } func TestArticlePublishingHttp(t *testing.T) { validator.InitValidator() token := jwtauth.New("HS256", []byte("test-secret"), nil) t.Run("Publishing an offline article makes it online", func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/2/publish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", rec.Code) } var got domainArticle.Article if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("failed to decode response: %v", err) } if got.ID != 2 || !got.IsOnline { t.Errorf("expected article 2 online, got %+v", got) } if !repo.articles[2].IsOnline { t.Errorf("expected repository article 2 to be online") } }) t.Run("Unpublishing an online article makes it offline", func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/1/unpublish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", rec.Code) } var got domainArticle.Article if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("failed to decode response: %v", err) } if got.ID != 1 || got.IsOnline { t.Errorf("expected article 1 offline, got %+v", got) } if repo.articles[1].IsOnline { t.Errorf("expected repository article 1 to be offline") } }) t.Run("Publishing an already-online article is idempotent", func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/1/publish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", rec.Code) } var got domainArticle.Article if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("failed to decode response: %v", err) } if got.ID != 1 || !got.IsOnline { t.Errorf("expected article 1 online, got %+v", got) } }) t.Run("Unpublishing an already-offline article is idempotent", func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/2/unpublish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", rec.Code) } var got domainArticle.Article if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("failed to decode response: %v", err) } if got.ID != 2 || got.IsOnline { t.Errorf("expected article 2 offline, got %+v", got) } }) notFoundCases := []struct { name string action string }{ {"publish", "publish"}, {"unpublish", "unpublish"}, } for _, tc := range notFoundCases { t.Run("Publishing or unpublishing an unknown article answers 404: "+tc.name, func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/9999/"+tc.action, nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusNotFound { t.Fatalf("expected status 404, got %d", rec.Code) } if rec.Body.String() != apperr.ArticleNotFoundErrorMessage+"\n" { t.Errorf("unexpected body: %q", rec.Body.String()) } }) } for _, tc := range notFoundCases { t.Run("A malformed id answers 400 before any repository call: "+tc.name, func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/not-a-number/"+tc.action, nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusBadRequest { t.Fatalf("expected status 400, got %d", rec.Code) } if rec.Body.String() != apperr.IdUint32ErrorMessage+"\n" { t.Errorf("unexpected body: %q", rec.Body.String()) } }) } for _, tc := range notFoundCases { t.Run("Publish and unpublish require authentication: "+tc.action, func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/1/"+tc.action, nil) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusUnauthorized { t.Fatalf("expected status 401, got %d", rec.Code) } }) } t.Run("Publishing an article makes it appear in the public online-only list", func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/2/publish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", rec.Code) } listReq := httptest.NewRequest(http.MethodGet, "/v1/article/", nil) listRec := httptest.NewRecorder() router.ServeHTTP(listRec, listReq) if listRec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", listRec.Code) } var articles []domainArticle.Article if err := json.Unmarshal(articleItemsJSON(listRec.Body.Bytes()), &articles); err != nil { t.Fatalf("failed to decode response: %v", err) } found := false for _, a := range articles { if a.ID == 2 { found = true } } if !found { t.Errorf("expected article 2 in the public listing, got %+v", articles) } }) t.Run("Publishing an article does not log a write failure on success", func(t *testing.T) { repo := newPublishingTestArticleRepo() router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/2/publish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() var logBuf bytes.Buffer previousOutput := log.Writer() log.SetOutput(&logBuf) defer log.SetOutput(previousOutput) router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", rec.Code) } if logBuf.Len() != 0 { t.Errorf("expected no write-failure log, got %q", logBuf.String()) } }) t.Run("A repository failure answers 500", func(t *testing.T) { repo := newPublishingTestArticleRepo() repo.fail.failNext("UpdateIsOnline") router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/1/publish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusInternalServerError { t.Fatalf("expected status 500, got %d", rec.Code) } }) t.Run("Unpublishing an article removes it from the public online-only list", func(t *testing.T) { repo := newPublishingTestArticleRepo() repo.articles[3] = domainArticle.Article{ID: 3, Title: "Still Online Article", IsOnline: true} router := newArticlePublishingRouter(repo, token) req := httptest.NewRequest(http.MethodPatch, "/v1/article/1/unpublish", nil) setPublishingJwtCookie(t, req, token) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", rec.Code) } listReq := httptest.NewRequest(http.MethodGet, "/v1/article/", nil) listRec := httptest.NewRecorder() router.ServeHTTP(listRec, listReq) if listRec.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", listRec.Code) } var articles []domainArticle.Article if err := json.Unmarshal(articleItemsJSON(listRec.Body.Bytes()), &articles); err != nil { t.Fatalf("failed to decode response: %v", err) } foundStillOnline := false for _, a := range articles { if a.ID == 1 { t.Errorf("expected article 1 absent from the public listing, got %+v", articles) } if a.ID == 3 { foundStillOnline = true } } if !foundStillOnline { t.Errorf("expected article 3 present in the public listing, got %+v", articles) } }) }