Files
mtusi2026lab3/student-tests/helpers_test.go
T

211 lines
3.9 KiB
Go

package studenttests_test
import (
"bytes"
"encoding/json"
"flag"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
var baseURL = flag.String("base-url", "http://127.0.0.1:8080", "base URL of the running server")
var httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 200,
IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 200,
MaxConnsPerHost: 200,
},
}
type testUser struct {
dto.UserResponse
Token string
}
const testPassword = "correct-horse-battery"
func doRequest(t *testing.T, method, path, token string, body []byte) *http.Response {
t.Helper()
req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body))
if err != nil {
t.Fatalf("build request: %v", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("%s %s: request failed: %v", method, path, err)
}
return resp
}
func mustDecode(t *testing.T, resp *http.Response, dst any) {
t.Helper()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if err := json.Unmarshal(data, dst); err != nil {
t.Fatalf("decode body %q: %v", data, err)
}
}
func requireStatus(t *testing.T, resp *http.Response, expected int) {
t.Helper()
if resp.StatusCode != expected {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf(
"expected status %d, got %d, body: %s",
expected,
resp.StatusCode,
data,
)
}
if resp.Header.Get("X-Request-Id") == "" {
t.Errorf("missing X-Request-Id header")
}
}
func createUser(t *testing.T) testUser {
t.Helper()
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Test " + username,
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal user: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
requireStatus(t, resp, http.StatusCreated)
var u dto.UserResponse
mustDecode(t, resp, &u)
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/auth/sessions",
nil,
)
if err != nil {
t.Fatalf("build login request: %v", err)
}
req.SetBasicAuth(username, testPassword)
resp, err = httpClient.Do(req)
if err != nil {
t.Fatalf("login request failed: %v", err)
}
requireStatus(t, resp, http.StatusCreated)
var session dto.SessionResponse
mustDecode(t, resp, &session)
return testUser{UserResponse: u, Token: session.Token}
}
func createChat(
t *testing.T,
creator testUser,
memberIDs ...uuid.UUID,
) dto.ChatResponse {
t.Helper()
body, err := json.Marshal(map[string]any{
"title": "Test chat " + uuid.NewString()[:8],
"member_ids": memberIDs,
})
if err != nil {
t.Fatalf("marshal chat: %v", err)
}
resp := doRequest(
t,
http.MethodPost,
"/api/v1/chats",
creator.Token,
body,
)
requireStatus(t, resp, http.StatusCreated)
var c dto.ChatResponse
mustDecode(t, resp, &c)
return c
}
func sendMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
) *http.Response {
t.Helper()
resp, err := sendLoadMessage(actor, chatID, text)
if err != nil {
t.Fatalf("send message: %v", err)
}
return resp
}
func sendLoadMessage(
actor testUser,
chatID uuid.UUID,
text string,
) (*http.Response, error) {
body, err := json.Marshal(map[string]string{
"text": text,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
return httpClient.Do(req)
}