|
| 1 | +// Copyright (c) 2026 Keymaster Team |
| 2 | +// Keymaster - SSH key management system |
| 3 | +// This source code is licensed under the MIT license found in the LICENSE file. |
| 4 | + |
| 5 | +package bun_test |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "errors" |
| 10 | + "io" |
| 11 | + "log" |
| 12 | + "testing" |
| 13 | + |
| 14 | + "github.com/toeirei/keymaster/client" |
| 15 | + "github.com/toeirei/keymaster/client/bun" |
| 16 | + "github.com/toeirei/keymaster/config" |
| 17 | +) |
| 18 | + |
| 19 | +func TestBunClient_WithTransaction_CommitsOnSuccess(t *testing.T) { |
| 20 | + cfg := config.Config{Database: config.ConfigDatabase{Type: "sqlite", Dsn: ":memory:"}} |
| 21 | + logger := log.New(io.Discard, "", 0) |
| 22 | + |
| 23 | + c, err := bun.NewBunClient(cfg, logger) |
| 24 | + if err != nil { |
| 25 | + t.Fatalf("NewBunClient failed: %v", err) |
| 26 | + } |
| 27 | + defer func() { _ = c.Close(context.Background()) }() |
| 28 | + |
| 29 | + ctx := context.Background() |
| 30 | + if err := c.WithTransaction(ctx, func(tx client.Client) error { |
| 31 | + _, err := tx.CreateAccount(ctx, "alice", "example.com", 22, "ssh", "") |
| 32 | + return err |
| 33 | + }); err != nil { |
| 34 | + t.Fatalf("WithTransaction failed: %v", err) |
| 35 | + } |
| 36 | + |
| 37 | + accounts, err := c.ListAccounts(ctx) |
| 38 | + if err != nil { |
| 39 | + t.Fatalf("ListAccounts failed: %v", err) |
| 40 | + } |
| 41 | + if len(accounts) != 1 { |
| 42 | + t.Fatalf("expected 1 account after commit, got %d", len(accounts)) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func TestBunClient_WithTransaction_RollsBackOnError(t *testing.T) { |
| 47 | + cfg := config.Config{Database: config.ConfigDatabase{Type: "sqlite", Dsn: ":memory:"}} |
| 48 | + logger := log.New(io.Discard, "", 0) |
| 49 | + |
| 50 | + c, err := bun.NewBunClient(cfg, logger) |
| 51 | + if err != nil { |
| 52 | + t.Fatalf("NewBunClient failed: %v", err) |
| 53 | + } |
| 54 | + defer func() { _ = c.Close(context.Background()) }() |
| 55 | + |
| 56 | + ctx := context.Background() |
| 57 | + expected := errors.New("boom") |
| 58 | + if err := c.WithTransaction(ctx, func(tx client.Client) error { |
| 59 | + if _, err := tx.CreateAccount(ctx, "bob", "rollback.example", 22, "ssh", ""); err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + return expected |
| 63 | + }); !errors.Is(err, expected) { |
| 64 | + t.Fatalf("expected rollback error %q, got: %v", expected, err) |
| 65 | + } |
| 66 | + |
| 67 | + accounts, err := c.ListAccounts(ctx) |
| 68 | + if err != nil { |
| 69 | + t.Fatalf("ListAccounts failed: %v", err) |
| 70 | + } |
| 71 | + if len(accounts) != 0 { |
| 72 | + t.Fatalf("expected 0 accounts after rollback, got %d", len(accounts)) |
| 73 | + } |
| 74 | +} |
0 commit comments