returned lab1
This commit is contained in:
@@ -0,0 +1,296 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
chathandler "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
type testAPI struct {
|
||||
server *httptest.Server
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type chatResponse struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type messagePageResponse struct {
|
||||
Items []messageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
func newTestAPI(t *testing.T) *testAPI {
|
||||
t.Helper()
|
||||
useCase := chatusecase.New(repository.NewMemory())
|
||||
server := httptest.NewServer(chathandler.NewChat(useCase).Router())
|
||||
t.Cleanup(server.Close)
|
||||
return &testAPI{server: server}
|
||||
}
|
||||
|
||||
func (a *testAPI) request(t *testing.T, client *http.Client, method, path, actorID, body string, wantStatus int, target any) {
|
||||
t.Helper()
|
||||
request, err := http.NewRequest(method, a.server.URL+path, bytes.NewBufferString(body))
|
||||
if err != nil {
|
||||
t.Fatalf("create request: %v", err)
|
||||
}
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actorID != "" {
|
||||
request.Header.Set("X-User-Id", actorID)
|
||||
}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("%s %s: %v", method, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
responseBody, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read response: %v", err)
|
||||
}
|
||||
if response.StatusCode != wantStatus {
|
||||
t.Fatalf("%s %s: status=%d, want=%d, body=%s", method, path, response.StatusCode, wantStatus, responseBody)
|
||||
}
|
||||
if response.Header.Get("X-Request-Id") == "" {
|
||||
t.Fatalf("%s %s: missing X-Request-Id", method, path)
|
||||
}
|
||||
if target != nil {
|
||||
if err := json.Unmarshal(responseBody, target); err != nil {
|
||||
t.Fatalf("decode response %q: %v", responseBody, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *testAPI) createUser(t *testing.T, username string) userResponse {
|
||||
t.Helper()
|
||||
var user userResponse
|
||||
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/users", "",
|
||||
fmt.Sprintf(`{"username":%q,"display_name":%q}`, username, username), http.StatusCreated, &user)
|
||||
return user
|
||||
}
|
||||
|
||||
func (a *testAPI) requestError(t *testing.T, method, path, actorID, body string, wantStatus int, wantCode string) {
|
||||
t.Helper()
|
||||
var response errorResponse
|
||||
a.request(t, http.DefaultClient, method, path, actorID, body, wantStatus, &response)
|
||||
if response.Error.Code != wantCode {
|
||||
t.Fatalf("%s %s: error code=%q, want=%q", method, path, response.Error.Code, wantCode)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *testAPI) createChat(t *testing.T, ownerID string, memberIDs []string) chatResponse {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(map[string]any{"title": "test chat", "member_ids": memberIDs})
|
||||
if err != nil {
|
||||
t.Fatalf("encode chat: %v", err)
|
||||
}
|
||||
var chat chatResponse
|
||||
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/chats", ownerID, string(body), http.StatusCreated, &chat)
|
||||
return chat
|
||||
}
|
||||
|
||||
func (a *testAPI) createMessage(t *testing.T, client *http.Client, actorID, chatID, text string) messageResponse {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(map[string]string{"text": text})
|
||||
if err != nil {
|
||||
t.Fatalf("encode message: %v", err)
|
||||
}
|
||||
var message messageResponse
|
||||
a.request(t, client, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID, string(body), http.StatusCreated, &message)
|
||||
return message
|
||||
}
|
||||
|
||||
func TestRejectsMalformedJSON(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.requestError(t, http.MethodPost, "/api/v1/users", "",
|
||||
`{"username":`, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
|
||||
func TestHidesForeignChat(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
owner := api.createUser(t, "owner_user")
|
||||
outsider := api.createUser(t, "outsider_user")
|
||||
chat := api.createChat(t, owner.ID, []string{owner.ID})
|
||||
api.requestError(t, http.MethodGet, "/api/v1/chats/"+chat.ID, outsider.ID,
|
||||
"", http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func TestRejectsEmptyMessage(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
user := api.createUser(t, "empty_message_user")
|
||||
chat := api.createChat(t, user.ID, []string{user.ID})
|
||||
api.requestError(t, http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", user.ID,
|
||||
`{"text":" "}`, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
|
||||
func TestRejectsDuplicateUsername(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.createUser(t, "duplicate_user")
|
||||
api.requestError(t, http.MethodPost, "/api/v1/users", "",
|
||||
`{"username":"duplicate_user","display_name":"Duplicate"}`, http.StatusConflict, "conflict")
|
||||
}
|
||||
|
||||
func TestPaginatesMessagesAcrossMultiplePages(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
user := api.createUser(t, "pagination_user")
|
||||
chat := api.createChat(t, user.ID, []string{user.ID})
|
||||
for index := 0; index < 7; index++ {
|
||||
api.createMessage(t, http.DefaultClient, user.ID, chat.ID, fmt.Sprintf("message-%d", index))
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{})
|
||||
cursor := ""
|
||||
pageSizes := make([]int, 0, 4)
|
||||
for {
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages?limit=2"
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
var page messagePageResponse
|
||||
api.request(t, http.DefaultClient, http.MethodGet, path, user.ID, "", http.StatusOK, &page)
|
||||
pageSizes = append(pageSizes, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
t.Fatalf("message %s appeared on multiple pages", message.ID)
|
||||
}
|
||||
seen[message.ID] = struct{}{}
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
if len(seen) != 7 {
|
||||
t.Fatalf("received %d unique messages, want 7", len(seen))
|
||||
}
|
||||
wantPageSizes := []int{2, 2, 2, 1}
|
||||
if fmt.Sprint(pageSizes) != fmt.Sprint(wantPageSizes) {
|
||||
t.Fatalf("page sizes=%v, want=%v", pageSizes, wantPageSizes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessagesAreUnique(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
|
||||
users := make([]userResponse, 10)
|
||||
memberIDs := make([]string, 10)
|
||||
for index := range users {
|
||||
users[index] = api.createUser(t, fmt.Sprintf("parallel_user_%02d", index))
|
||||
memberIDs[index] = users[index].ID
|
||||
}
|
||||
chat := api.createChat(t, users[0].ID, memberIDs)
|
||||
|
||||
start := make(chan struct{})
|
||||
errors := make(chan error, 10)
|
||||
var waitGroup sync.WaitGroup
|
||||
|
||||
for clientIndex := 0; clientIndex < 10; clientIndex++ {
|
||||
waitGroup.Add(1)
|
||||
go func(clientIndex int) {
|
||||
defer waitGroup.Done()
|
||||
client := &http.Client{Transport: &http.Transport{}, Timeout: 5 * time.Second}
|
||||
defer client.CloseIdleConnections()
|
||||
<-start
|
||||
for messageIndex := 0; messageIndex < 10; messageIndex++ {
|
||||
body, err := json.Marshal(map[string]string{
|
||||
"text": fmt.Sprintf("client-%02d-message-%02d", clientIndex, messageIndex),
|
||||
})
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodPost,
|
||||
api.server.URL+"/api/v1/chats/"+chat.ID+"/messages", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", users[clientIndex].ID)
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
_, readErr := io.Copy(io.Discard, response.Body)
|
||||
closeErr := response.Body.Close()
|
||||
if readErr != nil {
|
||||
errors <- readErr
|
||||
return
|
||||
}
|
||||
if closeErr != nil {
|
||||
errors <- closeErr
|
||||
return
|
||||
}
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
errors <- fmt.Errorf("client %d message %d: status=%d", clientIndex, messageIndex, response.StatusCode)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(clientIndex)
|
||||
}
|
||||
close(start)
|
||||
waitGroup.Wait()
|
||||
close(errors)
|
||||
for err := range errors {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
seenIDs := make(map[string]struct{}, 10*10)
|
||||
seenTexts := make(map[string]struct{}, 10*10)
|
||||
cursor := ""
|
||||
for {
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages?limit=17"
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
var page messagePageResponse
|
||||
api.request(t, http.DefaultClient, http.MethodGet, path, users[0].ID, "", http.StatusOK, &page)
|
||||
for _, message := range page.Items {
|
||||
if _, duplicate := seenIDs[message.ID]; duplicate {
|
||||
t.Fatalf("duplicate message ID %s", message.ID)
|
||||
}
|
||||
if _, duplicate := seenTexts[message.Text]; duplicate {
|
||||
t.Fatalf("duplicate message text %q", message.Text)
|
||||
}
|
||||
seenIDs[message.ID] = struct{}{}
|
||||
seenTexts[message.Text] = struct{}{}
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
if len(seenIDs) != 10*10 || len(seenTexts) != 10*10 {
|
||||
t.Fatalf("received %d unique IDs and %d unique texts, want %d of each",
|
||||
len(seenIDs), len(seenTexts), 10*10)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user