summaryrefslogtreecommitdiff
path: root/internal/cli/root_test.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/cli/root_test.go')
-rw-r--r--internal/cli/root_test.go69
1 files changed, 69 insertions, 0 deletions
diff --git a/internal/cli/root_test.go b/internal/cli/root_test.go
new file mode 100644
index 0000000..4603d3b
--- /dev/null
+++ b/internal/cli/root_test.go
@@ -0,0 +1,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")
+ }
+}