286 lines
8.5 KiB
Go
286 lines
8.5 KiB
Go
package tests
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type apiClient struct {
|
|
baseURL string
|
|
prefix string
|
|
tokens map[string]string
|
|
}
|
|
|
|
type apiResponse struct {
|
|
status int
|
|
requestID string
|
|
instanceID string
|
|
body []byte
|
|
}
|
|
|
|
func newAPI(t *testing.T) *apiClient {
|
|
t.Helper()
|
|
base := os.Getenv("TEST_BASE_URL")
|
|
if base == "" {
|
|
base = "http://localhost:18086"
|
|
}
|
|
return &apiClient{baseURL: strings.TrimRight(base, "/"), prefix: uuid.NewString()[:8] + "_", tokens: map[string]string{}}
|
|
}
|
|
func (api *apiClient) request(t *testing.T, method, path, userID, body string) apiResponse {
|
|
return api.requestKey(t, method, path, userID, body, uuid.NewString())
|
|
}
|
|
func (api *apiClient) requestKey(t *testing.T, method, path, userID, body, key string) apiResponse {
|
|
t.Helper()
|
|
response, err := api.send(method, path, userID, body, key)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return response
|
|
}
|
|
func (api *apiClient) send(method, path, userID, body, key string) (apiResponse, error) {
|
|
if path == "/api/v1/users" {
|
|
var fields map[string]any
|
|
if json.Unmarshal([]byte(body), &fields) == nil {
|
|
if name, ok := fields["username"].(string); ok {
|
|
fields["username"] = api.prefix + name
|
|
data, err := json.Marshal(fields)
|
|
if err != nil {
|
|
return apiResponse{}, err
|
|
}
|
|
body = string(data)
|
|
}
|
|
}
|
|
}
|
|
req, err := http.NewRequest(method, api.baseURL+path, strings.NewReader(body))
|
|
if err != nil {
|
|
return apiResponse{}, err
|
|
}
|
|
if body != "" {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if userID != "" {
|
|
req.Header.Set("Authorization", "Bearer "+api.tokens[userID])
|
|
}
|
|
if key != "" {
|
|
req.Header.Set("Idempotency-Key", key)
|
|
}
|
|
response, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
|
|
if err != nil {
|
|
return apiResponse{}, fmt.Errorf("running lab5 stand required: %w", err)
|
|
}
|
|
defer response.Body.Close()
|
|
data, err := io.ReadAll(response.Body)
|
|
if err != nil {
|
|
return apiResponse{}, err
|
|
}
|
|
requestID, instanceID := response.Header.Get("X-Request-Id"), response.Header.Get("X-Instance-Id")
|
|
if requestID == "" || instanceID == "" {
|
|
return apiResponse{}, fmt.Errorf("%s %s: HTTP %d missing response identity", method, path, response.StatusCode)
|
|
}
|
|
return apiResponse{status: response.StatusCode, requestID: requestID, instanceID: instanceID, body: data}, nil
|
|
}
|
|
|
|
func jsonString(t *testing.T, value any) string {
|
|
t.Helper()
|
|
data, err := json.Marshal(value)
|
|
if err != nil {
|
|
t.Fatalf("encode request: %v", err)
|
|
}
|
|
return string(data)
|
|
}
|
|
|
|
func decodeOK(t *testing.T, resp apiResponse, wantStatus int, target any) {
|
|
t.Helper()
|
|
if resp.status != wantStatus {
|
|
t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body)
|
|
}
|
|
if err := json.Unmarshal(resp.body, target); err != nil {
|
|
t.Fatalf("decode response %s: %v", resp.body, err)
|
|
}
|
|
}
|
|
|
|
func assertError(t *testing.T, resp apiResponse, wantStatus int, wantCode string) {
|
|
t.Helper()
|
|
if resp.status != wantStatus {
|
|
t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body)
|
|
}
|
|
var body struct {
|
|
Error struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
RequestID string `json:"request_id"`
|
|
} `json:"error"`
|
|
}
|
|
if err := json.Unmarshal(resp.body, &body); err != nil {
|
|
t.Fatalf("decode error response %s: %v", resp.body, err)
|
|
}
|
|
if body.Error.Code != wantCode || body.Error.Message == "" || body.Error.RequestID != resp.requestID {
|
|
t.Fatalf("invalid error response: header request ID %q, body %s", resp.requestID, resp.body)
|
|
}
|
|
}
|
|
|
|
func (api *apiClient) createUser(t *testing.T, username string) string {
|
|
t.Helper()
|
|
resp := api.request(t, http.MethodPost, "/api/v1/users", "", jsonString(t, map[string]string{
|
|
"username": username, "display_name": username, "password": "Synthetic-password-123",
|
|
}))
|
|
var user struct {
|
|
ID string `json:"id"`
|
|
}
|
|
decodeOK(t, resp, http.StatusCreated, &user)
|
|
if user.ID == "" {
|
|
t.Fatal("created user has no ID")
|
|
}
|
|
req, _ := http.NewRequest(http.MethodPost, api.baseURL+"/api/v1/auth/sessions", nil)
|
|
req.SetBasicAuth(api.prefix+username, "Synthetic-password-123")
|
|
sessionResp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer sessionResp.Body.Close()
|
|
var session struct {
|
|
Token string `json:"token"`
|
|
}
|
|
if err = json.NewDecoder(sessionResp.Body).Decode(&session); err != nil || sessionResp.StatusCode != 201 || session.Token == "" {
|
|
t.Fatalf("login failed: status %d, error %v", sessionResp.StatusCode, err)
|
|
}
|
|
api.tokens[user.ID] = session.Token
|
|
return user.ID
|
|
}
|
|
|
|
func (api *apiClient) createChat(t *testing.T, creatorID string, memberIDs ...string) string {
|
|
t.Helper()
|
|
resp := api.request(t, http.MethodPost, "/api/v1/chats", creatorID, jsonString(t, map[string]any{
|
|
"title": "Test chat", "member_ids": memberIDs,
|
|
}))
|
|
var chat struct {
|
|
ID string `json:"id"`
|
|
}
|
|
decodeOK(t, resp, http.StatusCreated, &chat)
|
|
if chat.ID == "" {
|
|
t.Fatal("created chat has no ID")
|
|
}
|
|
return chat.ID
|
|
}
|
|
|
|
func TestInvalidJSON(t *testing.T) {
|
|
api := newAPI(t)
|
|
for _, tc := range []struct {
|
|
name string
|
|
body string
|
|
}{
|
|
{name: "malformed", body: `{"username":`},
|
|
{name: "wrong type", body: `{"username":42,"display_name":"Alice"}`},
|
|
{name: "unknown field", body: `{"username":"alice","display_name":"Alice","admin":true}`},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
resp := api.request(t, http.MethodPost, "/api/v1/users", "", tc.body)
|
|
assertError(t, resp, http.StatusBadRequest, "invalid_request")
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestForeignChatIsHidden(t *testing.T) {
|
|
api := newAPI(t)
|
|
alice := api.createUser(t, "alice")
|
|
bob := api.createUser(t, "bob")
|
|
eve := api.createUser(t, "eve")
|
|
chatID := api.createChat(t, alice, alice, bob)
|
|
|
|
for _, tc := range []struct {
|
|
method string
|
|
path string
|
|
body string
|
|
}{
|
|
{method: http.MethodGet, path: "/api/v1/chats/" + chatID},
|
|
{method: http.MethodGet, path: "/api/v1/chats/" + chatID + "/messages"},
|
|
{method: http.MethodPost, path: "/api/v1/chats/" + chatID + "/messages", body: `{"text":"secret"}`},
|
|
} {
|
|
resp := api.request(t, tc.method, tc.path, eve, tc.body)
|
|
assertError(t, resp, http.StatusNotFound, "not_found")
|
|
}
|
|
}
|
|
|
|
func TestEmptyMessage(t *testing.T) {
|
|
api := newAPI(t)
|
|
alice := api.createUser(t, "alice")
|
|
chatID := api.createChat(t, alice, alice)
|
|
path := "/api/v1/chats/" + chatID + "/messages"
|
|
for _, body := range []string{`{"text":""}`, `{"text":" \t\n "}`} {
|
|
resp := api.request(t, http.MethodPost, path, alice, body)
|
|
assertError(t, resp, http.StatusBadRequest, "invalid_request")
|
|
}
|
|
}
|
|
|
|
func TestDuplicateUsername(t *testing.T) {
|
|
api := newAPI(t)
|
|
api.createUser(t, "alice")
|
|
resp := api.request(t, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Another Alice","password":"Synthetic-password-123"}`)
|
|
assertError(t, resp, http.StatusConflict, "conflict")
|
|
}
|
|
|
|
func TestMessagePagination(t *testing.T) {
|
|
api := newAPI(t)
|
|
alice := api.createUser(t, "alice")
|
|
chatID := api.createChat(t, alice, alice)
|
|
wantIDs := make(map[string]bool)
|
|
for i := range 5 {
|
|
resp := api.request(t, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", alice,
|
|
jsonString(t, map[string]string{"text": fmt.Sprintf("message %d", i)}))
|
|
var message struct {
|
|
ID string `json:"id"`
|
|
}
|
|
decodeOK(t, resp, http.StatusCreated, &message)
|
|
if message.ID == "" || wantIDs[message.ID] {
|
|
t.Fatalf("invalid or duplicate created message ID %q", message.ID)
|
|
}
|
|
wantIDs[message.ID] = true
|
|
}
|
|
|
|
seen := make(map[string]bool)
|
|
cursor := ""
|
|
pages := 0
|
|
for {
|
|
path := "/api/v1/chats/" + chatID + "/messages?limit=2"
|
|
if cursor != "" {
|
|
path += "&cursor=" + url.QueryEscape(cursor)
|
|
}
|
|
resp := api.request(t, http.MethodGet, path, alice, "")
|
|
var page struct {
|
|
Items []struct {
|
|
ID string `json:"id"`
|
|
} `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
decodeOK(t, resp, http.StatusOK, &page)
|
|
pages++
|
|
if pages > 3 || len(page.Items) == 0 || len(page.Items) > 2 {
|
|
t.Fatalf("unexpected page %d: %s", pages, resp.body)
|
|
}
|
|
for _, message := range page.Items {
|
|
if !wantIDs[message.ID] || seen[message.ID] {
|
|
t.Fatalf("unexpected or repeated message ID %q on page %d", message.ID, pages)
|
|
}
|
|
seen[message.ID] = true
|
|
}
|
|
if page.NextCursor == nil {
|
|
break
|
|
}
|
|
if *page.NextCursor == "" || *page.NextCursor == cursor {
|
|
t.Fatalf("invalid next cursor on page %d: %s", pages, resp.body)
|
|
}
|
|
cursor = *page.NextCursor
|
|
}
|
|
if pages != 3 || len(seen) != len(wantIDs) {
|
|
t.Fatalf("got %d pages and %d unique messages, want 3 pages and %d messages", pages, len(seen), len(wantIDs))
|
|
}
|
|
}
|