From 6a04c7ae8953eff663ae4d49aff4e8cdb8da9bbf Mon Sep 17 00:00:00 2001 From: Tim Wundenberg Date: Tue, 13 May 2025 12:37:11 +0200 Subject: [PATCH] feat(treasurechest): #64 fix tests --- db/auth.go | 7 +++ main_test.go | 55 +++++++++-------- migration/003_treasure_chest.up.sql | 1 - service/treasure_chest.go | 9 ++- template/treasurechest/treasure_chest.templ | 68 ++++++++++----------- 5 files changed, 78 insertions(+), 62 deletions(-) diff --git a/db/auth.go b/db/auth.go index 0a36c20..ab2106d 100644 --- a/db/auth.go +++ b/db/auth.go @@ -163,6 +163,13 @@ func (db AuthSqlite) DeleteUser(userId uuid.UUID) error { return types.ErrInternal } + _, err = tx.Exec("DELETE FROM treasure_chest WHERE user_id = ?", userId) + if err != nil { + _ = tx.Rollback() + log.Error("Could not delete user: %v", err) + return types.ErrInternal + } + err = tx.Commit() if err != nil { log.Error("Could not commit transaction: %v", err) diff --git a/main_test.go b/main_test.go index 1e77cae..3dcbb38 100644 --- a/main_test.go +++ b/main_test.go @@ -881,35 +881,39 @@ func TestIntegrationAuth(t *testing.T) { t.Parallel() db, basePath, ctx := setupIntegrationTest(t) - userId := uuid.New() - pass := service.GetHashPassword("password", []byte("salt")) - _, err := db.Exec(` - INSERT INTO user (user_id, email, email_verified, is_admin, password, salt, created_at) - VALUES (?, "mail@mail.de", FALSE, FALSE, ?, ?, datetime())`, userId, pass, []byte("salt")) + userId, csrfToken, sessionId := createValidUserSession(t, db, ctx, basePath, "") - sessionId := "session-id" - assert.Nil(t, err) - _, err = db.Exec(` - INSERT INTO session (session_id, user_id, created_at, expires_at) - VALUES (?, ?, datetime(), datetime("now", "+1 day"))`, sessionId, userId) - assert.Nil(t, err) - - req, err := http.NewRequestWithContext(ctx, "GET", basePath+"/auth/delete-account", nil) + formData := url.Values{ + "name": {"Name"}, + "csrf-token": {csrfToken}, + } + req, err := http.NewRequestWithContext(ctx, "POST", basePath+"/account/new", strings.NewReader(formData.Encode())) assert.Nil(t, err) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Cookie", "id="+sessionId) + req.Header.Set("HX-Request", "true") resp, err := httpClient.Do(req) assert.Nil(t, err) + assert.Equal(t, http.StatusOK, resp.StatusCode) - html, err := html.Parse(resp.Body) + formData = url.Values{ + "name": {"Name"}, + "csrf-token": {csrfToken}, + } + req, err = http.NewRequestWithContext(ctx, "POST", basePath+"/treasurechest/new", strings.NewReader(formData.Encode())) assert.Nil(t, err) - csrfToken := findCsrfToken(html) - assert.NotEqual(t, "", csrfToken) - formData := url.Values{ + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Cookie", "id="+sessionId) + req.Header.Set("HX-Request", "true") + resp, err = httpClient.Do(req) + assert.Nil(t, err) + assert.Equal(t, http.StatusOK, resp.StatusCode) + + formData = url.Values{ "password": {"password"}, "csrf-token": {csrfToken}, } - req, err = http.NewRequestWithContext(ctx, "POST", basePath+"/api/auth/delete-account", strings.NewReader(formData.Encode())) assert.Nil(t, err) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") @@ -933,6 +937,9 @@ func TestIntegrationAuth(t *testing.T) { err = db.QueryRow("SELECT COUNT(*) FROM account WHERE user_id = ?", userId).Scan(&rows) assert.Nil(t, err) assert.Equal(t, 0, rows) + err = db.QueryRow("SELECT COUNT(*) FROM treasure_chest WHERE user_id = ?", userId).Scan(&rows) + assert.Nil(t, err) + assert.Equal(t, 0, rows) }) }) @@ -1669,7 +1676,7 @@ func TestIntegrationAccount(t *testing.T) { db, basePath, ctx := setupIntegrationTest(t) - csrfToken, sessionId := createValidUserSession(t, db, ctx, basePath, "") + _, csrfToken, sessionId := createValidUserSession(t, db, ctx, basePath, "") // Insert expectedName := "My great Account" @@ -1738,8 +1745,8 @@ func TestIntegrationAccount(t *testing.T) { db, basePath, ctx := setupIntegrationTest(t) - csrfToken1, sessionId1 := createValidUserSession(t, db, ctx, basePath, "1") - _, sessionId2 := createValidUserSession(t, db, ctx, basePath, "2") + _, csrfToken1, sessionId1 := createValidUserSession(t, db, ctx, basePath, "1") + _, _, sessionId2 := createValidUserSession(t, db, ctx, basePath, "2") expectedName1 := "Account 1" @@ -1767,7 +1774,7 @@ func TestIntegrationAccount(t *testing.T) { t.Parallel() db, basePath, ctx := setupIntegrationTest(t) - csrfToken, sessionId := createValidUserSession(t, db, ctx, basePath, "") + _, csrfToken, sessionId := createValidUserSession(t, db, ctx, basePath, "") data := map[string]int{ "<": 400, @@ -1802,7 +1809,7 @@ func TestIntegrationAccount(t *testing.T) { }) } -func createValidUserSession(t *testing.T, db *sqlx.DB, ctx context.Context, basePath string, add string) (string, string) { +func createValidUserSession(t *testing.T, db *sqlx.DB, ctx context.Context, basePath string, add string) (uuid.UUID, string, string) { userId := uuid.New() sessionId := "session-id" + add pass := service.GetHashPassword("password", []byte("salt")) @@ -1823,7 +1830,7 @@ func createValidUserSession(t *testing.T, db *sqlx.DB, ctx context.Context, base VALUES (?, ?, ?, ?, datetime(), datetime("now", "+1 day"))`, csrfToken, userId, sessionId, types.TokenTypeCsrf) assert.Nil(t, err) - return csrfToken, sessionId + return userId, csrfToken, sessionId } func createAnonymousSession(t *testing.T, ctx context.Context, basePath string) (string, string) { diff --git a/migration/003_treasure_chest.up.sql b/migration/003_treasure_chest.up.sql index 718f80e..b836d9a 100644 --- a/migration/003_treasure_chest.up.sql +++ b/migration/003_treasure_chest.up.sql @@ -5,7 +5,6 @@ CREATE TABLE treasure_chest ( user_id TEXT NOT NULL, name TEXT NOT NULL, - account_id TEXT NOT NULL, current_balance int64 NOT NULL, diff --git a/service/treasure_chest.go b/service/treasure_chest.go index bdba171..e75e4f2 100644 --- a/service/treasure_chest.go +++ b/service/treasure_chest.go @@ -72,7 +72,7 @@ func (s TreasureChestImpl) Add(user *types.User, parentId, name string) (*types. return nil, err } if parent.ParentId != uuid.Nil { - return nil, fmt.Errorf("Only a depth of 1 allowed: %w", ErrBadRequest) + return nil, fmt.Errorf("only a depth of 1 allowed: %w", ErrBadRequest) } parentUuid = parent.Id } @@ -135,12 +135,15 @@ func (s TreasureChestImpl) Update(user *types.User, idStr, parentId, name string return nil, err } if parent.ParentId != uuid.Nil { - return nil, fmt.Errorf("Only a depth of 1 allowed: %w", ErrBadRequest) + return nil, fmt.Errorf("only a depth of 1 allowed: %w", ErrBadRequest) } children, err := s.db.GetAllByParentId(user.Id, treasureChest.Id) + if err != nil { + return nil, err + } if len(children) > 0 { - return nil, fmt.Errorf("Only a depth of 1 allowed: %w", ErrBadRequest) + return nil, fmt.Errorf("only a depth of 1 allowed: %w", ErrBadRequest) } parentUuid = parent.Id diff --git a/template/treasurechest/treasure_chest.templ b/template/treasurechest/treasure_chest.templ index 16c0d89..9ca6762 100644 --- a/template/treasurechest/treasure_chest.templ +++ b/template/treasurechest/treasure_chest.templ @@ -7,40 +7,6 @@ import "spend-sparrow/types" import "github.com/google/uuid" -func sortTree(nodes []*types.TreasureChest) []*types.TreasureChest { - - var ( - roots []*types.TreasureChest - result []*types.TreasureChest - ) - children := make(map[uuid.UUID][]*types.TreasureChest) - - for _, node := range nodes { - if node.ParentId == uuid.Nil { - roots = append(roots, node) - } else { - children[node.ParentId] = append(children[node.ParentId], node) - } - } - - for _, root := range roots { - result = append(result, root) - result = append(result, children[root.Id]...) - } - - return result -} - -func compareStrings(a, b string) int { - if a < b { - return -1 - } - if a > b { - return 1 - } - return 0 -} - templ TreasureChest(treasureChests []*types.TreasureChest) {