forked from mtusi2026/mtusi2026lab2
test(chat): add create chat rollback test
This commit is contained in:
@@ -77,6 +77,9 @@ func (s *ChatService) Create(
|
||||
ID: id,
|
||||
Title: title,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
err = q.AddChatMembers(ctx, db.AddChatMembersParams{
|
||||
ChatID: row.ID,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
//go:build contract
|
||||
|
||||
package studenttests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestCreateChatRollback(t *testing.T) {
|
||||
data, err := os.ReadFile("../secrets/test_database_url.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("read secrets/test_database_url: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
conn, err := pgx.Connect(ctx, strings.TrimSpace(string(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("connect to database: %v", err)
|
||||
}
|
||||
defer conn.Close(ctx)
|
||||
|
||||
creator := createUser(t)
|
||||
title := "rollback-" + uuid.NewString()
|
||||
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"title": title,
|
||||
"member_ids": []uuid.UUID{creator.ID, uuid.New()},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal body: %v", err)
|
||||
}
|
||||
|
||||
resp := doRequest(t, http.MethodPost, "/api/v1/chats", creator.Token, body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode < 400 || resp.StatusCode >= 500 {
|
||||
t.Fatalf("expected 4xx, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var n int
|
||||
err = conn.QueryRow(ctx, "SELECT count(*) FROM chats WHERE title = $1", title).Scan(&n)
|
||||
if err != nil {
|
||||
t.Fatalf("count chats: %v", err)
|
||||
}
|
||||
if n != 0 {
|
||||
t.Fatalf("expected no chat rows after failed creation, found %d", n)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user