package cli_test import ( "fmt" "os" "strings" "testing" "github.com/spf13/cobra" "git.avsdev.uk/Go/job-search/internal/cli" "git.avsdev.uk/Go/job-search/internal/cli/cmdtest" ) // The shared flags (--config, --debug and --quiet), run through a root // command like job-search's and a command that loads the configuration, as // every real command does. const appConfig = "logging:\n level: info\n" // newRoot returns a root command with a "level" command that loads the // configuration and prints its log level. func newRoot() *cobra.Command { opts := &cli.Options{} return cmdtest.NewRoot(opts, &cobra.Command{ Use: "level", RunE: func(cmd *cobra.Command, args []string) error { conf, err := opts.RunSetup(cmd, true, true) if err != nil { return err } fmt.Println("level:", conf.Logging.Level) return nil }, }) } // --debug and --quiet override the configured log level; --debug wins. func TestLogLevelFlags(t *testing.T) { cmdtest.Setup(t, appConfig) for _, tt := range []struct { args []string want string }{ {nil, "level: info"}, {[]string{"--debug"}, "level: debug"}, {[]string{"-d"}, "level: debug"}, {[]string{"--quiet"}, "level: error"}, {[]string{"-q"}, "level: error"}, {[]string{"-q", "-d"}, "level: debug"}, } { args := append([]string{"level"}, tt.args...) t.Run(strings.Join(args, " "), func(t *testing.T) { cmdtest.Contains(t, cmdtest.MustRun(t, newRoot, args...), tt.want) }) } } // --config points the command at another file. func TestConfigFlag(t *testing.T) { cmdtest.Setup(t, appConfig) cmdtest.WriteFile(t, "other.yaml", "logging:\n level: error\n") for _, flag := range []string{"--config", "-c"} { out := cmdtest.MustRun(t, newRoot, "level", flag, "other.yaml") cmdtest.Contains(t, out, "level: error") } _, err := cmdtest.Run(t, newRoot, "", "level", "--config", "missing.yaml") if err == nil { t.Error("a missing --config file was accepted") } } // A .env file is optional, but one that can't be parsed is an error. func TestEnvFile(t *testing.T) { cmdtest.Setup(t, appConfig) if err := os.Remove(".env"); err != nil { t.Fatal(err) } if _, err := cmdtest.Run(t, newRoot, "", "level"); err != nil { t.Errorf("without a .env file: %v; want no error", err) } cmdtest.WriteFile(t, ".env", "NOT VALID\n") _, err := cmdtest.Run(t, newRoot, "", "level") cmdtest.ErrContains(t, err, ".env") }