summaryrefslogtreecommitdiff
path: root/internal/cli/root_test.go
blob: 4603d3b08f7d7ed9c3320205e37ab0f3d1267a68 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package cli

import (
	"os"
	"path/filepath"
	"testing"

	"github.com/spf13/cobra"
)

// noopCmd is a harmless subcommand used to trigger PersistentPreRunE.
func noopCmd() *cobra.Command {
	return &cobra.Command{
		Use:  "noop",
		RunE: func(cmd *cobra.Command, args []string) error { return nil },
	}
}

func TestRootCmd_ConfigFile_Loaded(t *testing.T) {
	dir := t.TempDir()
	cfgPath := filepath.Join(dir, "config.toml")
	if err := os.WriteFile(cfgPath, []byte("server_addr = \":9191\"\n"), 0600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("HOME", dir)

	cmd := NewRootCmd()
	cmd.AddCommand(noopCmd())
	cmd.SetArgs([]string{"--config", cfgPath, "noop"})
	if err := cmd.Execute(); err != nil {
		t.Fatalf("Execute: %v", err)
	}

	if cfg.ServerAddr != ":9191" {
		t.Errorf("ServerAddr = %q, want :9191", cfg.ServerAddr)
	}
}

func TestRootCmd_ConfigFile_CLIFlagOverrides(t *testing.T) {
	dir := t.TempDir()
	cfgPath := filepath.Join(dir, "config.toml")
	// Config file sets data_dir, but --data-dir flag should win.
	if err := os.WriteFile(cfgPath, []byte("data_dir = \"/from/file\"\n"), 0600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("HOME", dir)

	cmd := NewRootCmd()
	cmd.AddCommand(noopCmd())
	cmd.SetArgs([]string{"--config", cfgPath, "--data-dir", "/from/flag", "noop"})
	if err := cmd.Execute(); err != nil {
		t.Fatalf("Execute: %v", err)
	}

	if cfg.DataDir != "/from/flag" {
		t.Errorf("DataDir = %q, want /from/flag", cfg.DataDir)
	}
}

func TestRootCmd_ConfigFile_Missing_ReturnsError(t *testing.T) {
	t.Setenv("HOME", t.TempDir())

	cmd := NewRootCmd()
	cmd.AddCommand(noopCmd())
	cmd.SetArgs([]string{"--config", "/nonexistent/config.toml", "noop"})
	if err := cmd.Execute(); err == nil {
		t.Fatal("expected error for missing config file, got nil")
	}
}