@@ -15,6 +15,7 @@ import (
1515 "time"
1616
1717 "github.com/docker/cli/cli/command"
18+ "github.com/docker/cli/cli/streams"
1819 "github.com/docker/cli/internal/test"
1920 "github.com/pkg/errors"
2021 "gotest.tools/v3/assert"
@@ -80,6 +81,67 @@ func TestValidateOutputPath(t *testing.T) {
8081 }
8182}
8283
84+ func TestPromptForInput (t * testing.T ) {
85+
86+ t .Run ("case=cancelling the context" , func (t * testing.T ) {
87+ ctx , cancel := context .WithCancel (context .Background ())
88+ t .Cleanup (cancel )
89+ reader , _ := io .Pipe ()
90+
91+ buf := new (bytes.Buffer )
92+ bufioWriter := bufio .NewWriter (buf )
93+
94+ wroteHook := make (chan struct {}, 1 )
95+ promptOut := test .NewWriterWithHook (bufioWriter , func (p []byte ) {
96+ wroteHook <- struct {}{}
97+ })
98+
99+ promptErr := make (chan error , 1 )
100+ go func () {
101+ _ , err := command .PromptForInput (ctx , streams .NewIn (reader ), streams .NewOut (promptOut ), "Enter something" )
102+ promptErr <- err
103+ }()
104+
105+ select {
106+ case <- time .After (1 * time .Second ):
107+ t .Fatal ("timeout waiting for prompt to write to buffer" )
108+ case <- wroteHook :
109+ cancel ()
110+ }
111+
112+ select {
113+ case <- time .After (1 * time .Second ):
114+ t .Fatal ("timeout waiting for prompt to be canceled" )
115+ case err := <- promptErr :
116+ assert .ErrorIs (t , err , command .ErrPromptTerminated )
117+ }
118+ })
119+
120+ t .Run ("case=user input should be properly trimmed" , func (t * testing.T ) {
121+ ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
122+ t .Cleanup (cancel )
123+
124+ reader , writer := io .Pipe ()
125+
126+ buf := new (bytes.Buffer )
127+ bufioWriter := bufio .NewWriter (buf )
128+
129+ wroteHook := make (chan struct {}, 1 )
130+ promptOut := test .NewWriterWithHook (bufioWriter , func (p []byte ) {
131+ wroteHook <- struct {}{}
132+ })
133+
134+ go func () {
135+ <- wroteHook
136+ writer .Write ([]byte (" foo \n " ))
137+ }()
138+
139+ answer , err := command .PromptForInput (ctx , streams .NewIn (reader ), streams .NewOut (promptOut ), "Enter something" )
140+ assert .NilError (t , err )
141+ assert .Equal (t , answer , "foo" )
142+ })
143+ }
144+
83145func TestPromptForConfirmation (t * testing.T ) {
84146 ctx , cancel := context .WithCancel (context .Background ())
85147 t .Cleanup (cancel )
0 commit comments