Added unit tests for CLI
This commit is contained in:
1 parent
169c6c6b64
commit
5ec4b65b91
7 files changed
+965
No files matched your search
@@ -0,0 +1,79 @@
|
||||
package cli_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/cli"
|
||||
"git.avsdev.uk/Go/job-search/internal/cli/cmdtest"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// 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"},
|
||||
} {
|
||||
out := cmdtest.MustRun(t, newRoot, append([]string{"level"}, tt.args...)...)
|
||||
cmdtest.Contains(t, out, 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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingEnvFile(t *testing.T) {
|
||||
cmdtest.Setup(t, appConfig)
|
||||
if err := os.Remove(".env"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := cmdtest.Run(t, newRoot, "", "level")
|
||||
cmdtest.ErrContains(t, err, ".env")
|
||||
}
|
||||
Reference in new issue
Block a user