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")
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user