app/cli_test.go
48 lines · 1330 bytes
1package app
2
3import (
4 "os"
5 "testing"
6)
7
8// captureExit swaps the fatal exit for one that records its message.
9func captureExit(t *testing.T) *[]string {
10 t.Helper()
11 orig := exit
12 var msgs []string
13 exit = func(msg string, _ int) { msgs = append(msgs, msg) }
14 t.Cleanup(func() { exit = orig })
15 return &msgs
16}
17
18// TestConfigFlagNeedsAValue is the regression test for the bounds check: -c as
19// the last argument, with other arguments before it, used to index past the
20// end and panic instead of reporting the missing value.
21func TestConfigFlagNeedsAValue(t *testing.T) {
22 args, cfg := os.Args, CFG.cfg
23 defer func() { os.Args, CFG.cfg = args, cfg }()
24 msgs := captureExit(t)
25
26 os.Args = []string{"skunkyart", "-x", "-c"}
27 ExecuteCommandLineArguments()
28
29 if len(*msgs) != 1 {
30 t.Fatalf("exit called %d times, want 1 usage error", len(*msgs))
31 }
32 if CFG.cfg != cfg {
33 t.Errorf("config path changed to %q with no value given", CFG.cfg)
34 }
35}
36
37func TestConfigFlagTakesTheNextArgument(t *testing.T) {
38 args, cfg := os.Args, CFG.cfg
39 defer func() { os.Args, CFG.cfg = args, cfg }()
40 msgs := captureExit(t)
41
42 os.Args = []string{"skunkyart", "-c", "other.json"}
43 ExecuteCommandLineArguments()
44
45 if len(*msgs) != 0 || CFG.cfg != "other.json" {
46 t.Errorf("exit calls %v, config path %q; want none and other.json", *msgs, CFG.cfg)
47 }
48}