forked from mtusi2026/mtusi2026lab3
lab3
This commit is contained in:
@@ -2,6 +2,7 @@ package rest_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -22,7 +23,10 @@ import (
|
||||
"mtusi-messenger/internal/transport/rest/mocks"
|
||||
)
|
||||
|
||||
const requestIDHeader = "X-Request-ID"
|
||||
const (
|
||||
requestIDHeader = "X-Request-ID"
|
||||
instanceIDHeader = "X-Instance-Id"
|
||||
)
|
||||
|
||||
func basic(username, password string) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
|
||||
@@ -324,3 +328,114 @@ func TestNotFoundAndMethodNotAllowed(t *testing.T) {
|
||||
result = fixture.do(t, http.MethodDelete, "/health/live", nil, nil)
|
||||
require.Equal(t, http.StatusMethodNotAllowed, result.status)
|
||||
}
|
||||
|
||||
func TestCreateMessageRequiresIdempotencyKey(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
|
||||
result := fixture.do(
|
||||
t,
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+uuid.NewString()+"/messages",
|
||||
[]byte(`{"text":"привет"}`),
|
||||
map[string]string{"Authorization": "Bearer opaque-token"},
|
||||
)
|
||||
require.Equal(t, http.StatusBadRequest, result.status)
|
||||
require.NotEmpty(t, result.header.Get(instanceIDHeader), "ответ об ошибке тоже помечен репликой")
|
||||
}
|
||||
|
||||
func TestCreateMessageFingerprintIgnoresJSONFormatting(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
chatID := uuid.New()
|
||||
message := domain.Message{ID: uuid.New(), ChatID: chatID, SenderID: user.ID, Text: "привет", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
|
||||
var fingerprints [][sha256.Size]byte
|
||||
|
||||
fixture.messages.EXPECT().
|
||||
Send(mock.Anything, mock.MatchedBy(func(draft domain.MessageDraft) bool {
|
||||
if draft.ChatID != chatID || draft.SenderID != user.ID || draft.Idempotency.Key != "key-1" {
|
||||
return false
|
||||
}
|
||||
|
||||
fingerprints = append(fingerprints, draft.Idempotency.RequestHash)
|
||||
|
||||
return true
|
||||
})).
|
||||
Return(message, nil)
|
||||
|
||||
headers := map[string]string{"Authorization": "Bearer opaque-token", "Idempotency-Key": "key-1"}
|
||||
path := "/api/v1/chats/" + chatID.String() + "/messages"
|
||||
|
||||
first := fixture.do(t, http.MethodPost, path, []byte(`{"text":"привет"}`), headers)
|
||||
replay := fixture.do(t, http.MethodPost, path, []byte(`{ "text" : "привет" }`), headers)
|
||||
other := fixture.do(t, http.MethodPost, path, []byte(`{"text":"другое"}`), headers)
|
||||
|
||||
require.Equal(t, http.StatusCreated, first.status)
|
||||
require.Equal(t, http.StatusCreated, replay.status)
|
||||
require.Equal(t, http.StatusCreated, other.status)
|
||||
require.NotEmpty(t, first.header.Get(instanceIDHeader))
|
||||
require.Len(t, fingerprints, 3)
|
||||
require.Equal(t, fingerprints[0], fingerprints[1],
|
||||
"порядок ключей и пробелы в JSON не меняют отпечаток payload")
|
||||
require.NotEqual(t, fingerprints[0], fingerprints[2],
|
||||
"другой payload с тем же ключом — это конфликт, отпечатки обязаны различаться")
|
||||
}
|
||||
|
||||
func TestCreateMessageReplayConflictIsReportedAsConflict(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
fixture.messages.EXPECT().
|
||||
Send(mock.Anything, mock.Anything).
|
||||
Return(domain.Message{}, domain.ErrIdempotency).
|
||||
Once()
|
||||
|
||||
result := fixture.do(
|
||||
t,
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+uuid.NewString()+"/messages",
|
||||
[]byte(`{"text":"другой"}`),
|
||||
map[string]string{"Authorization": "Bearer opaque-token", "Idempotency-Key": "key-1"},
|
||||
)
|
||||
require.Equal(t, http.StatusConflict, result.status)
|
||||
|
||||
var body struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(result.body, &body))
|
||||
require.Equal(t, "conflict", body.Error.Code)
|
||||
}
|
||||
|
||||
func TestEveryResponseCarriesInstanceID(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
|
||||
tests := map[string]httpResult{
|
||||
"успешный ответ": fixture.do(t, http.MethodGet, "/health/live", nil, nil),
|
||||
"неизвестный маршрут": fixture.do(t, http.MethodGet, "/nope", nil, nil),
|
||||
"неподдерживаемый метод": fixture.do(t, http.MethodDelete, "/health/live", nil, nil),
|
||||
"ошибка валидации схемы": fixture.do(
|
||||
t,
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+uuid.NewString()+"/messages",
|
||||
[]byte(`{"text":"привет"}`),
|
||||
map[string]string{"Authorization": "Bearer opaque-token"},
|
||||
),
|
||||
}
|
||||
|
||||
for name, result := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
require.NotEmpty(t, result.header.Get(instanceIDHeader))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user