forked from mtusi2026/mtusi2026lab4
лаба 4 на оценку 5
This commit is contained in:
@@ -8,7 +8,11 @@ import (
|
||||
|
||||
const testCursorSigningKey = "student-tests-cursor-signing-key-at-least-32-bytes"
|
||||
|
||||
func newTestService(repository application.Repository, sessionTTL time.Duration) *application.Service {
|
||||
func newTestService(
|
||||
repository application.Repository,
|
||||
sessionTTL time.Duration,
|
||||
options ...application.ServiceOption,
|
||||
) *application.Service {
|
||||
if sessionTTL <= 0 {
|
||||
sessionTTL = time.Hour
|
||||
}
|
||||
@@ -16,7 +20,7 @@ func newTestService(repository application.Repository, sessionTTL time.Duration)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
service, err := application.NewService(repository, codec, sessionTTL)
|
||||
service, err := application.NewService(repository, codec, sessionTTL, options...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
@@ -133,7 +134,7 @@ func TestMessageIdempotencyReplayAndConflict(t *testing.T) {
|
||||
|
||||
first := decodeMessageResponse(t, firstPayload)
|
||||
replay := decodeMessageResponse(t, replayPayload)
|
||||
if first != replay {
|
||||
if !reflect.DeepEqual(first, replay) {
|
||||
t.Fatalf("replay changed message: first=%+v replay=%+v", first, replay)
|
||||
}
|
||||
|
||||
@@ -256,7 +257,7 @@ func TestConcurrentMessageIdempotencyCreatesExactlyOneMessage(t *testing.T) {
|
||||
for message := range results {
|
||||
if count == 0 {
|
||||
expected = message
|
||||
} else if message != expected {
|
||||
} else if !reflect.DeepEqual(message, expected) {
|
||||
t.Fatalf("concurrent replay returned different message: %+v != %+v", message, expected)
|
||||
}
|
||||
count++
|
||||
@@ -273,3 +274,40 @@ func TestConcurrentMessageIdempotencyCreatesExactlyOneMessage(t *testing.T) {
|
||||
t.Fatalf("expected exactly one stored message, got %d", len(messages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyTreatsMissingAndEmptyAttachmentsEqually(t *testing.T) {
|
||||
_, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
status, firstPayload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"default-attachments",
|
||||
`{"text":"same semantic request"}`,
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first request: expected 201, got %d: %s", status, firstPayload)
|
||||
}
|
||||
|
||||
status, replayPayload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"default-attachments",
|
||||
`{"attachment_ids":[],"text":"same semantic request"}`,
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: expected 201, got %d: %s", status, replayPayload)
|
||||
}
|
||||
|
||||
first := decodeMessageResponse(t, firstPayload)
|
||||
replay := decodeMessageResponse(t, replayPayload)
|
||||
if !reflect.DeepEqual(first, replay) {
|
||||
t.Fatalf("missing attachment_ids and [] must replay identically")
|
||||
}
|
||||
if first.AttachmentIDs == nil || len(first.AttachmentIDs) != 0 {
|
||||
t.Fatalf("response must contain attachment_ids: [], got %#v", first.AttachmentIDs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
func TestMessageAttachmentContract(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
readyID := "11111111-1111-4111-8111-111111111111"
|
||||
if err := memoryStore.PutAttachment(domain.Attachment{
|
||||
ID: readyID,
|
||||
ChatID: chatID,
|
||||
OwnerID: user.ID,
|
||||
Status: domain.AttachmentStatusReady,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed ready attachment: %v", err)
|
||||
}
|
||||
|
||||
status, payload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"attachment-only",
|
||||
fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, readyID),
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("attachment-only message: expected 201, got %d: %s", status, payload)
|
||||
}
|
||||
|
||||
message := decodeMessageResponse(t, payload)
|
||||
if message.Text != "" {
|
||||
t.Fatalf("attachment-only message changed text: %q", message.Text)
|
||||
}
|
||||
if !reflect.DeepEqual(message.AttachmentIDs, []string{readyID}) {
|
||||
t.Fatalf("attachment_ids changed: %#v", message.AttachmentIDs)
|
||||
}
|
||||
|
||||
items, _, err := memoryStore.GetMessages(chatID, user.ID, 10, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("read stored messages: %v", err)
|
||||
}
|
||||
if len(items) != 1 || !reflect.DeepEqual(items[0].AttachmentIDs, []string{readyID}) {
|
||||
t.Fatalf("stored attachment relation differs: %#v", items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentValidationAndAccess(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
otherChat, err := memoryStore.CreateChat("Other chat", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create other chat: %v", err)
|
||||
}
|
||||
|
||||
pendingID := "22222222-2222-4222-8222-222222222222"
|
||||
if err = memoryStore.PutAttachment(domain.Attachment{
|
||||
ID: pendingID,
|
||||
ChatID: chatID,
|
||||
OwnerID: user.ID,
|
||||
Status: domain.AttachmentStatusPending,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed pending attachment: %v", err)
|
||||
}
|
||||
|
||||
foreignID := "33333333-3333-4333-8333-333333333333"
|
||||
if err = memoryStore.PutAttachment(domain.Attachment{
|
||||
ID: foreignID,
|
||||
ChatID: otherChat.ID,
|
||||
OwnerID: user.ID,
|
||||
Status: domain.AttachmentStatusReady,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed foreign attachment: %v", err)
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "empty without attachments",
|
||||
body: `{"text":"","attachment_ids":[]}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "invalid attachment uuid",
|
||||
body: `{"text":"hello","attachment_ids":["not-a-uuid"]}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "duplicate attachment",
|
||||
body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q,%q]}`, pendingID, pendingID),
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "unknown attachment",
|
||||
body: `{"text":"hello","attachment_ids":["44444444-4444-4444-8444-444444444444"]}`,
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "attachment from another chat",
|
||||
body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q]}`, foreignID),
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "attachment not ready",
|
||||
body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q]}`, pendingID),
|
||||
wantStatus: http.StatusConflict,
|
||||
},
|
||||
}
|
||||
|
||||
for index, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
status, payload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
fmt.Sprintf("attachment-validation-%d", index),
|
||||
testCase.body,
|
||||
)
|
||||
if status != testCase.wantStatus {
|
||||
t.Fatalf("expected %d, got %d: %s", testCase.wantStatus, status, payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user