github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/prompt/mock.go (about) 1 // Copyright 2022 Gravitational, Inc 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package prompt 16 17 import ( 18 "context" 19 "sync" 20 "time" 21 22 "github.com/gravitational/trace" 23 ) 24 25 type FakeReplyFunc func(context.Context) (string, error) 26 27 type FakeReader struct { 28 mu sync.Mutex 29 replies []FakeReplyFunc 30 waitingForReply chan struct{} 31 } 32 33 // NewFakeReader returns a fake that can be used in place of a ContextReader. 34 // Call Add functions in the desired order to configure responses. Each call 35 // represents a read reply, in order. 36 func NewFakeReader() *FakeReader { 37 return &FakeReader{} 38 } 39 40 func (r *FakeReader) IsTerminal() bool { 41 return true 42 } 43 44 func (r *FakeReader) AddReply(fn FakeReplyFunc) *FakeReader { 45 r.mu.Lock() 46 defer r.mu.Unlock() 47 r.replies = append(r.replies, fn) 48 if r.waitingForReply != nil { 49 close(r.waitingForReply) 50 r.waitingForReply = nil 51 } 52 return r 53 } 54 55 func (r *FakeReader) AddString(s string) *FakeReader { 56 return r.AddReply(func(context.Context) (string, error) { 57 return s, nil 58 }) 59 } 60 61 func (r *FakeReader) AddError(err error) *FakeReader { 62 return r.AddReply(func(context.Context) (string, error) { 63 return "", err 64 }) 65 } 66 67 func (r *FakeReader) ReadContext(ctx context.Context) ([]byte, error) { 68 r.mu.Lock() 69 if len(r.replies) == 0 { 70 // wait for a reply 71 wait := make(chan struct{}) 72 r.waitingForReply = wait 73 r.mu.Unlock() 74 75 select { 76 case <-ctx.Done(): 77 return nil, trace.Wrap(ctx.Err()) 78 case <-time.After(5 * time.Second): 79 return nil, trace.BadParameter("no fake replies available after wait") 80 case <-wait: 81 r.mu.Lock() 82 } 83 } 84 85 // Pop first reply. 86 fn := r.replies[0] 87 r.replies = r.replies[1:] 88 r.mu.Unlock() 89 90 val, err := fn(ctx) 91 return []byte(val), err 92 } 93 94 func (r *FakeReader) ReadPassword(ctx context.Context) ([]byte, error) { 95 return r.ReadContext(ctx) 96 }