test: authenticate student tests with session tokens

This commit is contained in:
kk10
2026-10-05 13:42:00 +03:00
parent 385a8c0312
commit 79036b0f18
3 changed files with 45 additions and 26 deletions
+5 -6
View File
@@ -9,13 +9,11 @@ import (
"strconv" "strconv"
"testing" "testing"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto" "mtusi2026-messenger/internal/dto"
) )
func TestInvalidJSON(t *testing.T) { func TestInvalidJSON(t *testing.T) {
resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, []byte(`{"username": "broken",`)) resp := doRequest(t, http.MethodPost, "/api/v1/users", "", []byte(`{"username": "broken",`))
requireStatus(t, resp, http.StatusBadRequest) requireStatus(t, resp, http.StatusBadRequest)
var apiErr dto.ErrorResponse var apiErr dto.ErrorResponse
@@ -33,7 +31,7 @@ func TestForeignChat(t *testing.T) {
chat := createChat(t, user1, user1.ID, user2.ID) chat := createChat(t, user1, user1.ID, user2.ID)
resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.ID, nil) resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.Token, nil)
requireStatus(t, resp, http.StatusNotFound) requireStatus(t, resp, http.StatusNotFound)
resp = sendMessage(t, user3, chat.ID, "should not land") resp = sendMessage(t, user3, chat.ID, "should not land")
@@ -56,12 +54,13 @@ func TestDuplicateUsername(t *testing.T) {
body, err := json.Marshal(map[string]string{ body, err := json.Marshal(map[string]string{
"username": user.Username, "username": user.Username,
"display_name": "Someone else", "display_name": "Someone else",
"password": testPassword,
}) })
if err != nil { if err != nil {
t.Fatalf("marshal body: %v", err) t.Fatalf("marshal body: %v", err)
} }
resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, body) resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
requireStatus(t, resp, http.StatusConflict) requireStatus(t, resp, http.StatusConflict)
var apiErr dto.ErrorResponse var apiErr dto.ErrorResponse
@@ -99,7 +98,7 @@ func TestPagination(t *testing.T) {
path += "&cursor=" + url.QueryEscape(cursor) path += "&cursor=" + url.QueryEscape(cursor)
} }
resp := doRequest(t, http.MethodGet, path, user.ID, nil) resp := doRequest(t, http.MethodGet, path, user.Token, nil)
requireStatus(t, resp, http.StatusOK) requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse var page dto.MessagePageResponse
+39 -19
View File
@@ -28,7 +28,14 @@ var httpClient = &http.Client{
}, },
} }
func doRequest(t *testing.T, method, path string, actorID uuid.UUID, body []byte) *http.Response { 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() t.Helper()
req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body)) req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body))
@@ -40,8 +47,8 @@ func doRequest(t *testing.T, method, path string, actorID uuid.UUID, body []byte
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
} }
if actorID != uuid.Nil { if token != "" {
req.Header.Set("X-User-Id", actorID.String()) req.Header.Set("Authorization", "Bearer "+token)
} }
resp, err := httpClient.Do(req) resp, err := httpClient.Do(req)
@@ -86,7 +93,7 @@ func requireStatus(t *testing.T, resp *http.Response, expected int) {
} }
} }
func createUser(t *testing.T) dto.UserResponse { func createUser(t *testing.T) testUser {
t.Helper() t.Helper()
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12] username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
@@ -94,30 +101,43 @@ func createUser(t *testing.T) dto.UserResponse {
body, err := json.Marshal(map[string]string{ body, err := json.Marshal(map[string]string{
"username": username, "username": username,
"display_name": "Test " + username, "display_name": "Test " + username,
"password": testPassword,
}) })
if err != nil { if err != nil {
t.Fatalf("marshal user: %v", err) t.Fatalf("marshal user: %v", err)
} }
resp := doRequest( resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
t,
http.MethodPost,
"/api/v1/users",
uuid.Nil,
body,
)
requireStatus(t, resp, http.StatusCreated) requireStatus(t, resp, http.StatusCreated)
var u dto.UserResponse var u dto.UserResponse
mustDecode(t, resp, &u) mustDecode(t, resp, &u)
return 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( func createChat(
t *testing.T, t *testing.T,
creator dto.UserResponse, creator testUser,
memberIDs ...uuid.UUID, memberIDs ...uuid.UUID,
) dto.ChatResponse { ) dto.ChatResponse {
t.Helper() t.Helper()
@@ -134,7 +154,7 @@ func createChat(
t, t,
http.MethodPost, http.MethodPost,
"/api/v1/chats", "/api/v1/chats",
creator.ID, creator.Token,
body, body,
) )
@@ -148,7 +168,7 @@ func createChat(
func sendMessage( func sendMessage(
t *testing.T, t *testing.T,
actor dto.UserResponse, actor testUser,
chatID uuid.UUID, chatID uuid.UUID,
text string, text string,
) *http.Response { ) *http.Response {
@@ -165,13 +185,13 @@ func sendMessage(
t, t,
http.MethodPost, http.MethodPost,
fmt.Sprintf("/api/v1/chats/%v/messages", chatID.String()), fmt.Sprintf("/api/v1/chats/%v/messages", chatID.String()),
actor.ID, actor.Token,
body, body,
) )
} }
func sendLoadMessage( func sendLoadMessage(
actor dto.UserResponse, actor testUser,
chatID uuid.UUID, chatID uuid.UUID,
text string, text string,
) (*http.Response, error) { ) (*http.Response, error) {
@@ -192,7 +212,7 @@ func sendLoadMessage(
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-Id", actor.ID.String()) req.Header.Set("Authorization", "Bearer "+actor.Token)
return httpClient.Do(req) return httpClient.Do(req)
} }
+1 -1
View File
@@ -70,7 +70,7 @@ func TestConcurrentMessages(t *testing.T) {
seen := make(map[string]bool, total) seen := make(map[string]bool, total)
path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100" path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100"
resp := doRequest(t, http.MethodGet, path, user1.ID, nil) resp := doRequest(t, http.MethodGet, path, user1.Token, nil)
requireStatus(t, resp, http.StatusOK) requireStatus(t, resp, http.StatusOK)
var page dto.MessagePageResponse var page dto.MessagePageResponse