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" "strings" "testing" "github.com/go-chi/chi/v5" "github.com/go-chi/jwtauth/v5" ) func newEditArticleBodyRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux { userRepo := newVerifiedUserRepo() getUserUseCase := useCases.NewGetUserUseCase(userRepo) articleHandler := article.NewHandler( useCases.NewCreateArticleUseCase(articleRepo, &fakeBodyRenderer{}, discardRecorder), useCases.NewGetArticleUseCase(articleRepo, &fakeBodyRenderer{}), useCases.NewListArticlesUseCase(articleRepo, &fakeBodyRenderer{}), useCases.NewDeleteArticleUseCase(articleRepo, discardRecorder), useCases.NewUpdateArticleUseCase(articleRepo, &fakeBodyRenderer{}, discardRecorder), 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.Group(func(r chi.Router) { r.Use(jwtauth.Authenticator(token)) r.Use(middleware.RequireVerifiedUser(getUserUseCase)) r.Patch("/{id}", articleHandler.UpdateArticleBody) }) }) }) }) return r } func newEditArticleBodyTestRepo() *mockArticleRepo { repo := newMockArticleRepo() repo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update", Body: "Old body text", IsOnline: true} repo.articles[2] = domainArticle.Article{ID: 2, Title: "Draft: Kitchen Remodel", Body: "Draft notes", IsOnline: false} return repo } func setEditArticleBodyJwtCookie(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 newEditArticleBodyRequest(method, target string, body string) *http.Request { return httptest.NewRequest(method, target, bytes.NewBufferString(body)) } func TestEditArticleBodyHttp(t *testing.T) { validator.InitValidator() token := jwtauth.New("HS256", []byte("test-secret"), nil) t.Run("Editing an existing article's body updates only the body", func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/1", `{"body": "New body text"}`) setEditArticleBodyJwtCookie(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.Body != "New body text" || got.Title != "Backyard Renovation Update" || !got.IsOnline { t.Errorf("unexpected article: %+v", got) } stored := repo.articles[1] if stored.Body != "New body text" || stored.Title != "Backyard Renovation Update" || !stored.IsOnline { t.Errorf("unexpected stored article: %+v", stored) } }) t.Run("Editing an offline article's body leaves it offline", func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/2", `{"body": "Revised draft notes"}`) setEditArticleBodyJwtCookie(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.Body != "Revised draft notes" || got.IsOnline { t.Errorf("unexpected article: %+v", got) } }) t.Run("Editing an unknown article answers 404", func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/9999", `{"body": "New body text"}`) setEditArticleBodyJwtCookie(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()) } }) t.Run("A malformed id answers 400 before any repository call", func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/not-a-number", `{"body": "New body text"}`) setEditArticleBodyJwtCookie(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()) } }) t.Run("A non-JSON request body answers 400 with the body error message", func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/1", `not valid json`) setEditArticleBodyJwtCookie(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.BodyErrorMessage+"\n" { t.Errorf("unexpected body: %q", rec.Body.String()) } }) validationCases := []struct { name string payload string }{ {"empty body", `{"body": ""}`}, {"body over 10000 characters", `{"body": "` + strings.Repeat("a", 10001) + `"}`}, } for _, tc := range validationCases { t.Run("A body value that fails validation answers 400: "+tc.name, func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/1", tc.payload) setEditArticleBodyJwtCookie(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 repo.articles[1].Body != "Old body text" { t.Errorf("expected stored body to be unchanged, got %q", repo.articles[1].Body) } }) } t.Run("A response write failure is logged", func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/1", `{"body": "New body text"}`) setEditArticleBodyJwtCookie(t, req, token) var logOutput bytes.Buffer defaultLogOutput := log.Writer() log.SetOutput(&logOutput) defer log.SetOutput(defaultLogOutput) router.ServeHTTP(&erroringResponseWriter{}, req) if !strings.Contains(logOutput.String(), "Failed to write response") { t.Errorf("expected the write failure to be logged, got %q", logOutput.String()) } }) t.Run("Editing an article requires authentication", func(t *testing.T) { repo := newEditArticleBodyTestRepo() router := newEditArticleBodyRouter(repo, token) req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/1", `{"body": "New body text"}`) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusUnauthorized { t.Fatalf("expected status 401, got %d", rec.Code) } }) }