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" "errors" "fmt" "net/http" "net/http/httptest" "reflect" "strings" "testing" "github.com/go-chi/chi/v5" "github.com/go-chi/jwtauth/v5" ) func newArticleTitleRulesRouter(repo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux { userRepo := newVerifiedUserRepo() getUserUseCase := useCases.NewGetUserUseCase(userRepo) articleHandler := article.NewHandler( useCases.NewCreateArticleUseCase(repo, &fakeBodyRenderer{}, discardRecorder, plainSites(), plainAuthors()), useCases.NewGetArticleUseCase(repo, &fakeBodyRenderer{}), useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{}, plainSites()), useCases.NewDeleteArticleUseCase(repo, discardRecorder), useCases.NewUpdateArticleUseCase(repo, &fakeBodyRenderer{}, discardRecorder, plainSites(), plainAuthors(), newMockImageRepo()), getUserUseCase, ) r := chi.NewRouter() r.Route("/v1", func(r chi.Router) { r.Group(func(r chi.Router) { r.Use(jwtauth.Verifier(token)) r.Use(jwtauth.Authenticator(token)) r.Use(middleware.RequireVerifiedUser(getUserUseCase)) r.Route("/article", func(r chi.Router) { r.Post("/", articleHandler.PostArticle) }) }) }) return r } func postArticleRequest(t *testing.T, token *jwtauth.JWTAuth, title string, body string) *http.Request { t.Helper() payload, err := json.Marshal(map[string]string{"title": title, "body": body}) if err != nil { t.Fatalf("failed to marshal body: %v", err) } req := httptest.NewRequest(http.MethodPost, "/v1/article/", bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") setJwtCookie(t, req, token, 1) return req } func TestArticleTitleTagMatchesDomainBounds(t *testing.T) { field, ok := reflect.TypeOf(article.PostArticle{}).FieldByName("Title") if !ok { t.Fatal("expected PostArticle to have a Title field") } expected := fmt.Sprintf("required,min=%d,max=%d", domainArticle.MinTitleRunes, domainArticle.MaxTitleRunes) got := field.Tag.Get("validate") if got != expected { t.Errorf("expected validate tag %q, got %q", expected, got) } } func TestArticleTitleRunesInUseCase(t *testing.T) { cases := []struct { runeCount int created bool }{ {2, false}, {3, true}, {200, true}, {201, false}, } for _, tc := range cases { t.Run(fmt.Sprintf("rune_count_%d", tc.runeCount), func(t *testing.T) { repo := newMockArticleRepo() uc := useCases.NewCreateArticleUseCase(repo, &fakeBodyRenderer{}, discardRecorder, plainSites(), plainAuthors()) title := strings.Repeat("\U0001F600", tc.runeCount) result, err := uc.CreateArticle(testCtx, useCases.CreateArticleCommand{Title: title, Body: "Some body text"}) if tc.created { if err != nil { t.Fatalf("expected no error, got %v", err) } if !repo.createCalled { t.Errorf("expected the repository's Create to have been called") } if len(repo.articles) != 1 { t.Errorf("expected 1 article stored, got %d", len(repo.articles)) } if result.Title != title { t.Errorf("expected title %q, got %q", title, result.Title) } } else { if !errors.Is(err, domainArticle.ErrInvalidTitle) { t.Errorf("expected ErrInvalidTitle, got %v", err) } if repo.createCalled { t.Errorf("expected the repository's Create not to have been called") } if len(repo.articles) != 0 { t.Errorf("expected nothing stored, got %d article(s)", len(repo.articles)) } } }) } } func TestArticleTitleRunesOverHttp(t *testing.T) { validator.InitValidator() token := jwtauth.New("HS256", []byte("test-secret"), nil) cases := []struct { length int status int created bool }{ {2, http.StatusBadRequest, false}, {3, http.StatusCreated, true}, {200, http.StatusCreated, true}, {201, http.StatusBadRequest, false}, } for _, tc := range cases { t.Run(fmt.Sprintf("length_%d", tc.length), func(t *testing.T) { repo := newMockArticleRepo() router := newArticleTitleRulesRouter(repo, token) title := strings.Repeat("a", tc.length) req := postArticleRequest(t, token, title, "Some body text") rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != tc.status { t.Fatalf("expected status %d, got %d, body %q", tc.status, rec.Code, rec.Body.String()) } if !tc.created { if repo.createCalled { t.Errorf("expected Create not to have been called") } if strings.Contains(rec.Body.String(), apperr.ArticleTitleErrorMessage) { t.Errorf("expected a request-layer validation error, got the domain error message: %q", rec.Body.String()) } if strings.Contains(rec.Body.String(), "Failed to create article") { t.Errorf("expected a request-layer validation error, got the generic failure message: %q", rec.Body.String()) } } if tc.created { var got domainArticle.Article if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("failed to decode response: %v", err) } if got.IsOnline { t.Errorf("expected is_online false, got true") } if len(repo.articles) != 1 { t.Errorf("expected 1 article stored, got %d", len(repo.articles)) } } else { if len(repo.articles) != 0 { t.Errorf("expected nothing stored, got %d article(s)", len(repo.articles)) } } }) } t.Run("A 200-rune multibyte title is accepted end to end over HTTP", func(t *testing.T) { repo := newMockArticleRepo() router := newArticleTitleRulesRouter(repo, token) title := strings.Repeat("\U0001F600", 200) req := postArticleRequest(t, token, title, "Some body text") rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusCreated { t.Fatalf("expected status 201, got %d, body %q", rec.Code, rec.Body.String()) } var got domainArticle.Article if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { t.Fatalf("failed to decode response: %v", err) } if got.Title != title { t.Errorf("expected title %q, got %q", title, got.Title) } }) t.Run("The handler maps a domain title rejection to 400, not 500", func(t *testing.T) { repo := newMockArticleRepo() repo.fail.failNextWith("Create", domainArticle.ErrInvalidTitle) router := newArticleTitleRulesRouter(repo, token) req := postArticleRequest(t, token, "Valid Title", "Some body text") 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.ArticleTitleErrorMessage+"\n" { t.Errorf("unexpected body: %q", rec.Body.String()) } if strings.Contains(rec.Body.String(), "Failed to create article") { t.Errorf("did not expect the generic failure message, got %q", rec.Body.String()) } }) t.Run("A non-title repository failure during creation still answers 500", func(t *testing.T) { repo := newMockArticleRepo() repo.fail.failNext("Create") router := newArticleTitleRulesRouter(repo, token) req := postArticleRequest(t, token, "Valid Title", "Some body text") rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusInternalServerError { t.Fatalf("expected status 500, got %d", rec.Code) } if rec.Body.String() != "Failed to create article\n" { t.Errorf("unexpected body: %q", rec.Body.String()) } }) t.Run("POST /v1/article/ without a jwt cookie is rejected", func(t *testing.T) { repo := newMockArticleRepo() router := newArticleTitleRulesRouter(repo, token) payload, err := json.Marshal(map[string]string{"title": "Valid Title", "body": "Some body text"}) if err != nil { t.Fatalf("failed to marshal body: %v", err) } req := httptest.NewRequest(http.MethodPost, "/v1/article/", bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() router.ServeHTTP(rec, req) if rec.Code != http.StatusUnauthorized { t.Fatalf("expected status 401, got %d", rec.Code) } if repo.createCalled { t.Errorf("expected Create not to have been called") } }) }