forked from mtusi2026/mtusi2026lab3
На 5
This commit is contained in:
+76
-30
@@ -3,57 +3,89 @@ package tests
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
controller "gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
|
||||
inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"time"
|
||||
)
|
||||
|
||||
type apiClient struct {
|
||||
handler http.Handler
|
||||
baseURL string
|
||||
prefix string
|
||||
tokens map[string]string
|
||||
}
|
||||
|
||||
type apiResponse struct {
|
||||
status int
|
||||
requestID string
|
||||
body []byte
|
||||
status int
|
||||
requestID string
|
||||
instanceID string
|
||||
body []byte
|
||||
}
|
||||
|
||||
func newAPI(t *testing.T) *apiClient {
|
||||
t.Helper()
|
||||
router := controller.NewRouter()
|
||||
users := inmemory2.NewUserCache()
|
||||
chats := inmemory2.NewChatCache(users)
|
||||
messages := inmemory2.NewMessageCache(chats)
|
||||
base := controller.NewBaseHandler(router)
|
||||
controller.NewAuthHandler(base, users).RegisterRoutes()
|
||||
controller.NewChatHandler(base, users, chats, messages).RegisterRoutes()
|
||||
|
||||
return &apiClient{handler: router}
|
||||
base := os.Getenv("TEST_BASE_URL")
|
||||
if base == "" {
|
||||
base = "http://localhost:18080"
|
||||
}
|
||||
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()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
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("X-User-Id", userID)
|
||||
req.Header.Set("Authorization", "Bearer "+api.tokens[userID])
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
api.handler.ServeHTTP(recorder, req)
|
||||
resp := recorder.Result()
|
||||
defer resp.Body.Close()
|
||||
requestID := resp.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
t.Fatalf("%s %s: missing X-Request-Id", method, path)
|
||||
if key != "" {
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
return apiResponse{status: resp.StatusCode, requestID: requestID, body: recorder.Body.Bytes()}
|
||||
response, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
|
||||
if err != nil {
|
||||
return apiResponse{}, fmt.Errorf("running lab3 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 {
|
||||
@@ -98,7 +130,7 @@ func assertError(t *testing.T, resp apiResponse, wantStatus int, wantCode string
|
||||
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,
|
||||
"username": username, "display_name": username, "password": "Synthetic-password-123",
|
||||
}))
|
||||
var user struct {
|
||||
ID string `json:"id"`
|
||||
@@ -107,6 +139,20 @@ func (api *apiClient) createUser(t *testing.T, username string) string {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -177,7 +223,7 @@ func TestEmptyMessage(t *testing.T) {
|
||||
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"}`)
|
||||
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")
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ package tests
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -31,7 +31,8 @@ func postMessage(client *http.Client, endpoint, userID, text string) (createdMes
|
||||
return createdMessage{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
req.Header.Set("Authorization", "Bearer "+userID)
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return createdMessage{}, err
|
||||
@@ -65,9 +66,7 @@ func TestConcurrentMessages(t *testing.T) {
|
||||
users[i] = api.createUser(t, fmt.Sprintf("user%02d", i))
|
||||
}
|
||||
chatID := api.createChat(t, users[0], users...)
|
||||
server := httptest.NewServer(api.handler)
|
||||
t.Cleanup(server.Close)
|
||||
endpoint := server.URL + "/api/v1/chats/" + chatID + "/messages"
|
||||
endpoint := api.baseURL + "/api/v1/chats/" + chatID + "/messages"
|
||||
|
||||
type result struct {
|
||||
message createdMessage
|
||||
@@ -90,7 +89,7 @@ func TestConcurrentMessages(t *testing.T) {
|
||||
<-start
|
||||
for j := range messagesPerClient {
|
||||
text := fmt.Sprintf("client-%02d-message-%02d", workerID, j)
|
||||
message, err := postMessage(client, endpoint, userID, text)
|
||||
message, err := postMessage(client, endpoint, api.tokens[userID], text)
|
||||
results <- result{message: message, wantSenderID: userID, wantText: text, err: err}
|
||||
}
|
||||
}(i, userID)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIdempotencyContract(t *testing.T) {
|
||||
api := newAPI(t)
|
||||
alice := api.createUser(t, "alice")
|
||||
bob := api.createUser(t, "bob")
|
||||
eve := api.createUser(t, "eve")
|
||||
chat := api.createChat(t, alice, alice, bob)
|
||||
other := api.createChat(t, alice, alice)
|
||||
path := "/api/v1/chats/" + chat + "/messages"
|
||||
for _, key := range []string{"", "bad key", "кириллица", string(make([]byte, 129))} {
|
||||
// NUL cannot be sent by net/http: use an overlength ASCII key instead.
|
||||
if len(key) == 129 {
|
||||
key = fmt.Sprintf("%0129d", 1)
|
||||
}
|
||||
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key), 400, "invalid_request")
|
||||
}
|
||||
key := uuid.NewString()
|
||||
first := api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key)
|
||||
var want map[string]any
|
||||
decodeOK(t, first, 201, &want)
|
||||
var got map[string]any
|
||||
decodeOK(t, api.requestKey(t, "POST", path, alice, `{ "text" : "hello" }`, key), 201, &got)
|
||||
if jsonString(t, want) != jsonString(t, got) {
|
||||
t.Fatal("replay changed message")
|
||||
}
|
||||
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"changed"}`, key), 409, "conflict")
|
||||
assertError(t, api.requestKey(t, "POST", path, eve, `{"text":"hello"}`, key), 404, "not_found")
|
||||
for _, tc := range []struct{ user, path string }{{bob, path}, {alice, "/api/v1/chats/" + other + "/messages"}} {
|
||||
var msg map[string]any
|
||||
decodeOK(t, api.requestKey(t, "POST", tc.path, tc.user, `{"text":"hello"}`, key), 201, &msg)
|
||||
if msg["id"] == want["id"] {
|
||||
t.Fatal("scope not isolated")
|
||||
}
|
||||
}
|
||||
resp := api.request(t, http.MethodDelete, "/api/v1/auth/sessions/current", alice, "")
|
||||
if resp.status != 204 {
|
||||
t.Fatal(resp.status)
|
||||
}
|
||||
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key), 401, "unauthorized")
|
||||
}
|
||||
func TestConcurrentIdempotencyAcrossReplicas(t *testing.T) {
|
||||
api := newAPI(t)
|
||||
user := api.createUser(t, "alice")
|
||||
chat := api.createChat(t, user, user)
|
||||
path := "/api/v1/chats/" + chat + "/messages"
|
||||
key := uuid.NewString()
|
||||
const count = 32
|
||||
type result struct {
|
||||
response apiResponse
|
||||
err error
|
||||
}
|
||||
responses := make(chan result, count)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for range count {
|
||||
wg.Go(func() {
|
||||
<-start
|
||||
response, err := api.send("POST", path, user, `{"text":"one logical message"}`, key)
|
||||
responses <- result{response: response, err: err}
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(responses)
|
||||
instances := map[string]bool{}
|
||||
var id string
|
||||
for result := range responses {
|
||||
if result.err != nil {
|
||||
t.Fatal(result.err)
|
||||
}
|
||||
resp := result.response
|
||||
var msg struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
decodeOK(t, resp, 201, &msg)
|
||||
if id != "" && id != msg.ID {
|
||||
t.Fatal("duplicate side effect")
|
||||
}
|
||||
id = msg.ID
|
||||
instances[resp.instanceID] = true
|
||||
}
|
||||
if len(instances) < 2 {
|
||||
t.Fatalf("need at least 2 real API replicas, observed %d", len(instances))
|
||||
}
|
||||
var page struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"items"`
|
||||
}
|
||||
decodeOK(t, api.request(t, "GET", path, user, ""), 200, &page)
|
||||
if len(page.Items) != 1 || page.Items[0].ID != id {
|
||||
t.Fatalf("history contains %d messages", len(page.Items))
|
||||
}
|
||||
t.Logf("%d requests across %d replicas created exactly one message", count, len(instances))
|
||||
}
|
||||
Reference in New Issue
Block a user