-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefix_test.go
85 lines (68 loc) · 1.51 KB
/
prefix_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package subcmd
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"testing"
)
func TestPrefix(t *testing.T) {
ctx := context.Background()
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
path := os.Getenv("PATH")
path += ":" + filepath.Join(wd, "testdata")
restoreEnv := testSetenv("PATH", path)
defer restoreEnv()
t.Run("subcmd", func(t *testing.T) {
oldStdout := os.Stdout
f, err := os.CreateTemp("", "subcmd")
if err != nil {
t.Fatal(err)
}
tmpname := f.Name()
defer os.Remove(tmpname)
defer f.Close()
os.Stdout = f
defer func() { os.Stdout = oldStdout }()
c := testPrefixMainCmd{Data: "xyz"}
if err := Run(ctx, c, []string{"subcmd", "a", "b", "c"}); err != nil {
t.Error(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
f, err = os.Open(tmpname)
if err != nil {
t.Fatal(err)
}
defer f.Close()
var got testPrefixMainCmd
if err = json.NewDecoder(f).Decode(&got); err != nil {
t.Fatal(err)
}
if got != c {
t.Errorf("got %+v, want %+v", got, c)
}
})
t.Run("nosubcmd", func(t *testing.T) {
err := Run(ctx, testPrefixMainCmd{}, []string{"nosubcmd", "a", "b", "c"})
var u *UnknownSubcmdErr
switch {
case errors.As(err, &u):
// ok
case err != nil:
t.Error(err)
default:
t.Errorf("expected error of type %T, got nil", u)
}
})
}
type testPrefixMainCmd struct {
Data string `json:"data"`
}
func (testPrefixMainCmd) Subcmds() Map { return nil }
func (testPrefixMainCmd) Prefix() string { return "foo-" }