Files
mtusi2026lab5/src/backend/tests/integration_test.go
T

74 lines
2.5 KiB
Go

package tests
import (
"bytes"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/google/uuid"
)
func TestMessengerWorkflow(t *testing.T) {
router := newTestFixture(t).router
call := func(method, path, body, auth string, expected int) map[string]any {
t.Helper()
request := httptest.NewRequest(method, path, bytes.NewBufferString(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
request.Header.Set("Idempotency-Key", uuid.NewString())
}
if auth != "" {
request.Header.Set("Authorization", auth)
}
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != expected {
t.Fatalf("%s %s: status %d, want %d: %s", method, path, response.Code, expected, response.Body.String())
}
if response.Header().Get("X-Request-Id") == "" {
t.Fatalf("%s %s: missing request ID", method, path)
}
if response.Code == http.StatusNoContent {
return nil
}
var result map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
user := call("POST", "/api/v1/users", `{"username":"alice","display_name":"Алиса","password":"lab2-test-password"}`, "", 201)
userID := user["id"].(string)
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:lab2-test-password"))
session := call("POST", "/api/v1/auth/sessions", "", basic, 201)
bearer := "Bearer " + session["token"].(string)
call("GET", "/api/v1/users/me", "", bearer, 200)
chat := call("POST", "/api/v1/chats", `{"title":"Тестовый чат","member_ids":["`+userID+`"]}`, bearer, 201)
chatID := chat["id"].(string)
path := "/api/v1/chats/" + chatID + "/messages"
for i := 0; i < 3; i++ {
call("POST", path, `{"text":"message"}`, bearer, 201)
}
page1 := call("GET", path+"?limit=2", "", bearer, 200)
first := page1["items"].([]any)
if len(first) != 2 || page1["next_cursor"] == nil {
t.Fatalf("unexpected first page: %v", page1)
}
page2 := call("GET", path+"?limit=2&cursor="+url.QueryEscape(page1["next_cursor"].(string)), "", bearer, 200)
second := page2["items"].([]any)
if len(second) != 1 || page2["next_cursor"] != nil || first[0].(map[string]any)["id"] == second[0].(map[string]any)["id"] {
t.Fatalf("unexpected second page: %v", page2)
}
call("DELETE", "/api/v1/auth/sessions/current", "", bearer, 204)
call("GET", "/api/v1/users/me", "", bearer, 401)
}