/
utils_test.go
96 lines (83 loc) · 2.64 KB
/
utils_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
86
87
88
89
90
91
92
93
94
95
96
package command
import (
"bufio"
"bytes"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/pkg/errors"
"gotest.tools/v3/assert"
)
func TestStringSliceReplaceAt(t *testing.T) {
out, ok := StringSliceReplaceAt([]string{"abc", "foo", "bar", "bax"}, []string{"foo", "bar"}, []string{"baz"}, -1)
assert.Assert(t, ok)
assert.DeepEqual(t, []string{"abc", "baz", "bax"}, out)
out, ok = StringSliceReplaceAt([]string{"foo"}, []string{"foo", "bar"}, []string{"baz"}, -1)
assert.Assert(t, !ok)
assert.DeepEqual(t, []string{"foo"}, out)
out, ok = StringSliceReplaceAt([]string{"abc", "foo", "bar", "bax"}, []string{"foo", "bar"}, []string{"baz"}, 0)
assert.Assert(t, !ok)
assert.DeepEqual(t, []string{"abc", "foo", "bar", "bax"}, out)
out, ok = StringSliceReplaceAt([]string{"foo", "bar", "bax"}, []string{"foo", "bar"}, []string{"baz"}, 0)
assert.Assert(t, ok)
assert.DeepEqual(t, []string{"baz", "bax"}, out)
out, ok = StringSliceReplaceAt([]string{"abc", "foo", "bar", "baz"}, []string{"foo", "bar"}, nil, -1)
assert.Assert(t, ok)
assert.DeepEqual(t, []string{"abc", "baz"}, out)
out, ok = StringSliceReplaceAt([]string{"foo"}, nil, []string{"baz"}, -1)
assert.Assert(t, !ok)
assert.DeepEqual(t, []string{"foo"}, out)
}
func TestValidateOutputPath(t *testing.T) {
basedir := t.TempDir()
dir := filepath.Join(basedir, "dir")
notexist := filepath.Join(basedir, "notexist")
err := os.MkdirAll(dir, 0o755)
assert.NilError(t, err)
file := filepath.Join(dir, "file")
err = os.WriteFile(file, []byte("hi"), 0o644)
assert.NilError(t, err)
testcases := []struct {
path string
err error
}{
{basedir, nil},
{file, nil},
{dir, nil},
{dir + string(os.PathSeparator), nil},
{notexist, nil},
{notexist + string(os.PathSeparator), nil},
{filepath.Join(notexist, "file"), errors.New("does not exist")},
}
for _, testcase := range testcases {
t.Run(testcase.path, func(t *testing.T) {
err := ValidateOutputPath(testcase.path)
if testcase.err == nil {
assert.NilError(t, err)
} else {
assert.ErrorContains(t, err, testcase.err.Error())
}
})
}
}
func TestPromptForConfirmation(t *testing.T) {
buf := new(bytes.Buffer)
w := bufio.NewWriter(buf)
result := make(chan bool)
go func() {
result <- PromptForConfirmation(os.Stdin, w, "")
}()
time.Sleep(100 * time.Millisecond)
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
select {
case r := <-result:
assert.Check(t, !r)
case <-time.After(100 * time.Millisecond):
t.Fatal("PromptForConfirmation did not return after SIGINT")
}
assert.NilError(t, w.Flush())
assert.Equal(t, strings.TrimSpace(buf.String()), "Are you sure you want to proceed? [y/N]")
}