Files
sm-journal-plugin/controllers/api/media_test.go
Jakub Zych 15fcad7a93 refactor(api): share media storage with the editor upload
- classes.StoreMedia holds the media upload route's storage: extension
  allowlist, 10240 KiB cap, /journal/<folder>/<name> keys with the unique
  suffix, bucket write and public URL
- UploadMedia keeps authentication, permissions, the folder and form checks
  and answers with the same 201 body and messages
- uniqueMediaKey fails instead of overwriting when every numbered name is
  taken; the media path tests move to classes
2026-10-10 12:08:42 +02:00

48 lines
1.8 KiB
Go

package api
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"git.golem15.com/golem15/sm-journal-plugin/classes"
)
// TestWriteMediaStoreError pins the media upload route's error bodies (D-09)
// after the storage moved to classes.StoreMedia: a MediaError is the same
// 422 body writeValidation always wrote, anything else the opaque 500.
func TestWriteMediaStoreError(t *testing.T) {
for _, tc := range []struct {
name string
err error
status int
body string
}{
{"size", &classes.MediaError{Field: "file", Message: "The file may not be greater than 10240 kilobytes."}, http.StatusUnprocessableEntity,
`{"error":"Validation failed","errors":{"file":["The file may not be greater than 10240 kilobytes."]}}`},
{"extension", &classes.MediaError{Field: "file", Message: "The file must be an image."}, http.StatusUnprocessableEntity,
`{"error":"Validation failed","errors":{"file":["The file must be an image."]}}`},
{"other", errors.New("disk full"), http.StatusInternalServerError, `{"error":"Internal server error"}`},
} {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
writeMediaStoreError(rec, tc.err)
want := httptest.NewRecorder()
if tc.status == http.StatusUnprocessableEntity {
var refused *classes.MediaError
errors.As(tc.err, &refused)
writeValidation(want, map[string][]string{refused.Field: {refused.Message}})
} else {
writeAPIError(want, http.StatusInternalServerError, "Internal server error")
}
if rec.Code != tc.status || rec.Body.String() != want.Body.String() {
t.Fatalf("got %d %s, want %d %s", rec.Code, rec.Body.String(), tc.status, want.Body.String())
}
if got := rec.Body.String(); got != tc.body && got != tc.body+"\n" {
t.Fatalf("body = %q, want %q", got, tc.body)
}
})
}
}