gunk-dev/the-valley

root_test.go

source4cbb5ec9c5dbmain's published tip history
2.0 KiB
1package cmd
2
3import (
4 "bytes"
5 "strings"
6 "testing"
7)
8
9// execRoot runs the root command with args and returns what it printed. The
10// flags a run sets stay set on cobra's commands, so it clears the help and
11// version flags of the command it ran afterwards.
12func execRoot(t *testing.T, args ...string) string {
13 t.Helper()
14 var out bytes.Buffer
15 rootCmd.SetOut(&out)
16 rootCmd.SetErr(&out)
17 rootCmd.SetArgs(args)
18 ran, err := rootCmd.ExecuteC()
19 for _, name := range []string{"help", "version"} {
20 if f := ran.Flags().Lookup(name); f != nil {
21 _ = f.Value.Set("false")
22 f.Changed = false
23 }
24 }
25 rootCmd.SetOut(nil)
26 rootCmd.SetErr(nil)
27 rootCmd.SetArgs(nil)
28 if err != nil {
29 t.Fatalf("%s: %v", strings.Join(args, " "), err)
30 }
31 return out.String()
32}
33
34// The root command names itself by the program name it runs under:
35// `valley flow` as valley-flow, wherever that is, and klaus under any other
36// name, with klaus's --version line exactly as its template has always
37// printed it.
38func TestRootNamesItselfByInvocation(t *testing.T) {
39 t.Cleanup(func() { nameRoot("klaus") })
40 for _, tc := range []struct{ argv0, name string }{
41 {"valley-flow", "valley flow"},
42 {"/nix/store/0000000000000000000000000000000-klaus-0.1.0/bin/valley-flow", "valley flow"},
43 {"klaus", "klaus"},
44 {"/home/operator/.nix-profile/bin/klaus", "klaus"},
45 {"./valley-flow-dev", "klaus"},
46 } {
47 nameRoot(invokedAs(tc.argv0))
48 if got, want := execRoot(t, "--version"), tc.name+" version "+version+"\n"; got != want {
49 t.Errorf("%s --version: printed %q, want %q", tc.argv0, got, want)
50 }
51 help := execRoot(t, "--help")
52 for _, want := range []string{"\n " + tc.name + " [command]\n", `Use "` + tc.name + ` [command] --help"`} {
53 if !strings.Contains(help, want) {
54 t.Errorf("%s --help: no %q in:\n%s", tc.argv0, want, help)
55 }
56 }
57 if sub := execRoot(t, "status", "--help"); !strings.Contains(sub, "\n "+tc.name+" status") {
58 t.Errorf("%s status --help: no usage line naming %q in:\n%s", tc.argv0, tc.name+" status", sub)
59 }
60 }
61}