Files
mtusi2026lab6/internal/application/attachments_test.go
T

156 lines
5.1 KiB
Go

package application_test
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/png"
"io"
"sync"
"testing"
"time"
"mtusi2026lab6/internal/adapter/memory"
. "mtusi2026lab6/internal/application"
"mtusi2026lab6/internal/domain"
)
type fakeObjectStore struct {
mu sync.Mutex
objects map[string][]byte
putError error
}
func newFakeObjectStore() *fakeObjectStore { return &fakeObjectStore{objects: make(map[string][]byte)} }
func (store *fakeObjectStore) Put(_ context.Context, object ObjectPut) error {
if store.putError != nil {
return store.putError
}
payload, err := io.ReadAll(object.Body)
if err != nil {
return err
}
store.mu.Lock()
store.objects[object.Key] = payload
store.mu.Unlock()
return nil
}
func (store *fakeObjectStore) Get(_ context.Context, key string) (ObjectContent, error) {
store.mu.Lock()
defer store.mu.Unlock()
payload, ok := store.objects[key]
if !ok {
return ObjectContent{}, errors.New("not found")
}
return ObjectContent{Body: io.NopCloser(bytes.NewReader(payload)), SizeBytes: int64(len(payload))}, nil
}
func (store *fakeObjectStore) Delete(_ context.Context, key string) error {
store.mu.Lock()
delete(store.objects, key)
store.mu.Unlock()
return nil
}
type interruptedReader struct{}
func (interruptedReader) Read([]byte) (int, error) { return 0, errors.New("injected read failure") }
func newAttachmentService(t *testing.T, objects ObjectStore) (*Service, string, string) {
t.Helper()
legacy := memory.NewMemoryStore()
repository := memory.NewMemoryRepository(legacy)
user, err := repository.CreateUser(context.Background(), "uploader", "Uploader", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := repository.CreateChat(context.Background(), "Images", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("attachment-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objects), WithJobMaxAttempts(5))
if err != nil {
t.Fatal(err)
}
return service, user.ID, chat.ID
}
func testPNG(t *testing.T) []byte {
t.Helper()
var payload bytes.Buffer
img := image.NewRGBA(image.Rect(0, 0, 320, 200))
img.Set(0, 0, color.RGBA{R: 255, A: 255})
if err := png.Encode(&payload, img); err != nil {
t.Fatal(err)
}
return payload.Bytes()
}
func TestUploadAttachmentDurablyQueuesStagingObject(t *testing.T) {
objects := newFakeObjectStore()
service, actorID, chatID := newAttachmentService(t, objects)
payload := testPNG(t)
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID, ChatID: chatID, Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(payload),
})
if err != nil {
t.Fatal(err)
}
if attachment.Status != domain.AttachmentStatusQueued {
t.Fatalf("status=%s, want queued", attachment.Status)
}
if attachment.StagingKey == "" || attachment.ObjectKey == attachment.StagingKey {
t.Fatalf("staging/final keys are not separated: %+v", attachment)
}
objects.mu.Lock()
staged := append([]byte(nil), objects.objects[attachment.StagingKey]...)
objects.mu.Unlock()
if !bytes.Equal(staged, payload) {
t.Fatal("durable staging bytes differ")
}
}
func TestUploadAttachmentRejectsInvalidInputBeforeStaging(t *testing.T) {
objects := newFakeObjectStore()
service, actorID, chatID := newAttachmentService(t, objects)
cases := []struct {
name string
command UploadAttachmentCommand
target error
}{
{"unsafe filename", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "../x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))}, ErrInvalidInput},
{"mime", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/jpeg", Body: bytes.NewReader(testPNG(t))}, ErrUnsupportedMediaType},
{"corrupt", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader([]byte("broken"))}, ErrInvalidImage},
{"interrupted", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: interruptedReader{}}, ErrInvalidInput},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := service.UploadAttachment(context.Background(), tc.command); !errors.Is(err, tc.target) {
t.Fatalf("error=%v, want %v", err, tc.target)
}
})
}
objects.mu.Lock()
count := len(objects.objects)
objects.mu.Unlock()
if count != 0 {
t.Fatalf("invalid requests staged %d objects", count)
}
}
func TestUploadAttachmentStorageFailureDoesNotCreateQueuedMetadata(t *testing.T) {
objects := newFakeObjectStore()
objects.putError = errors.New("storage down")
service, actorID, chatID := newAttachmentService(t, objects)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))})
if !errors.Is(err, ErrStorageUnavailable) {
t.Fatalf("error=%v, want storage unavailable", err)
}
}