package student_tests import ( "bytes" "context" "encoding/json" "image" "image/color" "image/png" "io" "net/http" "net/http/httptest" "net/url" "sync" "testing" "time" store "mtusi2026lab4/internal/adapter/memory" "mtusi2026lab4/internal/application" "mtusi2026lab4/internal/domain" "mtusi2026lab4/internal/transport/http/dto" "mtusi2026lab4/internal/transport/http/handlers" "mtusi2026lab4/internal/transport/http/middleware" ) type httpFakeObjectStore struct { mu sync.Mutex objects map[string][]byte } func (store *httpFakeObjectStore) Put(_ context.Context, object application.ObjectPut) error { 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 *httpFakeObjectStore) Get(_ context.Context, key string) (application.ObjectContent, error) { store.mu.Lock() defer store.mu.Unlock() payload, exists := store.objects[key] if !exists { return application.ObjectContent{}, domain.ErrNotFound } copyOfPayload := append([]byte(nil), payload...) return application.ObjectContent{ Body: io.NopCloser(bytes.NewReader(copyOfPayload)), SizeBytes: int64(len(copyOfPayload)), }, nil } func (store *httpFakeObjectStore) Delete(_ context.Context, key string) error { store.mu.Lock() delete(store.objects, key) store.mu.Unlock() return nil } func setupAttachmentUploadServer( t *testing.T, ) (*httptest.Server, *store.MemoryStore, *httpFakeObjectStore) { t.Helper() memoryStore := store.NewMemoryStore() repository := store.NewMemoryRepository(memoryStore) objectStore := &httpFakeObjectStore{objects: make(map[string][]byte)} service := newTestService( repository, time.Hour, application.WithObjectStore(objectStore), ) handler := handlers.NewHandler(service) mux := http.NewServeMux() mux.HandleFunc( "POST /api/v1/chats/{chat_id}/attachments", requireLegacyAuth(memoryStore, handler.UploadAttachment), ) mux.HandleFunc( "GET /api/v1/attachments/{attachment_id}", requireLegacyAuth(memoryStore, handler.GetAttachment), ) mux.HandleFunc( "GET /api/v1/attachments/{attachment_id}/content", requireLegacyAuth(memoryStore, handler.DownloadAttachment), ) var root http.Handler = mux root = middleware.Recovery(root) root = middleware.RequestID(root) return httptest.NewServer(root), memoryStore, objectStore } func pngPayload(t *testing.T) []byte { t.Helper() var payload bytes.Buffer img := image.NewRGBA(image.Rect(0, 0, 2, 2)) 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 uploadRequest( t *testing.T, baseURL string, chatID string, userID string, filename string, contentType string, payload []byte, ) *http.Response { t.Helper() requestURL := baseURL + "/api/v1/chats/" + chatID + "/attachments?filename=" + url.QueryEscape(filename) request, err := http.NewRequest(http.MethodPost, requestURL, bytes.NewReader(payload)) if err != nil { t.Fatal(err) } request.Header.Set("Content-Type", contentType) request.Header.Set("X-User-Id", userID) response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } return response } func attachmentGetRequest(t *testing.T, requestURL string, userID string) *http.Response { t.Helper() request, err := http.NewRequest(http.MethodGet, requestURL, nil) if err != nil { t.Fatal(err) } request.Header.Set("X-User-Id", userID) response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } return response } func TestUploadAttachmentHTTPContract(t *testing.T) { server, memoryStore, objectStore := setupAttachmentUploadServer(t) defer server.Close() user, err := memoryStore.CreateUser("attachment_user", "Attachment User") if err != nil { t.Fatal(err) } outsider, err := memoryStore.CreateUser("attachment_outsider", "Attachment Outsider") if err != nil { t.Fatal(err) } chat, err := memoryStore.CreateChat("Images", []string{user.ID}) if err != nil { t.Fatal(err) } payload := pngPayload(t) response := uploadRequest(t, server.URL, chat.ID, user.ID, "кот.png", "image/png", payload) defer response.Body.Close() if response.StatusCode != http.StatusCreated { body, _ := io.ReadAll(response.Body) t.Fatalf("status = %d, want 201: %s", response.StatusCode, body) } var attachment dto.AttachmentResponse if err = json.NewDecoder(response.Body).Decode(&attachment); err != nil { t.Fatal(err) } if attachment.Status != domain.AttachmentStatusReady || attachment.Filename != "кот.png" { t.Fatalf("unexpected response: %+v", attachment) } if attachment.Variants == nil || len(attachment.Variants) != 0 || attachment.ErrorCode != nil { t.Fatalf("contract arrays/nulls differ: %+v", attachment) } objectStore.mu.Lock() storedObjects := len(objectStore.objects) objectStore.mu.Unlock() if storedObjects != 1 { t.Fatalf("stored objects = %d, want 1", storedObjects) } metadataResponse := attachmentGetRequest(t, server.URL+"/api/v1/attachments/"+attachment.ID, user.ID) defer metadataResponse.Body.Close() if metadataResponse.StatusCode != http.StatusOK { t.Fatalf("metadata status = %d, want 200", metadataResponse.StatusCode) } contentResponse := attachmentGetRequest(t, server.URL+"/api/v1/attachments/"+attachment.ID+"/content", user.ID) defer contentResponse.Body.Close() downloaded, err := io.ReadAll(contentResponse.Body) if err != nil { t.Fatal(err) } if contentResponse.StatusCode != http.StatusOK || !bytes.Equal(downloaded, payload) { t.Fatalf("download status/content differ: status=%d", contentResponse.StatusCode) } if contentResponse.Header.Get("Content-Type") != "image/png" { t.Fatalf("download Content-Type = %q", contentResponse.Header.Get("Content-Type")) } for _, suffix := range []string{"", "/content"} { outsiderResponse := attachmentGetRequest(t, server.URL+"/api/v1/attachments/"+attachment.ID+suffix, outsider.ID) _ = outsiderResponse.Body.Close() if outsiderResponse.StatusCode != http.StatusNotFound { t.Fatalf("outsider %q status = %d, want 404", suffix, outsiderResponse.StatusCode) } } missingVariant := attachmentGetRequest(t, server.URL+"/api/v1/attachments/"+attachment.ID+"/content?variant=thumbnail", user.ID) _ = missingVariant.Body.Close() if missingVariant.StatusCode != http.StatusNotFound { t.Fatalf("missing variant status = %d, want 404", missingVariant.StatusCode) } } func TestUploadAttachmentHTTPErrorMapping(t *testing.T) { server, memoryStore, _ := setupAttachmentUploadServer(t) defer server.Close() user, _ := memoryStore.CreateUser("attachment_errors", "Attachment Errors") chat, _ := memoryStore.CreateChat("Images", []string{user.ID}) validPNG := pngPayload(t) testCases := []struct { name string chatID string filename string contentType string payload []byte wantStatus int }{ {name: "unsafe filename", chatID: chat.ID, filename: "../image.png", contentType: "image/png", payload: validPNG, wantStatus: http.StatusBadRequest}, {name: "unsupported content type", chatID: chat.ID, filename: "image.gif", contentType: "image/gif", payload: []byte("GIF89a"), wantStatus: http.StatusUnsupportedMediaType}, {name: "MIME substitution", chatID: chat.ID, filename: "image.jpg", contentType: "image/jpeg", payload: validPNG, wantStatus: http.StatusUnsupportedMediaType}, {name: "corrupt image", chatID: chat.ID, filename: "image.png", contentType: "image/png", payload: []byte("bad"), wantStatus: http.StatusUnsupportedMediaType}, {name: "too large", chatID: chat.ID, filename: "image.png", contentType: "image/png", payload: bytes.Repeat([]byte{0}, domain.MaxAttachmentSizeBytes+1), wantStatus: http.StatusRequestEntityTooLarge}, {name: "unknown chat", chatID: "11111111-1111-4111-8111-111111111111", filename: "image.png", contentType: "image/png", payload: validPNG, wantStatus: http.StatusNotFound}, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { response := uploadRequest(t, server.URL, testCase.chatID, user.ID, testCase.filename, testCase.contentType, testCase.payload) defer response.Body.Close() if response.StatusCode != testCase.wantStatus { body, _ := io.ReadAll(response.Body) t.Fatalf("status = %d, want %d: %s", response.StatusCode, testCase.wantStatus, body) } }) } }