github.com/jlowellwofford/u-root@v1.0.0/pkg/testutil/stdin.go (about) 1 // Copyright 2017 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package testutil 6 7 // FakeStdin implements io.Reader and returns predefined list of answers, 8 // suitable for mocking standard input. 9 type FakeStdin struct { 10 answers []string 11 pos int 12 overflowed bool 13 } 14 15 // NewFakeStdin creates new FakeStdin value with given answers. 16 func NewFakeStdin(answers ...string) *FakeStdin { 17 var fs = FakeStdin{answers: make([]string, len(answers))} 18 for i, a := range answers { 19 fs.answers[i] = a + "\n" 20 } 21 return &fs 22 } 23 24 // Read answers one by one and keep record whether the stdin 25 // has overflowed. 26 func (fs *FakeStdin) Read(p []byte) (int, error) { 27 if len(fs.answers) <= fs.pos { 28 fs.overflowed = true 29 fs.pos = 0 30 } 31 n := copy(p, fs.answers[fs.pos]) 32 fs.pos += 1 33 return n, nil 34 } 35 36 // Count returns how many answers have been read. 37 // 38 // This counter overflows and never returns value bigger than the count of 39 // given answers. 40 func (fs *FakeStdin) Count() int { 41 return fs.pos 42 } 43 44 // Overflowed reports whether more reads happened than expected. 45 func (fs *FakeStdin) Overflowed() bool { 46 return fs.overflowed 47 }