feat(API): media library
This commit is contained in:
1 parent
95ae043d3e
commit
0d99544579
65 files changed
+3992
-1530
No files matched your search
@@ -26,7 +26,7 @@ func newArticlePublishingRouter(articleRepo *mockArticleRepo, token *jwtauth.JWT
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
+19
-20
@@ -2,25 +2,24 @@ package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
imageDomain "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type mockArticleRepo struct {
|
||||
articles map[uint32]article.Article
|
||||
images map[uint32]*imageDomain.Image
|
||||
nextID uint32
|
||||
fail failSwitch
|
||||
createCalled bool
|
||||
articles map[uint32]article.Article
|
||||
failUpdateBodyFor map[uint32]error
|
||||
nextID uint32
|
||||
fail failSwitch
|
||||
createCalled bool
|
||||
}
|
||||
|
||||
func newMockArticleRepo() *mockArticleRepo {
|
||||
return &mockArticleRepo{
|
||||
articles: make(map[uint32]article.Article),
|
||||
images: make(map[uint32]*imageDomain.Image),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +94,9 @@ func (m *mockArticleRepo) UpdateBody(id uint32, body string) (article.Article, e
|
||||
if err := m.fail.trigger("UpdateBody"); err != nil {
|
||||
return article.Article{}, err
|
||||
}
|
||||
if err, ok := m.failUpdateBodyFor[id]; ok {
|
||||
return article.Article{}, err
|
||||
}
|
||||
a, ok := m.articles[id]
|
||||
if !ok {
|
||||
return article.Article{}, article.ErrArticleNotFound
|
||||
@@ -128,21 +130,18 @@ func (m *mockArticleRepo) Delete(id uint32) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockArticleRepo) AddImage(articleId uint32, imageId uint32) error {
|
||||
if err := m.fail.trigger("AddImage"); err != nil {
|
||||
return err
|
||||
func (m *mockArticleRepo) FindByBodyContaining(filename string) ([]article.Article, error) {
|
||||
if err := m.fail.trigger("FindByBodyContaining"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a, ok := m.articles[articleId]
|
||||
if !ok {
|
||||
return article.ErrArticleNotFound
|
||||
result := make([]article.Article, 0)
|
||||
for _, id := range m.sortedIds() {
|
||||
a := m.articles[id]
|
||||
if strings.Contains(a.Body, filename) {
|
||||
result = append(result, a)
|
||||
}
|
||||
}
|
||||
img, ok := m.images[imageId]
|
||||
if !ok {
|
||||
return imageDomain.ErrImageNotFound
|
||||
}
|
||||
a.Images = append(a.Images, img)
|
||||
m.articles[articleId] = a
|
||||
return nil
|
||||
return result, nil
|
||||
}
|
||||
|
||||
var _ article.Repository = &mockArticleRepo{}
|
||||
|
||||
@@ -29,7 +29,7 @@ func newArticleTitleRulesRouter(repo *mockArticleRepo, token *jwtauth.JWTAuth) *
|
||||
useCases.NewCreateArticleUseCase(repo),
|
||||
useCases.NewGetArticleUseCase(repo),
|
||||
useCases.NewListArticlesUseCase(repo),
|
||||
useCases.NewDeleteArticleUseCase(repo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(repo),
|
||||
useCases.NewUpdateArticleUseCase(repo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
@@ -3,7 +3,6 @@ package test
|
||||
import (
|
||||
"RenewCMS/api/handlers/article"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
@@ -24,7 +23,7 @@ func newArticlesListRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth)
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
@@ -43,16 +42,9 @@ func TestArticlesListHttp(t *testing.T) {
|
||||
validator.InitValidator()
|
||||
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||
|
||||
t.Run("GET /v1/article/ returns each article's images array populated", func(t *testing.T) {
|
||||
t.Run("GET /v1/article/ items carry no images field now that images belong to the library", func(t *testing.T) {
|
||||
repo := newMockArticleRepo()
|
||||
repo.articles[4] = domainArticle.Article{
|
||||
ID: 4,
|
||||
Title: "Winter checklist for timber windows",
|
||||
Images: []*domainImage.Image{
|
||||
{ID: 10, ArticleID: 4},
|
||||
{ID: 11, ArticleID: 4},
|
||||
},
|
||||
}
|
||||
repo.articles[4] = domainArticle.Article{ID: 4, Title: "Winter checklist for timber windows"}
|
||||
|
||||
router := newArticlesListRouter(repo, token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/", nil)
|
||||
@@ -64,29 +56,15 @@ func TestArticlesListHttp(t *testing.T) {
|
||||
t.Fatalf("expected status 200, got %d", rec.Code)
|
||||
}
|
||||
|
||||
var got []domainArticle.Article
|
||||
var got []map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
var found *domainArticle.Article
|
||||
for i := range got {
|
||||
if got[i].ID == 4 {
|
||||
found = &got[i]
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("expected 1 article, got %d", len(got))
|
||||
}
|
||||
if found == nil {
|
||||
t.Fatalf("expected article id 4 in response, got %v", got)
|
||||
}
|
||||
if len(found.Images) != 2 {
|
||||
t.Fatalf("expected 2 images, got %d", len(found.Images))
|
||||
}
|
||||
ids := map[uint32]bool{}
|
||||
for _, img := range found.Images {
|
||||
ids[img.ID] = true
|
||||
}
|
||||
if !ids[10] || !ids[11] {
|
||||
t.Errorf("expected images 10 and 11, got %v", found.Images)
|
||||
if _, present := got[0]["images"]; present {
|
||||
t.Errorf("expected no images field, got %v", got[0]["images"])
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api/handlers/article"
|
||||
"RenewCMS/api/middleware"
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
func seedArticleImages(imageRepo *mockImageRepo, ids ...uint32) []*domainImage.Image {
|
||||
images := make([]*domainImage.Image, len(ids))
|
||||
for i, id := range ids {
|
||||
imageRepo.images[id] = domainImage.Image{ID: id}
|
||||
seeded := imageRepo.images[id]
|
||||
images[i] = &seeded
|
||||
}
|
||||
return images
|
||||
}
|
||||
|
||||
func TestDeleteArticleUseCaseCascadesImageDeletion(t *testing.T) {
|
||||
t.Run("deletes every image before deleting the article, in Images slice order", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Images: seedArticleImages(imageRepo, 10, 11)}
|
||||
uc := useCases.NewDeleteArticleUseCase(articleRepo, imageRepo)
|
||||
|
||||
if err := uc.DeleteArticle(1); err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if got := imageRepo.deleteCalls; len(got) != 2 || got[0] != 10 || got[1] != 11 {
|
||||
t.Errorf("expected image Delete to be called with [10 11] in order, got %v", got)
|
||||
}
|
||||
if _, exists := articleRepo.articles[1]; exists {
|
||||
t.Errorf("expected article 1 to have been deleted")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stops at the first image Delete failure and leaves the article untouched", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
articleRepo.articles[3] = domainArticle.Article{ID: 3, Images: seedArticleImages(imageRepo, 20, 21)}
|
||||
imageRepo.failDeleteFor = map[uint32]error{20: errRepositoryFailure}
|
||||
uc := useCases.NewDeleteArticleUseCase(articleRepo, imageRepo)
|
||||
|
||||
err := uc.DeleteArticle(3)
|
||||
if !errors.Is(err, errRepositoryFailure) {
|
||||
t.Fatalf("expected errRepositoryFailure, got %v", err)
|
||||
}
|
||||
if got := imageRepo.deleteCalls; len(got) != 1 || got[0] != 20 {
|
||||
t.Errorf("expected image Delete to be called only once with 20, got %v", got)
|
||||
}
|
||||
if _, exists := articleRepo.articles[3]; !exists {
|
||||
t.Errorf("expected article 3 to still be present")
|
||||
}
|
||||
if _, exists := imageRepo.images[21]; !exists {
|
||||
t.Errorf("expected image 21 to still be present")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("propagates ErrArticleNotFound without touching the image repository", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
uc := useCases.NewDeleteArticleUseCase(articleRepo, imageRepo)
|
||||
|
||||
err := uc.DeleteArticle(9999)
|
||||
if !errors.Is(err, domainArticle.ErrArticleNotFound) {
|
||||
t.Fatalf("expected article.ErrArticleNotFound, got %v", err)
|
||||
}
|
||||
if len(imageRepo.deleteCalls) != 0 {
|
||||
t.Errorf("expected no call to the image repository's Delete method, got %v", imageRepo.deleteCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func newDeleteArticleCascadesImagesRouter(articleRepo *mockArticleRepo, imageRepo *mockImageRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||
userRepo := newVerifiedUserRepo()
|
||||
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
|
||||
|
||||
articleHandler := article.NewHandler(
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, imageRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
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.Delete("/{id}", articleHandler.DeleteArticle)
|
||||
})
|
||||
})
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func TestDeleteArticleCascadesImages(t *testing.T) {
|
||||
validator.InitValidator()
|
||||
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||
|
||||
t.Run("Deleting an article with images removes the article and every one of its images", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Images: seedArticleImages(imageRepo, 10, 11)}
|
||||
|
||||
router := newDeleteArticleCascadesImagesRouter(articleRepo, imageRepo, token)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/1", nil)
|
||||
setJwtCookie(t, req, token, 1)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected status 204, got %d", rec.Code)
|
||||
}
|
||||
if _, exists := articleRepo.articles[1]; exists {
|
||||
t.Errorf("expected article 1 to have been deleted")
|
||||
}
|
||||
if _, exists := imageRepo.images[10]; exists {
|
||||
t.Errorf("expected image 10 to have been deleted")
|
||||
}
|
||||
if _, exists := imageRepo.images[11]; exists {
|
||||
t.Errorf("expected image 11 to have been deleted")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Deleting an article with no images still succeeds", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
articleRepo.articles[2] = domainArticle.Article{ID: 2}
|
||||
|
||||
router := newDeleteArticleCascadesImagesRouter(articleRepo, imageRepo, token)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/2", nil)
|
||||
setJwtCookie(t, req, token, 1)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected status 204, got %d", rec.Code)
|
||||
}
|
||||
if _, exists := articleRepo.articles[2]; exists {
|
||||
t.Errorf("expected article 2 to have been deleted")
|
||||
}
|
||||
if len(imageRepo.deleteCalls) != 0 {
|
||||
t.Errorf("expected no call to the image repository's Delete method, got %v", imageRepo.deleteCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Deleting an unknown article still answers 404 and deletes no images", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
|
||||
router := newDeleteArticleCascadesImagesRouter(articleRepo, imageRepo, token)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/9999", nil)
|
||||
setJwtCookie(t, req, token, 1)
|
||||
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())
|
||||
}
|
||||
if len(imageRepo.deleteCalls) != 0 {
|
||||
t.Errorf("expected no call to the image repository's Delete method, got %v", imageRepo.deleteCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Deleting an article still requires authentication", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Images: seedArticleImages(imageRepo, 10)}
|
||||
|
||||
router := newDeleteArticleCascadesImagesRouter(articleRepo, imageRepo, token)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/1", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected status 401, got %d", rec.Code)
|
||||
}
|
||||
if _, exists := articleRepo.articles[1]; !exists {
|
||||
t.Errorf("expected article 1 to still be present")
|
||||
}
|
||||
if _, exists := imageRepo.images[10]; !exists {
|
||||
t.Errorf("expected image 10 to still be present")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failure deleting one of an article's images aborts the whole delete", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
articleRepo.articles[3] = domainArticle.Article{ID: 3, Images: seedArticleImages(imageRepo, 20, 21)}
|
||||
imageRepo.failDeleteFor = map[uint32]error{20: errRepositoryFailure}
|
||||
|
||||
router := newDeleteArticleCascadesImagesRouter(articleRepo, imageRepo, token)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/3", nil)
|
||||
setJwtCookie(t, req, token, 1)
|
||||
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 delete article\n" {
|
||||
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||
}
|
||||
if _, exists := articleRepo.articles[3]; !exists {
|
||||
t.Errorf("expected article 3 to still be present")
|
||||
}
|
||||
if _, exists := imageRepo.images[21]; !exists {
|
||||
t.Errorf("expected image 21 to still be present")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeleteArticleKeepsImages(t *testing.T) {
|
||||
newEnv := func(t *testing.T) *mediaEnv {
|
||||
env := newMediaEnv(t)
|
||||
env.seedImage(10, "ten.png", 1, "image/png", 1, 1, hashA, 1)
|
||||
env.seedImage(11, "eleven.png", 1, "image/png", 1, 1, hashB, 1)
|
||||
env.seedArticle(1, "Kitchen Renovation", true, env.urlOf(10)+" "+env.urlOf(11))
|
||||
return env
|
||||
}
|
||||
|
||||
t.Run("Deleting an article leaves every image it used", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
|
||||
rec := env.send(t, http.MethodDelete, "/v1/article/1", "", mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected status 204, got %d", rec.Code)
|
||||
}
|
||||
if _, ok := env.articles.articles[1]; ok {
|
||||
t.Errorf("expected article 1 to be gone")
|
||||
}
|
||||
expectIds(t, env.imageIds(), []uint32{10, 11})
|
||||
if len(env.images.deleteCalls) != 0 {
|
||||
t.Errorf("expected image Delete to never be called, got %v", env.images.deleteCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Deleting an unknown article is 404 and touches no image", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
|
||||
rec := env.send(t, http.MethodDelete, "/v1/article/9999", "", mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusNotFound || rec.Body.String() != apperr.ArticleNotFoundErrorMessage+"\n" {
|
||||
t.Errorf("expected 404 Article not found, got %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
expectIds(t, env.imageIds(), []uint32{10, 11})
|
||||
if len(env.images.deleteCalls) != 0 {
|
||||
t.Errorf("expected the image repository to be untouched")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Deleting still requires authentication", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
|
||||
rec := env.send(t, http.MethodDelete, "/v1/article/1", "", 0)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected status 401, got %d", rec.Code)
|
||||
}
|
||||
if _, ok := env.articles.articles[1]; !ok {
|
||||
t.Errorf("expected article 1 to still exist")
|
||||
}
|
||||
if _, ok := env.images.images[10]; !ok {
|
||||
t.Errorf("expected image 10 to still exist")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An article repository failure is 500 and everything stays", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
bodiesBefore := env.bodies()
|
||||
env.articles.fail.failNext("Delete")
|
||||
|
||||
rec := env.send(t, http.MethodDelete, "/v1/article/1", "", mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusInternalServerError || rec.Body.String() != "Failed to delete article\n" {
|
||||
t.Errorf("expected 500 Failed to delete article, got %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !reflect.DeepEqual(env.bodies(), bodiesBefore) {
|
||||
t.Errorf("expected the article to stay")
|
||||
}
|
||||
expectIds(t, env.imageIds(), []uint32{10, 11})
|
||||
if len(env.images.deleteCalls) != 0 {
|
||||
t.Errorf("expected the image repository to be untouched")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func newEditArticleBodyRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAu
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
+144
-8
@@ -3,36 +3,86 @@ package test
|
||||
import (
|
||||
imageDomain "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"errors"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var mockImageEpoch = time.Date(2026, time.June, 1, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
var mockImageExtensions = map[string]string{
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpeg",
|
||||
"image/webp": ".webp",
|
||||
"image/svg+xml": ".svg",
|
||||
}
|
||||
|
||||
type mockImageRepo struct {
|
||||
images map[uint32]imageDomain.Image
|
||||
nextID uint32
|
||||
fail failSwitch
|
||||
failDeleteFor map[uint32]error
|
||||
deleteCalls []uint32
|
||||
createCalls int
|
||||
lastContent []byte
|
||||
}
|
||||
|
||||
func newMockImageRepo() *mockImageRepo {
|
||||
return &mockImageRepo{images: make(map[uint32]imageDomain.Image)}
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) sortedImages() []imageDomain.Image {
|
||||
result := make([]imageDomain.Image, 0, len(m.images))
|
||||
for _, img := range m.images {
|
||||
result = append(result, img)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool { return result[i].ID < result[j].ID })
|
||||
return result
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) Create(input imageDomain.ImageInput) (imageDomain.Image, error) {
|
||||
m.createCalls++
|
||||
if err := m.fail.trigger("Create"); err != nil {
|
||||
return imageDomain.Image{}, err
|
||||
}
|
||||
if input.Content != nil {
|
||||
_, _ = io.ReadAll(input.Content)
|
||||
m.lastContent, _ = io.ReadAll(input.Content)
|
||||
}
|
||||
for m.images[m.nextID+1].ID != 0 {
|
||||
m.nextID++
|
||||
}
|
||||
m.nextID++
|
||||
img := imageDomain.Image{ID: m.nextID, Path: "/static/uploadedImages/" + input.Filename}
|
||||
img := imageDomain.Image{
|
||||
ID: m.nextID,
|
||||
Path: "/static/uploadedImages/" + strconv.Itoa(int(m.nextID)) + mockImageExtensions[input.ContentType],
|
||||
Filename: input.Filename,
|
||||
Size: input.Size,
|
||||
ContentType: input.ContentType,
|
||||
Width: input.Width,
|
||||
Height: input.Height,
|
||||
SHA256: input.SHA256,
|
||||
UploadedByID: input.UploadedByID,
|
||||
CreatedAt: mockImageEpoch.Add(time.Duration(m.nextID) * time.Minute),
|
||||
}
|
||||
m.images[img.ID] = img
|
||||
return img, nil
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) Get(id uint32) (imageDomain.Image, error) {
|
||||
if err := m.fail.trigger("Get"); err != nil {
|
||||
return imageDomain.Image{}, err
|
||||
}
|
||||
img, ok := m.images[id]
|
||||
if !ok {
|
||||
return imageDomain.Image{}, imageDomain.ErrImageNotFound
|
||||
}
|
||||
return img, nil
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) Delete(id uint32) error {
|
||||
m.deleteCalls = append(m.deleteCalls, id)
|
||||
if err := m.fail.trigger("Delete"); err != nil {
|
||||
@@ -48,16 +98,96 @@ func (m *mockImageRepo) Delete(id uint32) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) List(query imageDomain.SearchQuery) ([]imageDomain.Image, error) {
|
||||
if err := m.fail.trigger("List"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]imageDomain.Image, 0)
|
||||
for _, img := range m.sortedImages() {
|
||||
if query.Search != "" && !strings.Contains(strings.ToLower(img.Filename), strings.ToLower(query.Search)) {
|
||||
continue
|
||||
}
|
||||
if query.Hash != "" && img.SHA256 != query.Hash {
|
||||
continue
|
||||
}
|
||||
result = append(result, img)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) FindByHash(hash string) ([]imageDomain.Image, error) {
|
||||
if err := m.fail.trigger("FindByHash"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]imageDomain.Image, 0)
|
||||
for _, img := range m.sortedImages() {
|
||||
if hash != "" && img.SHA256 == hash {
|
||||
result = append(result, img)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) Rename(id uint32, filename string) (imageDomain.Image, error) {
|
||||
if err := m.fail.trigger("Rename"); err != nil {
|
||||
return imageDomain.Image{}, err
|
||||
}
|
||||
img, ok := m.images[id]
|
||||
if !ok {
|
||||
return imageDomain.Image{}, imageDomain.ErrImageNotFound
|
||||
}
|
||||
img.Filename = filename
|
||||
m.images[id] = img
|
||||
return img, nil
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) hashCounts() map[string]int {
|
||||
counts := map[string]int{}
|
||||
for _, img := range m.images {
|
||||
if img.SHA256 != "" {
|
||||
counts[img.SHA256]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) ListDuplicates() ([]imageDomain.Image, error) {
|
||||
if err := m.fail.trigger("ListDuplicates"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
counts := m.hashCounts()
|
||||
result := make([]imageDomain.Image, 0)
|
||||
for _, img := range m.sortedImages() {
|
||||
if img.SHA256 != "" && counts[img.SHA256] > 1 {
|
||||
result = append(result, img)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *mockImageRepo) Counts() (imageDomain.Counts, error) {
|
||||
if err := m.fail.trigger("Counts"); err != nil {
|
||||
return imageDomain.Counts{}, err
|
||||
}
|
||||
groups := 0
|
||||
for _, count := range m.hashCounts() {
|
||||
if count > 1 {
|
||||
groups++
|
||||
}
|
||||
}
|
||||
return imageDomain.Counts{All: len(m.images), DuplicateGroups: groups}, nil
|
||||
}
|
||||
|
||||
var _ imageDomain.Repository = &mockImageRepo{}
|
||||
|
||||
func TestImageUseCases(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
createUc := useCases.NewCreateImageUseCase(repo)
|
||||
deleteUc := useCases.NewDeleteImageUseCase(repo)
|
||||
deleteUc := useCases.NewDeleteMediaUseCase(repo)
|
||||
|
||||
t.Run("Create Image", func(t *testing.T) {
|
||||
input := imageDomain.ImageInput{
|
||||
Content: strings.NewReader("fake-image-data"),
|
||||
Content: strings.NewReader(string(pngBytes(t, 3, 2))),
|
||||
Filename: "test.png",
|
||||
ContentType: "image/png",
|
||||
}
|
||||
@@ -69,21 +199,27 @@ func TestImageUseCases(t *testing.T) {
|
||||
if res.ID == 0 {
|
||||
t.Errorf("Expected valid ID, got 0")
|
||||
}
|
||||
if !strings.Contains(res.Path, "test.png") {
|
||||
t.Errorf("Path mismatch: %s", res.Path)
|
||||
if res.Filename != "test.png" {
|
||||
t.Errorf("Filename mismatch: %s", res.Filename)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Delete Image", func(t *testing.T) {
|
||||
repo.images[99] = imageDomain.Image{ID: 99, Path: "/static/delete-me.png"}
|
||||
|
||||
err := deleteUc.DeleteImage(99)
|
||||
err := deleteUc.Delete(99)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteImage failed: %v", err)
|
||||
t.Fatalf("Delete failed: %v", err)
|
||||
}
|
||||
|
||||
if _, exists := repo.images[99]; exists {
|
||||
t.Errorf("Image 99 should have been deleted")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Delete unknown image", func(t *testing.T) {
|
||||
if err := deleteUc.Delete(12345); !errors.Is(err, imageDomain.ErrImageNotFound) {
|
||||
t.Errorf("expected ErrImageNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -3,10 +3,37 @@ package test
|
||||
import (
|
||||
imageDomain "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func validBytesFor(t *testing.T, contentType string) []byte {
|
||||
t.Helper()
|
||||
switch contentType {
|
||||
case "image/png":
|
||||
return pngBytes(t, 3, 2)
|
||||
case "image/jpeg":
|
||||
return jpegBytes(t, 3, 2)
|
||||
case "image/webp":
|
||||
return webpBytes(t)
|
||||
default:
|
||||
return []byte(svgFixture)
|
||||
}
|
||||
}
|
||||
|
||||
func paddedTo(data []byte, size int) []byte {
|
||||
padding := byte(0)
|
||||
if bytes.HasPrefix(data, []byte("<svg")) {
|
||||
padding = ' '
|
||||
}
|
||||
return append(append([]byte{}, data...), bytes.Repeat([]byte{padding}, size-len(data))...)
|
||||
}
|
||||
|
||||
func inputOf(content []byte, contentType string) imageDomain.ImageInput {
|
||||
return imageDomain.ImageInput{Content: bytes.NewReader(content), Filename: "upload", ContentType: contentType}
|
||||
}
|
||||
|
||||
func TestImageUploadRules(t *testing.T) {
|
||||
t.Run("CreateImage accepts every allowed content type within the size limit", func(t *testing.T) {
|
||||
for _, contentType := range []string{"image/png", "image/jpeg", "image/webp", "image/svg+xml"} {
|
||||
@@ -14,10 +41,7 @@ func TestImageUploadRules(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
createUc := useCases.NewCreateImageUseCase(repo)
|
||||
|
||||
result, err := createUc.CreateImage(imageDomain.ImageInput{
|
||||
ContentType: contentType,
|
||||
Size: imageDomain.MaxImageSize,
|
||||
})
|
||||
result, err := createUc.CreateImage(inputOf(paddedTo(validBytesFor(t, contentType), int(imageDomain.MaxImageSize)), contentType))
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
@@ -36,10 +60,7 @@ func TestImageUploadRules(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
createUc := useCases.NewCreateImageUseCase(repo)
|
||||
|
||||
_, err := createUc.CreateImage(imageDomain.ImageInput{
|
||||
ContentType: "application/pdf",
|
||||
Size: 1024,
|
||||
})
|
||||
_, err := createUc.CreateImage(inputOf([]byte("%PDF"), "application/pdf"))
|
||||
|
||||
if !errors.Is(err, imageDomain.ErrImageTypeNotAllowed) {
|
||||
t.Fatalf("expected ErrImageTypeNotAllowed, got %v", err)
|
||||
@@ -53,10 +74,7 @@ func TestImageUploadRules(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
createUc := useCases.NewCreateImageUseCase(repo)
|
||||
|
||||
_, err := createUc.CreateImage(imageDomain.ImageInput{
|
||||
ContentType: "image/png",
|
||||
Size: imageDomain.MaxImageSize + 1,
|
||||
})
|
||||
_, err := createUc.CreateImage(inputOf(paddedTo(pngBytes(t, 3, 2), int(imageDomain.MaxImageSize)+1), "image/png"))
|
||||
|
||||
if !errors.Is(err, imageDomain.ErrImageTooLarge) {
|
||||
t.Fatalf("expected ErrImageTooLarge, got %v", err)
|
||||
@@ -70,10 +88,7 @@ func TestImageUploadRules(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
createUc := useCases.NewCreateImageUseCase(repo)
|
||||
|
||||
_, err := createUc.CreateImage(imageDomain.ImageInput{
|
||||
ContentType: "image/png",
|
||||
Size: imageDomain.MaxImageSize,
|
||||
})
|
||||
_, err := createUc.CreateImage(inputOf(paddedTo(pngBytes(t, 3, 2), int(imageDomain.MaxImageSize)), "image/png"))
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error at the exact limit, got %v", err)
|
||||
}
|
||||
@@ -81,10 +96,7 @@ func TestImageUploadRules(t *testing.T) {
|
||||
t.Fatalf("expected Create to be called once, got %d calls", len(repo.images))
|
||||
}
|
||||
|
||||
_, err = createUc.CreateImage(imageDomain.ImageInput{
|
||||
ContentType: "image/png",
|
||||
Size: imageDomain.MaxImageSize + 1,
|
||||
})
|
||||
_, err = createUc.CreateImage(inputOf(paddedTo(pngBytes(t, 3, 2), int(imageDomain.MaxImageSize)+1), "image/png"))
|
||||
if !errors.Is(err, imageDomain.ErrImageTooLarge) {
|
||||
t.Fatalf("expected ErrImageTooLarge, got %v", err)
|
||||
}
|
||||
@@ -98,10 +110,7 @@ func TestImageUploadRules(t *testing.T) {
|
||||
repo.fail.failNextWith("Create", errRepositoryFailure)
|
||||
createUc := useCases.NewCreateImageUseCase(repo)
|
||||
|
||||
_, err := createUc.CreateImage(imageDomain.ImageInput{
|
||||
ContentType: "image/png",
|
||||
Size: 1024,
|
||||
})
|
||||
_, err := createUc.CreateImage(inputOf(pngBytes(t, 3, 2), "image/png"))
|
||||
|
||||
if !errors.Is(err, errRepositoryFailure) {
|
||||
t.Fatalf("expected the generic repository error, got %v", err)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type mediaOrderRecordingArticleRepo struct {
|
||||
*mockArticleRepo
|
||||
updated []uint32
|
||||
}
|
||||
|
||||
func (r *mediaOrderRecordingArticleRepo) UpdateBody(id uint32, body string) (domainArticle.Article, error) {
|
||||
r.updated = append(r.updated, id)
|
||||
return r.mockArticleRepo.UpdateBody(id, body)
|
||||
}
|
||||
|
||||
func TestMediaCursorBoundaries(t *testing.T) {
|
||||
seed := func(env *mediaEnv) {
|
||||
env.seedImage(1, "a.jpg", 10, "image/jpeg", 3, 2, hashA, 1)
|
||||
env.seedImage(2, "b.jpg", 20, "image/jpeg", 3, 2, hashB, 1)
|
||||
}
|
||||
encode := func(raw string) string {
|
||||
return url.QueryEscape(base64.RawURLEncoding.EncodeToString([]byte(raw)))
|
||||
}
|
||||
|
||||
t.Run("A cursor at offset zero is accepted and starts from the first item", func(t *testing.T) {
|
||||
env := newMediaEnv(t)
|
||||
seed(env)
|
||||
|
||||
rec := env.send(t, http.MethodGet, "/v1/media/?cursor="+encode("offset:0"), "", mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A negative cursor offset is refused", func(t *testing.T) {
|
||||
env := newMediaEnv(t)
|
||||
seed(env)
|
||||
|
||||
rec := env.send(t, http.MethodGet, "/v1/media/?cursor="+encode("offset:-1"), "", mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status 400, got %d", rec.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMediaMergeRewritesArticlesInIdOrder(t *testing.T) {
|
||||
env := newMediaEnv(t)
|
||||
env.seedImage(2, "floorboards.jpg", 20, "image/jpeg", 3, 2, hashB, 1)
|
||||
env.seedImage(3, "floorboards-copy.jpg", 20, "image/jpeg", 3, 2, hashB, 2)
|
||||
for id := uint32(1); id <= 8; id++ {
|
||||
env.seedArticle(id, "Article", true, env.urlOf(3))
|
||||
}
|
||||
recorder := &mediaOrderRecordingArticleRepo{mockArticleRepo: env.articles}
|
||||
uc := useCases.NewMergeMediaUseCase(env.images, recorder)
|
||||
|
||||
if _, err := uc.Merge(2, []uint32{3}); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if want := []uint32{1, 2, 3, 4, 5, 6, 7, 8}; !reflect.DeepEqual(recorder.updated, want) {
|
||||
t.Errorf("expected updates in id order %v, got %v", want, recorder.updated)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/config"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
mediaVerifiedUserId uint32 = 1
|
||||
mediaSecondUserId uint32 = 2
|
||||
mediaUnverifiedUserId uint32 = 3
|
||||
mediaStaleUserId uint32 = 4
|
||||
)
|
||||
|
||||
type mediaEnv struct {
|
||||
articles *mockArticleRepo
|
||||
images *mockImageRepo
|
||||
users *mockUserRepo
|
||||
token *jwtauth.JWTAuth
|
||||
router http.Handler
|
||||
}
|
||||
|
||||
func newMediaEnv(t *testing.T) *mediaEnv {
|
||||
t.Helper()
|
||||
validator.InitValidator()
|
||||
|
||||
env := &mediaEnv{
|
||||
articles: newMockArticleRepo(),
|
||||
images: newMockImageRepo(),
|
||||
users: newMockUserRepo(),
|
||||
token: jwtauth.New("HS256", []byte("test-secret"), nil),
|
||||
}
|
||||
env.users.users[mediaVerifiedUserId] = user.User{ID: 1, Username: "ines", DisplayName: "Inès Duarte", IsVerified: true}
|
||||
env.users.users[mediaSecondUserId] = user.User{ID: 2, Username: "marta", IsVerified: true}
|
||||
env.users.users[mediaUnverifiedUserId] = user.User{ID: 3, Username: "pending", IsVerified: false}
|
||||
env.users.users[mediaStaleUserId] = user.User{ID: 4, Username: "stale", IsVerified: true, TokenVersion: 1}
|
||||
|
||||
container := &api.UseCases{
|
||||
Token: env.token,
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(env.articles),
|
||||
GetArticleUseCase: useCases.NewGetArticleUseCase(env.articles),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(env.articles),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(env.articles),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(env.articles),
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(env.users),
|
||||
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images),
|
||||
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users),
|
||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images),
|
||||
MergeMediaUseCase: useCases.NewMergeMediaUseCase(env.images, env.articles),
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles),
|
||||
}
|
||||
router := chi.NewRouter()
|
||||
router.Mount("/v1", api.InitBackendRoutes(container, config.Settings{}))
|
||||
env.router = router
|
||||
return env
|
||||
}
|
||||
|
||||
func (e *mediaEnv) cookie(t *testing.T, userId uint32, tokenVersion uint32) *http.Cookie {
|
||||
t.Helper()
|
||||
_, tokenString, err := e.token.Encode(map[string]any{"user_id": userId, "token_version": tokenVersion})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encode jwt: %v", err)
|
||||
}
|
||||
return &http.Cookie{Name: "jwt", Value: tokenString}
|
||||
}
|
||||
|
||||
func (e *mediaEnv) serve(t *testing.T, req *http.Request, userId uint32) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
if userId != 0 {
|
||||
req.AddCookie(e.cookie(t, userId, 0))
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
e.router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func (e *mediaEnv) send(t *testing.T, method string, path string, body string, userId uint32) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
return e.serve(t, req, userId)
|
||||
}
|
||||
|
||||
func (e *mediaEnv) seedImage(id uint32, filename string, size int64, contentType string, width int, height int, hash string, uploadedBy uint32) {
|
||||
extension := map[string]string{"image/jpeg": ".jpeg", "image/svg+xml": ".svg", "image/png": ".png"}[contentType]
|
||||
e.images.images[id] = domainImage.Image{
|
||||
ID: id,
|
||||
Path: "/static/uploadedImages/img-" + strconv.Itoa(int(id)) + "-" + extension,
|
||||
Filename: filename,
|
||||
Size: size,
|
||||
ContentType: contentType,
|
||||
Width: width,
|
||||
Height: height,
|
||||
SHA256: hash,
|
||||
UploadedByID: uploadedBy,
|
||||
CreatedAt: mockImageEpoch.Add(time.Duration(id) * time.Minute),
|
||||
}
|
||||
if id > e.images.nextID {
|
||||
e.images.nextID = id
|
||||
}
|
||||
}
|
||||
|
||||
func (e *mediaEnv) urlOf(id uint32) string {
|
||||
return e.images.images[id].Path
|
||||
}
|
||||
|
||||
func (e *mediaEnv) seedArticle(id uint32, title string, online bool, body string) {
|
||||
e.articles.articles[id] = domainArticle.Article{ID: id, Title: title, IsOnline: online, Body: body}
|
||||
if id > e.articles.nextID {
|
||||
e.articles.nextID = id
|
||||
}
|
||||
}
|
||||
|
||||
func (e *mediaEnv) bodies() map[uint32]string {
|
||||
result := map[uint32]string{}
|
||||
for id, a := range e.articles.articles {
|
||||
result[id] = a.Body
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (e *mediaEnv) imageIds() []uint32 {
|
||||
ids := make([]uint32, 0)
|
||||
for _, img := range e.images.sortedImages() {
|
||||
ids = append(ids, img.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func decodeObject(t *testing.T, body string) map[string]any {
|
||||
t.Helper()
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &decoded); err != nil {
|
||||
t.Fatalf("failed to decode %q: %v", body, err)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
func numberOf(value any) uint32 {
|
||||
number, _ := value.(float64)
|
||||
return uint32(number)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const webpFixtureBase64 = "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA=="
|
||||
|
||||
const svgFixture = `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>`
|
||||
|
||||
func solidImage(width int, height int) image.Image {
|
||||
canvas := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
for x := 0; x < width; x++ {
|
||||
for y := 0; y < height; y++ {
|
||||
canvas.Set(x, y, color.RGBA{R: uint8(x * 40), G: uint8(y * 40), B: 200, A: 255})
|
||||
}
|
||||
}
|
||||
return canvas
|
||||
}
|
||||
|
||||
func pngBytes(t *testing.T, width int, height int) []byte {
|
||||
t.Helper()
|
||||
buffer := &bytes.Buffer{}
|
||||
if err := png.Encode(buffer, solidImage(width, height)); err != nil {
|
||||
t.Fatalf("failed to encode png: %v", err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func jpegBytes(t *testing.T, width int, height int) []byte {
|
||||
t.Helper()
|
||||
buffer := &bytes.Buffer{}
|
||||
if err := jpeg.Encode(buffer, solidImage(width, height), nil); err != nil {
|
||||
t.Fatalf("failed to encode jpeg: %v", err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func webpBytes(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
data, err := base64.StdEncoding.DecodeString(webpFixtureBase64)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to decode webp fixture: %v", err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func paddedPngBytes(t *testing.T, size int) []byte {
|
||||
t.Helper()
|
||||
data := pngBytes(t, 3, 2)
|
||||
return append(data, bytes.Repeat([]byte{0}, size-len(data))...)
|
||||
}
|
||||
|
||||
func sha256Hex(data []byte) string {
|
||||
sum := sha256.Sum256(data)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func newMultipartFileRequest(t *testing.T, method string, url string, filename string, contentType string, content []byte) *http.Request {
|
||||
t.Helper()
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
part, err := writer.CreatePart(map[string][]string{
|
||||
"Content-Disposition": {`form-data; name="file"; filename="` + filename + `"`},
|
||||
"Content-Type": {contentType},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create multipart part: %v", err)
|
||||
}
|
||||
if _, err := io.Copy(part, bytes.NewReader(content)); err != nil {
|
||||
t.Fatalf("failed to write file content: %v", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(method, url, body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
return req
|
||||
}
|
||||
|
||||
func newMultipartWithoutFileRequest(t *testing.T, url string) *http.Request {
|
||||
t.Helper()
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, url, body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
return req
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,253 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newMediaPersistence(t *testing.T) (*gorm.DB, *persistence.ImageRepository, string) {
|
||||
t.Helper()
|
||||
db := openInMemoryDb(t)
|
||||
if err := db.AutoMigrate(&models.Article{}, &models.Image{}); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
uploadDir := t.TempDir()
|
||||
return db, persistence.NewImageRepository(db, uploadDir), uploadDir
|
||||
}
|
||||
|
||||
func createStoredImage(t *testing.T, repo *persistence.ImageRepository, filename string, content []byte, contentType string) domainImage.Image {
|
||||
t.Helper()
|
||||
created, err := repo.Create(domainImage.ImageInput{
|
||||
Content: bytes.NewReader(content),
|
||||
Filename: filename,
|
||||
Size: int64(len(content)),
|
||||
ContentType: contentType,
|
||||
Width: 3,
|
||||
Height: 2,
|
||||
SHA256: sha256Hex(content),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create failed: %v", err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
func TestMediaImageRepository(t *testing.T) {
|
||||
t.Run("Create stores the file and the metadata and returns the assigned id", func(t *testing.T) {
|
||||
_, repo, uploadDir := newMediaPersistence(t)
|
||||
content := pngBytes(t, 3, 2)
|
||||
|
||||
created := createStoredImage(t, repo, "a.png", content, "image/png")
|
||||
|
||||
if created.ID == 0 || created.Filename != "a.png" || created.SHA256 != sha256Hex(content) || created.Width != 3 || created.Size != int64(len(content)) {
|
||||
t.Errorf("unexpected image %+v", created)
|
||||
}
|
||||
onDisk, err := os.ReadFile(filepath.Join(uploadDir, filepath.Base(created.Path)))
|
||||
if err != nil || !bytes.Equal(onDisk, content) {
|
||||
t.Errorf("expected the file on disk, got %v", err)
|
||||
}
|
||||
got, err := repo.Get(created.ID)
|
||||
if err != nil || got.SHA256 != created.SHA256 {
|
||||
t.Errorf("Get returned %+v, %v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Get reports a missing image as ErrImageNotFound", func(t *testing.T) {
|
||||
_, repo, _ := newMediaPersistence(t)
|
||||
|
||||
if _, err := repo.Get(9); !errors.Is(err, domainImage.ErrImageNotFound) {
|
||||
t.Errorf("expected ErrImageNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Delete removes the file and the row", func(t *testing.T) {
|
||||
_, repo, uploadDir := newMediaPersistence(t)
|
||||
created := createStoredImage(t, repo, "a.png", pngBytes(t, 3, 2), "image/png")
|
||||
|
||||
if err := repo.Delete(created.ID); err != nil {
|
||||
t.Fatalf("Delete failed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(uploadDir, filepath.Base(created.Path))); !os.IsNotExist(err) {
|
||||
t.Errorf("expected the file to be gone")
|
||||
}
|
||||
if _, err := repo.Get(created.ID); !errors.Is(err, domainImage.ErrImageNotFound) {
|
||||
t.Errorf("expected the row to be gone, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A file already missing from disk still deletes the row", func(t *testing.T) {
|
||||
_, repo, uploadDir := newMediaPersistence(t)
|
||||
created := createStoredImage(t, repo, "a.png", pngBytes(t, 3, 2), "image/png")
|
||||
if err := os.Remove(filepath.Join(uploadDir, filepath.Base(created.Path))); err != nil {
|
||||
t.Fatalf("failed to remove the file: %v", err)
|
||||
}
|
||||
|
||||
if err := repo.Delete(created.ID); err != nil {
|
||||
t.Fatalf("Delete failed: %v", err)
|
||||
}
|
||||
if _, err := repo.Get(created.ID); !errors.Is(err, domainImage.ErrImageNotFound) {
|
||||
t.Errorf("expected the row to be gone, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("List, FindByHash, Rename, ListDuplicates and Counts", func(t *testing.T) {
|
||||
_, repo, _ := newMediaPersistence(t)
|
||||
same := pngBytes(t, 3, 2)
|
||||
first := createStoredImage(t, repo, "North-Wall.png", same, "image/png")
|
||||
second := createStoredImage(t, repo, "copy.png", same, "image/png")
|
||||
createStoredImage(t, repo, "other.png", pngBytes(t, 4, 4), "image/png")
|
||||
|
||||
found, err := repo.List(domainImage.SearchQuery{Search: "NORTH"})
|
||||
if err != nil || len(found) != 1 || found[0].ID != first.ID {
|
||||
t.Errorf("unexpected search result %+v, %v", found, err)
|
||||
}
|
||||
byHash, err := repo.List(domainImage.SearchQuery{Hash: sha256Hex(same)})
|
||||
if err != nil || len(byHash) != 2 {
|
||||
t.Errorf("unexpected hash result %+v, %v", byHash, err)
|
||||
}
|
||||
sameContent, err := repo.FindByHash(sha256Hex(same))
|
||||
if err != nil || len(sameContent) != 2 || sameContent[1].ID != second.ID {
|
||||
t.Errorf("unexpected FindByHash result %+v, %v", sameContent, err)
|
||||
}
|
||||
if none, err := repo.FindByHash(""); err != nil || len(none) != 0 {
|
||||
t.Errorf("expected no result for an empty hash, got %+v, %v", none, err)
|
||||
}
|
||||
duplicates, err := repo.ListDuplicates()
|
||||
if err != nil || len(duplicates) != 2 {
|
||||
t.Errorf("unexpected duplicates %+v, %v", duplicates, err)
|
||||
}
|
||||
counts, err := repo.Counts()
|
||||
if err != nil || counts.All != 3 || counts.DuplicateGroups != 1 {
|
||||
t.Errorf("unexpected counts %+v, %v", counts, err)
|
||||
}
|
||||
|
||||
renamed, err := repo.Rename(first.ID, "renamed.png")
|
||||
if err != nil || renamed.Filename != "renamed.png" || renamed.Path != first.Path {
|
||||
t.Errorf("unexpected rename result %+v, %v", renamed, err)
|
||||
}
|
||||
if _, err := repo.Rename(9999, "x.png"); !errors.Is(err, domainImage.ErrImageNotFound) {
|
||||
t.Errorf("expected ErrImageNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMediaArticleRepositoryFindsBodiesContainingAFilename(t *testing.T) {
|
||||
db, _, _ := newMediaPersistence(t)
|
||||
repo := persistence.NewArticleRepository(db)
|
||||
if _, err := repo.Create(domainArticle.Article{Title: "Kitchen Renovation", Body: "see /static/uploadedImages/aaa.png"}); err != nil {
|
||||
t.Fatalf("failed to seed article: %v", err)
|
||||
}
|
||||
if _, err := repo.Create(domainArticle.Article{Title: "Backyard Notes", Body: "nothing"}); err != nil {
|
||||
t.Fatalf("failed to seed article: %v", err)
|
||||
}
|
||||
|
||||
found, err := repo.FindByBodyContaining("aaa.png")
|
||||
|
||||
if err != nil || len(found) != 1 || found[0].Title != "Kitchen Renovation" {
|
||||
t.Errorf("unexpected result %+v, %v", found, err)
|
||||
}
|
||||
if none, err := repo.FindByBodyContaining("zzz.png"); err != nil || none == nil || len(none) != 0 {
|
||||
t.Errorf("expected an empty non-nil slice, got %+v, %v", none, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaImageBackfill(t *testing.T) {
|
||||
seedLegacyRow := func(t *testing.T, db *gorm.DB, name string) models.Image {
|
||||
t.Helper()
|
||||
row := models.Image{Path: "/static/uploadedImages/" + name}
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatalf("failed to seed a legacy row: %v", err)
|
||||
}
|
||||
return row
|
||||
}
|
||||
writeFile := func(t *testing.T, dir string, name string, content []byte) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, name), content, 0666); err != nil {
|
||||
t.Fatalf("failed to write %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("Existing rows get metadata and hash from the files on disk", func(t *testing.T) {
|
||||
db, repo, uploadDir := newMediaPersistence(t)
|
||||
png, svg := pngBytes(t, 3, 2), []byte(svgFixture)
|
||||
writeFile(t, uploadDir, "one.png", png)
|
||||
writeFile(t, uploadDir, "two.svg", svg)
|
||||
pngRow, svgRow := seedLegacyRow(t, db, "one.png"), seedLegacyRow(t, db, "two.svg")
|
||||
|
||||
if err := persistence.BackfillImageMetadata(db, uploadDir); err != nil {
|
||||
t.Fatalf("backfill failed: %v", err)
|
||||
}
|
||||
|
||||
gotPng, _ := repo.Get(pngRow.ID)
|
||||
if gotPng.Filename != "one.png" || gotPng.Size != int64(len(png)) || gotPng.ContentType != "image/png" || gotPng.Width != 3 || gotPng.Height != 2 || gotPng.SHA256 != sha256Hex(png) || gotPng.UploadedByID != 0 {
|
||||
t.Errorf("unexpected png row %+v", gotPng)
|
||||
}
|
||||
gotSvg, _ := repo.Get(svgRow.ID)
|
||||
if gotSvg.ContentType != "image/svg+xml" || gotSvg.Width != 0 || gotSvg.Height != 0 || gotSvg.SHA256 != sha256Hex(svg) {
|
||||
t.Errorf("unexpected svg row %+v", gotSvg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A row whose file is missing does not stop the boot", func(t *testing.T) {
|
||||
db, repo, uploadDir := newMediaPersistence(t)
|
||||
row := seedLegacyRow(t, db, "gone.png")
|
||||
|
||||
if err := persistence.BackfillImageMetadata(db, uploadDir); err != nil {
|
||||
t.Fatalf("backfill failed: %v", err)
|
||||
}
|
||||
|
||||
got, _ := repo.Get(row.ID)
|
||||
if got.Filename != "" || got.SHA256 != "" {
|
||||
t.Errorf("expected the row to be left as is, got %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An unreadable file leaves its row as is and the others are still filled", func(t *testing.T) {
|
||||
db, repo, uploadDir := newMediaPersistence(t)
|
||||
writeFile(t, uploadDir, "broken.png", []byte("not an image"))
|
||||
writeFile(t, uploadDir, "fine.png", pngBytes(t, 3, 2))
|
||||
broken, fine := seedLegacyRow(t, db, "broken.png"), seedLegacyRow(t, db, "fine.png")
|
||||
|
||||
if err := persistence.BackfillImageMetadata(db, uploadDir); err != nil {
|
||||
t.Fatalf("backfill failed: %v", err)
|
||||
}
|
||||
|
||||
if got, _ := repo.Get(broken.ID); got.Filename != "" {
|
||||
t.Errorf("expected the broken row to be left as is, got %+v", got)
|
||||
}
|
||||
if got, _ := repo.Get(fine.ID); got.Filename != "fine.png" {
|
||||
t.Errorf("expected the fine row to be filled, got %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The backfill is idempotent", func(t *testing.T) {
|
||||
db, repo, uploadDir := newMediaPersistence(t)
|
||||
writeFile(t, uploadDir, "one.png", pngBytes(t, 3, 2))
|
||||
row := seedLegacyRow(t, db, "one.png")
|
||||
if err := persistence.BackfillImageMetadata(db, uploadDir); err != nil {
|
||||
t.Fatalf("backfill failed: %v", err)
|
||||
}
|
||||
afterFirst, _ := repo.Get(row.ID)
|
||||
if _, err := repo.Rename(row.ID, "renamed.png"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := persistence.BackfillImageMetadata(db, uploadDir); err != nil {
|
||||
t.Fatalf("second backfill failed: %v", err)
|
||||
}
|
||||
|
||||
afterSecond, _ := repo.Get(row.ID)
|
||||
if afterSecond.Filename != "renamed.png" || afterSecond.SHA256 != afterFirst.SHA256 {
|
||||
t.Errorf("expected the second run to change nothing, got %+v", afterSecond)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -129,7 +129,7 @@ func newNotFoundErrorsRouter(articleRepo *mockArticleRepo, userRepo *mockUserRep
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
@@ -45,7 +45,7 @@ func newPublicArticleListingRouter(articleRepo *mockArticleRepo, token *jwtauth.
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
@@ -27,7 +27,7 @@ func newPublicArticleReadRouter(articleRepo *mockArticleRepo, userRepo *mockUser
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api/handlers/image"
|
||||
"RenewCMS/api/middleware"
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
func newRemoveArticleImageRouter(articleRepo *mockArticleRepo, imageRepo *mockImageRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||
userRepo := newVerifiedUserRepo()
|
||||
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
|
||||
|
||||
imageHandler := image.NewHandler(
|
||||
useCases.NewCreateImageUseCase(imageRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
useCases.NewDeleteImageUseCase(imageRepo),
|
||||
)
|
||||
|
||||
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.Delete("/{id}/image/{imageId}", imageHandler.DeleteImage)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func setRemoveImageJwtCookie(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 TestRemoveArticleImageHttp(t *testing.T) {
|
||||
validator.InitValidator()
|
||||
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||
|
||||
t.Run("Removing an image from an article it belongs to succeeds", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update", Images: []*domainImage.Image{{ID: 10}}}
|
||||
imageRepo := newMockImageRepo()
|
||||
imageRepo.images[10] = domainImage.Image{ID: 10, Path: "/static/uploadedImages/before.png"}
|
||||
router := newRemoveArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/1/image/10", nil)
|
||||
setRemoveImageJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected status 204, got %d, body %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Errorf("expected empty body, got %q", rec.Body.String())
|
||||
}
|
||||
if _, ok := imageRepo.images[10]; ok {
|
||||
t.Errorf("expected image 10 to have been removed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Removing an image from an unknown article answers 404 and never touches the image repository", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
imageRepo.images[10] = domainImage.Image{ID: 10, Path: "/static/uploadedImages/before.png"}
|
||||
router := newRemoveArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/9999/image/10", nil)
|
||||
setRemoveImageJwtCookie(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())
|
||||
}
|
||||
if len(imageRepo.deleteCalls) != 0 {
|
||||
t.Errorf("expected Delete to never be called, got %d calls", len(imageRepo.deleteCalls))
|
||||
}
|
||||
if _, ok := imageRepo.images[10]; !ok {
|
||||
t.Errorf("expected image 10 to still exist")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Removing an unknown image from an existing article answers 404", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newRemoveArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/1/image/9999", nil)
|
||||
setRemoveImageJwtCookie(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.ImageNotFoundErrorMessage+"\n" {
|
||||
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Removing an image id that belongs to a different article still succeeds, because the check is shallow", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
articleRepo.articles[2] = domainArticle.Article{ID: 2, Images: []*domainImage.Image{{ID: 10}}}
|
||||
imageRepo := newMockImageRepo()
|
||||
imageRepo.images[10] = domainImage.Image{ID: 10, Path: "/static/uploadedImages/before.png"}
|
||||
router := newRemoveArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/1/image/10", nil)
|
||||
setRemoveImageJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected status 204, got %d, body %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, ok := imageRepo.images[10]; ok {
|
||||
t.Errorf("expected image 10 to have been removed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Removing an image still requires authentication", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update", Images: []*domainImage.Image{{ID: 10}}}
|
||||
imageRepo := newMockImageRepo()
|
||||
imageRepo.images[10] = domainImage.Image{ID: 10, Path: "/static/uploadedImages/before.png"}
|
||||
router := newRemoveArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/1/image/10", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected status 401, got %d", rec.Code)
|
||||
}
|
||||
if _, ok := imageRepo.images[10]; !ok {
|
||||
t.Errorf("expected image 10 to still exist")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A malformed id in the URL answers 400 before either repository is touched", func(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
articleId string
|
||||
imageId string
|
||||
}{
|
||||
{"malformed article id", "abc", "10"},
|
||||
{"malformed image id", "1", "abc"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newRemoveArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/v1/article/"+tc.articleId+"/image/"+tc.imageId, nil)
|
||||
setRemoveImageJwtCookie(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())
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -136,7 +136,7 @@ func newRuntimeSettingsContainer(t *testing.T) *api.UseCases {
|
||||
GetArticleUseCase: useCases.NewGetArticleUseCase(articleRepo),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(articleRepo),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(articleRepo, imageRepo),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(userRepo),
|
||||
CreateUserUseCase: useCases.NewCreateUserUseCase(userRepo, hasher, mailRepo, "https://cms.example.com"),
|
||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(userRepo, hasher),
|
||||
@@ -144,7 +144,11 @@ func newRuntimeSettingsContainer(t *testing.T) *api.UseCases {
|
||||
ListUsersUseCase: useCases.NewListUsersUseCase(userRepo),
|
||||
SendMailUseCase: useCases.NewSendMailUseCase(mailRepo),
|
||||
CreateImageUseCase: useCases.NewCreateImageUseCase(imageRepo),
|
||||
DeleteImageUseCase: useCases.NewDeleteImageUseCase(imageRepo),
|
||||
ListMediaUseCase: useCases.NewListMediaUseCase(imageRepo, articleRepo, userRepo),
|
||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(imageRepo),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(imageRepo),
|
||||
MergeMediaUseCase: useCases.NewMergeMediaUseCase(imageRepo, articleRepo),
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(imageRepo, articleRepo),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ func newStaleTokenInvalidationRouter(userRepo *mockUserRepo, articleRepo *mockAr
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, imageRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
@@ -1,152 +1,59 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api/handlers/image"
|
||||
"RenewCMS/api/middleware"
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
)
|
||||
|
||||
func newUploadArticleImageRouter(articleRepo *mockArticleRepo, imageRepo *mockImageRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||
userRepo := newVerifiedUserRepo()
|
||||
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
|
||||
|
||||
imageHandler := image.NewHandler(
|
||||
useCases.NewCreateImageUseCase(imageRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
useCases.NewDeleteImageUseCase(imageRepo),
|
||||
)
|
||||
|
||||
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.Post("/{id}/image", imageHandler.PostImage)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func setUploadJwtCookie(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 newMultipartImageUploadRequest(t *testing.T, url string, filename string, contentType string) *http.Request {
|
||||
t.Helper()
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
part, err := writer.CreatePart(map[string][]string{
|
||||
"Content-Disposition": {`form-data; name="file"; filename="` + filename + `"`},
|
||||
"Content-Type": {contentType},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create multipart part: %v", err)
|
||||
}
|
||||
if _, err := io.WriteString(part, "fake-image-data"); err != nil {
|
||||
t.Fatalf("failed to write file content: %v", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, url, body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
return req
|
||||
}
|
||||
|
||||
func TestUploadArticleImageHttp(t *testing.T) {
|
||||
validator.InitValidator()
|
||||
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||
newEnv := func(t *testing.T) *mediaEnv {
|
||||
env := newMediaEnv(t)
|
||||
env.seedArticle(1, "Backyard Renovation Update", true, "unchanged body")
|
||||
return env
|
||||
}
|
||||
|
||||
t.Run("Uploading an allowed image type to an existing article succeeds", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
articleRepo.images[1] = &domainImage.Image{ID: 1, Path: "/static/uploadedImages/before.png"}
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
t.Run("Uploading through the alias creates a library image", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/1/image", "before.png", "image/png")
|
||||
setUploadJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/article/1/image", "before.png", "image/png", pngBytes(t, 3, 2))
|
||||
rec := env.serve(t, req, mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("expected status 201, got %d, body %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
got := decodeObject(t, rec.Body.String())
|
||||
if len(env.images.images) != 1 {
|
||||
t.Fatalf("expected exactly one library image, got %d", len(env.images.images))
|
||||
}
|
||||
if got["location"] != "/static/uploadedImages/before.png" {
|
||||
t.Errorf("expected location %q, got %q", "/static/uploadedImages/before.png", got["location"])
|
||||
created := env.images.images[1]
|
||||
if numberOf(got["id"]) != created.ID {
|
||||
t.Errorf("expected id %d, got %v", created.ID, got["id"])
|
||||
}
|
||||
if got["location"] != created.Path {
|
||||
t.Errorf("expected location %q, got %v", created.Path, got["location"])
|
||||
}
|
||||
if created.UploadedByID != mediaVerifiedUserId {
|
||||
t.Errorf("expected UploadedByID 1, got %d", created.UploadedByID)
|
||||
}
|
||||
|
||||
if len(imageRepo.images) != 1 {
|
||||
t.Fatalf("expected the image repository to gain exactly one entry, got %d", len(imageRepo.images))
|
||||
listing := env.send(t, http.MethodGet, "/v1/media/", "", mediaVerifiedUserId)
|
||||
items := decodeObject(t, listing.Body.String())["items"].([]any)
|
||||
if len(items) != 1 || items[0].(map[string]any)["uploaded_by"] != "Inès Duarte" {
|
||||
t.Errorf("expected the media list to hold the image uploaded by user 1, got %v", items)
|
||||
}
|
||||
var storedImageID uint32
|
||||
found := false
|
||||
for id, img := range imageRepo.images {
|
||||
if img.Path == "/static/uploadedImages/before.png" {
|
||||
storedImageID = id
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("expected the image repository to contain the new image")
|
||||
}
|
||||
gotId, ok := got["id"].(float64)
|
||||
if !ok || uint32(gotId) != storedImageID {
|
||||
t.Errorf("expected id %v, got %v", storedImageID, got["id"])
|
||||
}
|
||||
|
||||
updatedArticle := articleRepo.articles[1]
|
||||
imageAttached := false
|
||||
for _, img := range updatedArticle.Images {
|
||||
if img.ID == storedImageID {
|
||||
imageAttached = true
|
||||
}
|
||||
}
|
||||
if !imageAttached {
|
||||
t.Errorf("expected article 1 to reference the new image's id, got %+v", updatedArticle.Images)
|
||||
if env.articles.articles[1].Body != "unchanged body" {
|
||||
t.Errorf("expected article 1 to be unchanged, got %+v", env.articles.articles[1])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Uploading to an unknown article answers 404 and creates no image", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
t.Run("An unknown article is 404 and creates no image", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/9999/image", "before.png", "image/png")
|
||||
setUploadJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/article/9999/image", "before.png", "image/png", pngBytes(t, 3, 2))
|
||||
rec := env.serve(t, req, mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected status 404, got %d", rec.Code)
|
||||
@@ -154,111 +61,101 @@ func TestUploadArticleImageHttp(t *testing.T) {
|
||||
if rec.Body.String() != apperr.ArticleNotFoundErrorMessage+"\n" {
|
||||
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||
}
|
||||
if len(imageRepo.images) != 0 {
|
||||
t.Errorf("expected no image to be created, got %d", len(imageRepo.images))
|
||||
if env.images.createCalls != 0 {
|
||||
t.Errorf("expected Create to never be called, got %d calls", env.images.createCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Uploading a disallowed content type answers 400 before the article is touched", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
t.Run("Rejected files use the media status codes", func(t *testing.T) {
|
||||
examples := []struct {
|
||||
name string
|
||||
filename string
|
||||
contentType string
|
||||
content []byte
|
||||
status int
|
||||
}{
|
||||
{"notes.pdf as application/pdf", "notes.pdf", "application/pdf", []byte("%PDF"), http.StatusUnsupportedMediaType},
|
||||
{"a valid PNG padded to 10485761 bytes", "huge.png", "image/png", paddedPngBytes(t, int(domainImage.MaxImageSize)+1), http.StatusRequestEntityTooLarge},
|
||||
{"broken.png as image/png with text bytes", "broken.png", "image/png", []byte("not an image"), http.StatusBadRequest},
|
||||
}
|
||||
for _, example := range examples {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/1/image", "notes.pdf", "application/pdf")
|
||||
setUploadJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/article/1/image", example.filename, example.contentType, example.content)
|
||||
rec := env.serve(t, req, mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status 400, got %d", rec.Code)
|
||||
}
|
||||
if rec.Body.String() != "the file must be a PNG, JPEG, WEBP, or SVG image\n" {
|
||||
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||
}
|
||||
if len(imageRepo.images) != 0 {
|
||||
t.Errorf("expected no image to be created, got %d", len(imageRepo.images))
|
||||
}
|
||||
if len(articleRepo.articles[1].Images) != 0 {
|
||||
t.Errorf("expected article 1 to still have an empty Images slice, got %+v", articleRepo.articles[1].Images)
|
||||
if rec.Code != example.status {
|
||||
t.Fatalf("expected status %d, got %d", example.status, rec.Code)
|
||||
}
|
||||
if env.images.createCalls != 0 {
|
||||
t.Errorf("expected Create to never be called, got %d calls", env.images.createCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Uploading an image still requires authentication", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
t.Run("The alias still requires authentication", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/1/image", "before.png", "image/png")
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/article/1/image", "before.png", "image/png", pngBytes(t, 3, 2))
|
||||
rec := env.serve(t, req, 0)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected status 401, got %d", rec.Code)
|
||||
}
|
||||
if len(imageRepo.images) != 0 {
|
||||
t.Errorf("expected no image to be created, got %d", len(imageRepo.images))
|
||||
if env.images.createCalls != 0 {
|
||||
t.Errorf("expected Create to never be called, got %d calls", env.images.createCalls)
|
||||
}
|
||||
if len(articleRepo.articles[1].Images) != 0 {
|
||||
t.Errorf("expected article 1 to still have an empty Images slice, got %+v", articleRepo.articles[1].Images)
|
||||
})
|
||||
|
||||
t.Run("The removed delete route is gone", func(t *testing.T) {
|
||||
env := newEnv(t)
|
||||
env.seedImage(10, "before.png", 10, "image/png", 3, 2, sha256Hex([]byte("x")), 1)
|
||||
|
||||
rec := env.send(t, http.MethodDelete, "/v1/article/1/image/10", "", mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusNotFound && rec.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("expected status 404 or 405, got %d", rec.Code)
|
||||
}
|
||||
if _, ok := env.images.images[10]; !ok {
|
||||
t.Errorf("expected image 10 to still exist")
|
||||
}
|
||||
if len(env.images.deleteCalls) != 0 {
|
||||
t.Errorf("expected Delete to never be called, got %v", env.images.deleteCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Uploading with a non-numeric article id answers 400", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
env := newEnv(t)
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/abc/image", "before.png", "image/png")
|
||||
setUploadJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/article/abc/image", "before.png", "image/png", pngBytes(t, 3, 2))
|
||||
rec := env.serve(t, req, mediaVerifiedUserId)
|
||||
|
||||
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())
|
||||
if rec.Code != http.StatusBadRequest || rec.Body.String() != apperr.IdUint32ErrorMessage+"\n" {
|
||||
t.Fatalf("expected 400 with the id message, got %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Uploading without a file field answers 400", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
env := newEnv(t)
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/article/1/image", body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
setUploadJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
rec := env.serve(t, newMultipartWithoutFileRequest(t, "/v1/article/1/image"), mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status 400, got %d", rec.Code)
|
||||
}
|
||||
if len(imageRepo.images) != 0 {
|
||||
t.Errorf("expected no image to be created, got %d", len(imageRepo.images))
|
||||
if env.images.createCalls != 0 {
|
||||
t.Errorf("expected Create to never be called, got %d calls", env.images.createCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A repository failure while fetching the article answers 500", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
articleRepo.fail.failNext("Get")
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
env := newEnv(t)
|
||||
env.articles.fail.failNext("Get")
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/1/image", "before.png", "image/png")
|
||||
setUploadJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/article/1/image", "before.png", "image/png", pngBytes(t, 3, 2))
|
||||
rec := env.serve(t, req, mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected status 500, got %d", rec.Code)
|
||||
@@ -266,94 +163,14 @@ func TestUploadArticleImageHttp(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("A repository failure while creating the image answers 500", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
imageRepo := newMockImageRepo()
|
||||
imageRepo.fail.failNext("Create")
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
env := newEnv(t)
|
||||
env.images.fail.failNext("Create")
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/1/image", "before.png", "image/png")
|
||||
setUploadJwtCookie(t, req, token)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/article/1/image", "before.png", "image/png", pngBytes(t, 3, 2))
|
||||
rec := env.serve(t, req, mediaVerifiedUserId)
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected status 500, got %d", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Uploading a file over the size limit answers 400", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
part, err := writer.CreatePart(map[string][]string{
|
||||
"Content-Disposition": {`form-data; name="file"; filename="huge.png"`},
|
||||
"Content-Type": {"image/png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create multipart part: %v", err)
|
||||
}
|
||||
if _, err := io.Copy(part, strings.NewReader(strings.Repeat("a", int(domainImage.MaxImageSize)+1))); err != nil {
|
||||
t.Fatalf("failed to write file content: %v", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/article/1/image", body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
setUploadJwtCookie(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() != domainImage.ErrImageTooLarge.Error()+"\n" {
|
||||
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||
}
|
||||
if len(imageRepo.images) != 0 {
|
||||
t.Errorf("expected no image to be created, got %d", len(imageRepo.images))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A repository failure while attaching the image to the article answers 500", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
articleRepo.fail.failNext("AddImage")
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/1/image", "before.png", "image/png")
|
||||
setUploadJwtCookie(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("AddImage reporting a missing article after the initial lookup still answers 404", func(t *testing.T) {
|
||||
articleRepo := newMockArticleRepo()
|
||||
articleRepo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
|
||||
articleRepo.fail.failNextWith("AddImage", domainArticle.ErrArticleNotFound)
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newUploadArticleImageRouter(articleRepo, imageRepo, token)
|
||||
|
||||
req := newMultipartImageUploadRequest(t, "/v1/article/1/image", "before.png", "image/png")
|
||||
setUploadJwtCookie(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())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
imageDomain "RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
@@ -236,7 +237,6 @@ func TestUpdateArticleDelegatesEachOperation(t *testing.T) {
|
||||
newRepo := func() *mockArticleRepo {
|
||||
repo := newMockArticleRepo()
|
||||
repo.articles[1] = article.Article{ID: 1, Title: "Existing"}
|
||||
repo.images[1] = &imageDomain.Image{ID: 1, Path: "/static/one.png"}
|
||||
return repo
|
||||
}
|
||||
|
||||
@@ -281,47 +281,13 @@ func TestUpdateArticleDelegatesEachOperation(t *testing.T) {
|
||||
t.Errorf("expected article.ErrArticleNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("AddImage_article1_image1", func(t *testing.T) {
|
||||
repo := newRepo()
|
||||
uc := useCases.NewUpdateArticleUseCase(repo)
|
||||
err := uc.AddImage(1, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
updated, err := repo.Get(1)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if len(updated.Images) != 1 || updated.Images[0].ID != 1 {
|
||||
t.Errorf("expected image 1 attached, got %+v", updated.Images)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("AddImage_article9_image1", func(t *testing.T) {
|
||||
repo := newRepo()
|
||||
uc := useCases.NewUpdateArticleUseCase(repo)
|
||||
err := uc.AddImage(9, 1)
|
||||
if !errors.Is(err, article.ErrArticleNotFound) {
|
||||
t.Errorf("expected article.ErrArticleNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("AddImage_article1_image9", func(t *testing.T) {
|
||||
repo := newRepo()
|
||||
uc := useCases.NewUpdateArticleUseCase(repo)
|
||||
err := uc.AddImage(1, 9)
|
||||
if !errors.Is(err, imageDomain.ErrImageNotFound) {
|
||||
t.Errorf("expected image.ErrImageNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeleteArticleReportsMissingArticle(t *testing.T) {
|
||||
t.Run("id_1", func(t *testing.T) {
|
||||
repo := newMockArticleRepo()
|
||||
repo.articles[1] = article.Article{ID: 1}
|
||||
uc := useCases.NewDeleteArticleUseCase(repo, newMockImageRepo())
|
||||
uc := useCases.NewDeleteArticleUseCase(repo)
|
||||
|
||||
err := uc.DeleteArticle(1)
|
||||
if err != nil {
|
||||
@@ -332,7 +298,7 @@ func TestDeleteArticleReportsMissingArticle(t *testing.T) {
|
||||
t.Run("id_9", func(t *testing.T) {
|
||||
repo := newMockArticleRepo()
|
||||
repo.articles[1] = article.Article{ID: 1}
|
||||
uc := useCases.NewDeleteArticleUseCase(repo, newMockImageRepo())
|
||||
uc := useCases.NewDeleteArticleUseCase(repo)
|
||||
|
||||
err := uc.DeleteArticle(9)
|
||||
if !errors.Is(err, article.ErrArticleNotFound) {
|
||||
@@ -345,7 +311,7 @@ func TestDeleteArticlePropagatesRepositoryFailure(t *testing.T) {
|
||||
repo := newMockArticleRepo()
|
||||
repo.articles[1] = article.Article{ID: 1}
|
||||
repo.fail.failNext("Delete")
|
||||
uc := useCases.NewDeleteArticleUseCase(repo, newMockImageRepo())
|
||||
uc := useCases.NewDeleteArticleUseCase(repo)
|
||||
|
||||
err := uc.DeleteArticle(1)
|
||||
if !errors.Is(err, errRepositoryFailure) {
|
||||
@@ -370,8 +336,12 @@ func TestCreateImageDelegatesContentTypeCheck(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
uc := useCases.NewCreateImageUseCase(repo)
|
||||
|
||||
content := []byte("fake-image-data")
|
||||
if tc.valid {
|
||||
content = validBytesFor(t, tc.contentType)
|
||||
}
|
||||
result, err := uc.CreateImage(imageDomain.ImageInput{
|
||||
Content: strings.NewReader("fake-image-data"),
|
||||
Content: bytes.NewReader(content),
|
||||
Filename: "test.img",
|
||||
ContentType: tc.contentType,
|
||||
})
|
||||
@@ -401,7 +371,7 @@ func TestCreateImagePropagatesRepositoryFailure(t *testing.T) {
|
||||
uc := useCases.NewCreateImageUseCase(repo)
|
||||
|
||||
_, err := uc.CreateImage(imageDomain.ImageInput{
|
||||
Content: strings.NewReader("data"),
|
||||
Content: bytes.NewReader(pngBytes(t, 3, 2)),
|
||||
Filename: "test.png",
|
||||
ContentType: "image/png",
|
||||
})
|
||||
@@ -415,9 +385,9 @@ func TestDeleteImageRequiresExistence(t *testing.T) {
|
||||
t.Run("id_1", func(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
repo.images[1] = imageDomain.Image{ID: 1}
|
||||
uc := useCases.NewDeleteImageUseCase(repo)
|
||||
uc := useCases.NewDeleteMediaUseCase(repo)
|
||||
|
||||
err := uc.DeleteImage(1)
|
||||
err := uc.Delete(1)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
@@ -429,9 +399,9 @@ func TestDeleteImageRequiresExistence(t *testing.T) {
|
||||
t.Run("id_9", func(t *testing.T) {
|
||||
repo := newMockImageRepo()
|
||||
repo.images[1] = imageDomain.Image{ID: 1}
|
||||
uc := useCases.NewDeleteImageUseCase(repo)
|
||||
uc := useCases.NewDeleteMediaUseCase(repo)
|
||||
|
||||
err := uc.DeleteImage(9)
|
||||
err := uc.Delete(9)
|
||||
if !errors.Is(err, imageDomain.ErrImageNotFound) {
|
||||
t.Errorf("expected image.ErrImageNotFound, got %v", err)
|
||||
}
|
||||
|
||||
@@ -27,15 +27,13 @@ func newVerifiedAccountRequiredRouter(articleRepo *mockArticleRepo, userRepo *mo
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, imageRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
imageHandler := image.NewHandler(
|
||||
useCases.NewCreateImageUseCase(imageRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
useCases.NewDeleteImageUseCase(imageRepo),
|
||||
)
|
||||
|
||||
r := chi.NewRouter()
|
||||
@@ -52,7 +50,7 @@ func newVerifiedAccountRequiredRouter(articleRepo *mockArticleRepo, userRepo *mo
|
||||
r.Patch("/{id}", articleHandler.UpdateArticleBody)
|
||||
r.Patch("/{id}/publish", articleHandler.PublishArticle)
|
||||
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
|
||||
r.Post("/{id}/image", imageHandler.PostImage)
|
||||
r.Post("/{id}/image", imageHandler.PostLegacyArticleImage)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -85,20 +85,6 @@ func TestTheArticleRepositoryReportsAMissingArticleAsADomainErrorOnAWrite(t *tes
|
||||
})
|
||||
}
|
||||
|
||||
func TestAddImageReportsAMissingArticleAsADomainErrorNotAMissingImage(t *testing.T) {
|
||||
repo := newSeededArticleRepository(t)
|
||||
|
||||
err := repo.AddImage(9, 1)
|
||||
assertWriteResultIsArticleNotFound(t, err)
|
||||
}
|
||||
|
||||
func TestAddImageReportsAMissingImageAsADomainErrorOnceTheArticleExists(t *testing.T) {
|
||||
repo := newSeededArticleRepository(t)
|
||||
|
||||
err := repo.AddImage(1, 9)
|
||||
assertWriteResultIsImageNotFound(t, err)
|
||||
}
|
||||
|
||||
func newSeededUserRepository(t *testing.T) *persistence.UserRepository {
|
||||
t.Helper()
|
||||
db := openInMemoryDb(t)
|
||||
@@ -205,13 +191,6 @@ func TestTheFakesMirrorTheRealRepositoriesOnEveryWriteNotFoundPath(t *testing.T)
|
||||
if err := articleRepo.Delete(9); !errors.Is(err, domainArticle.ErrArticleNotFound) {
|
||||
t.Errorf("expected article.ErrArticleNotFound, got %v", err)
|
||||
}
|
||||
if err := articleRepo.AddImage(9, 1); !errors.Is(err, domainArticle.ErrArticleNotFound) {
|
||||
t.Errorf("expected article.ErrArticleNotFound, got %v", err)
|
||||
}
|
||||
articleRepo.images[1] = &domainImage.Image{ID: 1}
|
||||
if err := articleRepo.AddImage(1, 9); !errors.Is(err, domainImage.ErrImageNotFound) {
|
||||
t.Errorf("expected image.ErrImageNotFound, got %v", err)
|
||||
}
|
||||
|
||||
userRepo := newMockUserRepo()
|
||||
userRepo.users[1] = domainUser.User{ID: 1, Username: "alice"}
|
||||
@@ -237,7 +216,7 @@ func newDeleteArticleRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user