summaryrefslogtreecommitdiff
path: root/internal/commands/test_utils.go
blob: c53578fce48f2233f78b73fc88493f989b76704e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package commands

import (
	"bytes"
	"context"
	"database/sql"
	"testing"

	punchctx "git.tjp.lol/punchcard/internal/context"
	"git.tjp.lol/punchcard/internal/database"
	"git.tjp.lol/punchcard/internal/queries"
)

func setupTestDB(t *testing.T) (*queries.Queries, func()) {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		t.Fatalf("Failed to open in-memory sqlite db: %v", err)
	}
	if err := database.InitializeDB(db); err != nil {
		t.Fatalf("Failed to initialize in-memory sqlite db: %v", err)
	}
	q := queries.New(db)

	// Return cleanup function that restores environment immediately
	cleanup := func() {
		if err := q.DBTX().(*sql.DB).Close(); err != nil {
			t.Logf("error closing database: %v", err)
		}
	}

	return q, cleanup
}

func executeCommandWithDB(t *testing.T, q *queries.Queries, args ...string) (string, error) {
	buf := new(bytes.Buffer)

	// Create context with provided database
	ctx := punchctx.WithDB(context.Background(), q)

	// Use factory functions to create fresh command instances for each test
	testRootCmd := NewRootCmd()
	testRootCmd.SetOut(buf)
	testRootCmd.SetErr(buf)
	testRootCmd.SetArgs(args)

	err := testRootCmd.ExecuteContext(ctx)
	return buf.String(), err
}