forked from mtusi2026/mtusi2026lab3
на оценку 3
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
store "mtusi2026lab3/internal/adapter/memory"
|
||||
"mtusi2026lab3/internal/domain"
|
||||
"mtusi2026lab3/internal/transport/http/dto"
|
||||
)
|
||||
|
||||
func sendMessageRequest(
|
||||
t *testing.T,
|
||||
serverURL string,
|
||||
chatID string,
|
||||
actorID string,
|
||||
key string,
|
||||
body string,
|
||||
) (int, []byte) {
|
||||
t.Helper()
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID),
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create message request: %v", err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", actorID)
|
||||
if key != "" {
|
||||
request.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send message request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read message response: %v", err)
|
||||
}
|
||||
return response.StatusCode, payload
|
||||
}
|
||||
|
||||
func decodeMessageResponse(t *testing.T, payload []byte) dto.MessageResponse {
|
||||
t.Helper()
|
||||
|
||||
var message dto.MessageResponse
|
||||
if err := json.Unmarshal(payload, &message); err != nil {
|
||||
t.Fatalf("decode message response: %v; body=%s", err, payload)
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func createMessageFixture(t *testing.T) (*store.MemoryStore, string, domain.User, string) {
|
||||
t.Helper()
|
||||
|
||||
server, memoryStore := setupTestServer()
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
user, err := memoryStore.CreateUser("idempotency_user", "Idempotency User")
|
||||
if err != nil {
|
||||
t.Fatalf("create fixture user: %v", err)
|
||||
}
|
||||
chat, err := memoryStore.CreateChat("Idempotency Chat", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create fixture chat: %v", err)
|
||||
}
|
||||
|
||||
return memoryStore, server.URL, user, chat.ID
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyKeyValidation(t *testing.T) {
|
||||
_, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
key string
|
||||
}{
|
||||
{name: "missing", key: ""},
|
||||
{name: "space", key: "invalid key"},
|
||||
{name: "non ascii", key: "ключ"},
|
||||
{name: "too long", key: string(bytes.Repeat([]byte{'a'}, 129))},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
status, _ := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
testCase.key,
|
||||
`{"text":"hello"}`,
|
||||
)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyReplayAndConflict(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
status, firstPayload := sendMessageRequest(
|
||||
t, serverURL, chatID, user.ID, "replay-key", `{"text":"hello"}`,
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first request: expected 201, got %d: %s", status, firstPayload)
|
||||
}
|
||||
|
||||
status, replayPayload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"replay-key",
|
||||
"{\n \"text\": \"hello\"\n}",
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: expected 201, got %d: %s", status, replayPayload)
|
||||
}
|
||||
|
||||
first := decodeMessageResponse(t, firstPayload)
|
||||
replay := decodeMessageResponse(t, replayPayload)
|
||||
if first != replay {
|
||||
t.Fatalf("replay changed message: first=%+v replay=%+v", first, replay)
|
||||
}
|
||||
|
||||
status, _ = sendMessageRequest(
|
||||
t, serverURL, chatID, user.ID, "replay-key", `{"text":"different"}`,
|
||||
)
|
||||
if status != http.StatusConflict {
|
||||
t.Fatalf("different body: expected 409, got %d", status)
|
||||
}
|
||||
|
||||
messages, _, err := memoryStore.GetMessages(chatID, user.ID, 10, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("list messages: %v", err)
|
||||
}
|
||||
if len(messages) != 1 {
|
||||
t.Fatalf("expected one stored message, got %d", len(messages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyScopesAreIndependent(t *testing.T) {
|
||||
server, memoryStore := setupTestServer()
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
alice, _ := memoryStore.CreateUser("scope_alice", "Alice")
|
||||
bob, _ := memoryStore.CreateUser("scope_bob", "Bob")
|
||||
firstChat, _ := memoryStore.CreateChat("First", []string{alice.ID, bob.ID})
|
||||
secondChat, _ := memoryStore.CreateChat("Second", []string{alice.ID, bob.ID})
|
||||
|
||||
testCases := []struct {
|
||||
actorID string
|
||||
chatID string
|
||||
text string
|
||||
}{
|
||||
{actorID: alice.ID, chatID: firstChat.ID, text: "alice first"},
|
||||
{actorID: bob.ID, chatID: firstChat.ID, text: "bob first"},
|
||||
{actorID: alice.ID, chatID: secondChat.ID, text: "alice second"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
status, payload := sendMessageRequest(
|
||||
t,
|
||||
server.URL,
|
||||
testCase.chatID,
|
||||
testCase.actorID,
|
||||
"shared-key",
|
||||
fmt.Sprintf(`{"text":%q}`, testCase.text),
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("independent scope: expected 201, got %d: %s", status, payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessageIdempotencyCreatesExactlyOneMessage(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
const clients = 32
|
||||
start := make(chan struct{})
|
||||
results := make(chan dto.MessageResponse, clients)
|
||||
errors := make(chan error, clients)
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
for index := 0; index < clients; index++ {
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
<-start
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID),
|
||||
bytes.NewBufferString(`{"text":"concurrent replay"}`),
|
||||
)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", user.ID)
|
||||
request.Header.Set("Idempotency-Key", "one-concurrent-key")
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
payload, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
errors <- fmt.Errorf("expected 201, got %d: %s", response.StatusCode, payload)
|
||||
return
|
||||
}
|
||||
|
||||
var message dto.MessageResponse
|
||||
if err = json.Unmarshal(payload, &message); err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
results <- message
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
waitGroup.Wait()
|
||||
close(results)
|
||||
close(errors)
|
||||
|
||||
for err := range errors {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
var expected dto.MessageResponse
|
||||
count := 0
|
||||
for message := range results {
|
||||
if count == 0 {
|
||||
expected = message
|
||||
} else if message != expected {
|
||||
t.Fatalf("concurrent replay returned different message: %+v != %+v", message, expected)
|
||||
}
|
||||
count++
|
||||
}
|
||||
if count != clients {
|
||||
t.Fatalf("expected %d successful responses, got %d", clients, count)
|
||||
}
|
||||
|
||||
messages, _, err := memoryStore.GetMessages(chatID, user.ID, clients+1, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("list messages: %v", err)
|
||||
}
|
||||
if len(messages) != 1 {
|
||||
t.Fatalf("expected exactly one stored message, got %d", len(messages))
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,7 @@ func TestEmptyMessageValidation(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
req.Header.Set("Idempotency-Key", "empty-text")
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
@@ -147,6 +148,7 @@ func TestEmptyMessageValidation(t *testing.T) {
|
||||
reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`))
|
||||
reqSpaces.Header.Set("Content-Type", "application/json")
|
||||
reqSpaces.Header.Set("X-User-Id", u.ID)
|
||||
reqSpaces.Header.Set("Idempotency-Key", "spaces-text")
|
||||
|
||||
resSpaces, _ := http.DefaultClient.Do(reqSpaces)
|
||||
if resSpaces.StatusCode != http.StatusBadRequest {
|
||||
@@ -494,6 +496,10 @@ func TestConcurrent100MessagesFrom10Clients(t *testing.T) {
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", senderID)
|
||||
req.Header.Set(
|
||||
"Idempotency-Key",
|
||||
fmt.Sprintf("concurrent-%d-%d", clientIndex, m),
|
||||
)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil || res.StatusCode != http.StatusCreated {
|
||||
@@ -638,6 +644,7 @@ func TestUnicodeLimits(t *testing.T) {
|
||||
req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", u.ID)
|
||||
req1.Header.Set("Idempotency-Key", "unicode-valid")
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode)
|
||||
@@ -652,6 +659,7 @@ func TestUnicodeLimits(t *testing.T) {
|
||||
req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", u.ID)
|
||||
req2.Header.Set("Idempotency-Key", "unicode-too-long")
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode)
|
||||
|
||||
Reference in New Issue
Block a user