1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ui_test
15
16 import (
17 "bytes"
18 "context"
19 "errors"
20 "testing"
21
22 "github.com/sigstore/cosign/v2/internal/ui"
23 "github.com/stretchr/testify/assert"
24 )
25
26 func TestConfirm(t *testing.T) {
27 cases := []struct {
28 name string
29 input string
30 expected error
31 expectedMessage string
32 }{
33 {"no", "n\n", &ui.ErrPromptDeclined{}, "user declined"},
34 {"no-upper", "N\n", &ui.ErrPromptDeclined{}, "user declined"},
35 {"yes", "y\n", nil, ""},
36 {"yes-upper", "Y\n", nil, ""},
37 {"default", "\n", &ui.ErrPromptDeclined{}, "user declined"},
38 {"empty", "", &ui.ErrPromptDeclined{}, "user declined"},
39 {"invalid", "yy", &ui.ErrInvalidInput{Got: "yy", Allowed: "y, n"}, "invalid input"},
40 {"no-windows", "n\r\n", &ui.ErrPromptDeclined{}, "user declined"},
41 {"yes-windows", "y\r\n", nil, ""},
42 {"default-windows", "\r\n", &ui.ErrPromptDeclined{}, "user declined"},
43 {"invalid", "yy\r\n", &ui.ErrInvalidInput{Got: "yy", Allowed: "y, n"}, "invalid input"},
44 }
45 for _, tc := range cases {
46 t.Run(tc.name, func(t *testing.T) {
47 stderr := ui.RunWithTestCtx(func(ctx context.Context, write ui.WriteFunc) {
48 write(tc.input)
49 err := ui.ConfirmContinue(ctx)
50 assert.EqualValues(t, tc.expected, err)
51 if len(tc.expectedMessage) > 0 {
52 assert.ErrorContains(t, err, "")
53 }
54 })
55 assert.Equal(t, "Are you sure you would like to continue? [y/N] ", stderr, "Bad output to STDERR")
56 })
57 }
58 }
59
60 type BadReader struct{}
61
62
63 func (b *BadReader) Read(p []byte) (n int, err error) {
64 return 0, errors.New("my error")
65 }
66
67 func TestConfirmError(t *testing.T) {
68 var stderr bytes.Buffer
69 stdin := BadReader{}
70 ctx := ui.WithEnv(context.Background(), &ui.Env{&stderr, &stdin})
71 assert.ErrorContains(t, ui.ConfirmContinue(ctx), "my error")
72 }
73
View as plain text