test(attachments): add upload tests

This commit is contained in:
kk10
2026-11-03 12:35:11 +03:00
parent aaf9a1e00a
commit 5f3efc63a0
3 changed files with 202 additions and 3 deletions
+2
View File
@@ -8,6 +8,8 @@ http {
server {
listen 8080;
client_max_body_size 11m;
location ~ ^/api/v1/chats/[^/]+/messages$ {
set $backend http://api:8080;
proxy_pass $backend;
+3 -3
View File
@@ -51,7 +51,7 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodeInvalidRequest, "file too large", requestID)
httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID)
return
}
@@ -62,10 +62,10 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
att, err := h.service.Upload(r.Context(), userID, chatID, req.Filename, body, contentType)
switch {
case errors.Is(err, service.ErrInvalidSize):
httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodeInvalidRequest, "file too large", requestID)
httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID)
return
case errors.Is(err, service.ErrInvalidImage):
httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeInvalidRequest, "invalid image", requestID)
httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "invalid image", requestID)
return
case errors.Is(err, service.ErrAttachmentNotFound):
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
+197
View File
@@ -0,0 +1,197 @@
//go:build contract
package studenttests_test
import (
"bytes"
"encoding/json"
"image"
"image/color"
"image/png"
"net/http"
"net/url"
"testing"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
const maxUploadBytes = 10 * 1024 * 1024
func makePNG(t *testing.T, width, height int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
img.Set(x, y, color.RGBA{
R: uint8((x * 7) % 256),
G: uint8((y * 13) % 256),
B: uint8((x + y) % 256),
A: 255,
})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("encode png: %v", err)
}
return buf.Bytes()
}
func uploadAttachment(
t *testing.T,
actor testUser,
chatID uuid.UUID,
filename string,
contentType string,
body []byte,
) *http.Response {
t.Helper()
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/attachments?filename="+url.QueryEscape(filename),
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build upload request: %v", err)
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("Authorization", "Bearer "+actor.Token)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("upload request failed: %v", err)
}
return resp
}
func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentResponse {
t.Helper()
resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusCreated)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
return att
}
func postMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
attachmentIDs []uuid.UUID,
) *http.Response {
t.Helper()
body, err := json.Marshal(map[string]any{
"text": text,
"attachment_ids": attachmentIDs,
})
if err != nil {
t.Fatalf("marshal message: %v", err)
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build message request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("message request failed: %v", err)
}
return resp
}
func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) {
t.Helper()
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != code {
t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code)
}
}
func TestAttachmentTooLarge(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := bytes.Repeat([]byte{0x00}, maxUploadBytes+1)
resp := uploadAttachment(t, user, chat.ID, "big.png", "image/png", body)
requireStatus(t, resp, http.StatusRequestEntityTooLarge)
requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge)
}
func TestAttachmentCorruptedImage(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body := []byte("this is definitely not a png or jpeg image")
resp := uploadAttachment(t, user, chat.ID, "broken.png", "image/png", body)
requireStatus(t, resp, http.StatusUnsupportedMediaType)
requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType)
}
func TestAttachmentMimeSubstitution(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
resp := uploadAttachment(t, user, chat.ID, "actually-png.jpg", "image/jpeg", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusUnsupportedMediaType)
requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType)
}
func TestAttachmentForeignID(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
foreign := uuid.New()
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String(), user.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String()+"/content", user.Token, nil)
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
resp = postMessage(t, user, chat.ID, "", []uuid.UUID{foreign})
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
}
func TestAttachmentFromAnotherChat(t *testing.T) {
user := createUser(t)
member := createUser(t)
chatA := createChat(t, user, user.ID, member.ID)
chatB := createChat(t, user, user.ID)
att := uploadPNG(t, user, chatA.ID)
// The attachment belongs to chatA; linking it to a chatB message must fail.
resp := postMessage(t, user, chatB.ID, "", []uuid.UUID{att.ID})
requireStatus(t, resp, http.StatusNotFound)
requireErrorCode(t, resp, dto.ErrorCodeNotFound)
}