feat(treasurechest): #64 fix tests
All checks were successful
Build Docker Image / Build-Docker-Image (push) Successful in 4m58s

This commit is contained in:
2025-05-13 12:37:11 +02:00
parent 74a44f043c
commit 6a04c7ae89
5 changed files with 78 additions and 62 deletions

View File

@@ -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)

View File

@@ -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) {

View File

@@ -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,

View File

@@ -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

View File

@@ -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) {
<div class="max-w-6xl mt-10 mx-auto">
<button
@@ -182,3 +148,37 @@ func displayBalance(balance int64) string {
euros := float64(balance) / 100
return fmt.Sprintf("%.2f €", euros)
}
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
}