summaryrefslogtreecommitdiff
path: root/internal/commands/test_utils.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/commands/test_utils.go')
-rw-r--r--internal/commands/test_utils.go48
1 files changed, 48 insertions, 0 deletions
diff --git a/internal/commands/test_utils.go b/internal/commands/test_utils.go
new file mode 100644
index 0000000..282e472
--- /dev/null
+++ b/internal/commands/test_utils.go
@@ -0,0 +1,48 @@
+package commands
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "testing"
+
+ punchctx "punchcard/internal/context"
+ "punchcard/internal/database"
+ "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
+}