feat(API): media library

This commit is contained in:
fsylvain committed 2026-09-30 18:35:28 +02:00
1 parent 95ae043d3e
commit 0d99544579
65 files changed
+3992 -1530

No files matched your search

+97 -280
View File
@@ -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())
}
})
}