-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli_test.go
77 lines (70 loc) · 1.72 KB
/
cli_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
package main
import (
"bytes"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
)
func TestCLI_Run(t *testing.T) {
t.Parallel()
const (
noErr = false
hasErr = true
)
cases := map[string]struct {
args string
in string
want []string
wantErr bool
Err error
}{
"normal/byte count": {"./gosplit -b 1", "aaa", []string{"a", "a", "a"}, noErr, nil},
"normal/line count": {"./gosplit -l 1", "aaa", []string{"aaa\n"}, noErr, nil},
"abnormal/with prefix": {"./gosplit -l 1 noexist prefix", "", []string{}, noErr, errors.New("stat noexist: no such file or directory")},
"abnormal/too many flags": {"./gosplit -l 1 -b 2", "aaa", []string{}, hasErr, errors.New("only one of -b, -l can be specified")},
}
for name, tt := range cases {
name, tt := name, tt
t.Run(name, func(t *testing.T) {
t.Parallel()
var got bytes.Buffer
cli := &CLI{
Stdout: &got,
Stderr: &got,
Stdin: strings.NewReader(tt.in),
OutputDir: t.TempDir(),
}
args := strings.Split(tt.args, " ")
err := cli.Run(args)
switch {
case tt.wantErr && err == nil:
t.Error("expected error did not occur")
case !tt.wantErr && err != nil && err.Error() != tt.Err.Error():
t.Error("unexpected error:", err)
}
files, err := os.ReadDir(cli.OutputDir)
if err != nil {
t.Error(err)
}
var buf bytes.Buffer
for i, file := range files {
if file.IsDir() {
continue
}
f, err := os.Open(filepath.Join(cli.OutputDir, file.Name()))
if err != nil {
t.Error(err)
}
defer f.Close()
io.Copy(&buf, f)
if buf.String() != tt.want[i] {
t.Errorf("got %q, want %q", buf.String(), tt.want[i])
}
buf.Reset()
}
})
}
}