gitlab.com/apertussolutions/u-root@v7.0.0+incompatible/cmds/core/yes/yes_test.go (about) 1 // Copyright 2017-2019 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 main 6 7 import ( 8 "bufio" 9 "testing" 10 11 "github.com/u-root/u-root/pkg/testutil" 12 ) 13 14 func TestMain(m *testing.M) { 15 testutil.Run(m, main) 16 } 17 18 func TestYes(t *testing.T) { 19 type test struct { 20 name string 21 in []string 22 expected string 23 closeStdout bool 24 } 25 tests := []test{ 26 {name: "noParameterCloseTest", in: []string{}, expected: "y", closeStdout: true}, 27 {name: "noParameterKillTest", in: []string{}, expected: "y", closeStdout: false}, 28 {name: "oneParameterCloseTest", in: []string{"hi"}, expected: "hi", closeStdout: true}, 29 {name: "oneParameterKillTest", in: []string{"hi"}, expected: "hi", closeStdout: false}, 30 {name: "fourParameterCloseTest", in: []string{"hi", "how", "are", "you"}, expected: "hi how are you", closeStdout: true}, 31 {name: "fourParameterKillTest", in: []string{"hi", "how", "are", "you"}, expected: "hi how are you", closeStdout: false}, 32 } 33 for _, v := range tests { 34 t.Run(v.name, func(t *testing.T) { 35 cmd := testutil.Command(t, v.in...) 36 stdout, err := cmd.StdoutPipe() 37 if err != nil { 38 t.Fatalf("Failed to get stdout of yes command: got %v, want nil", err) 39 } 40 if err := cmd.Start(); err != nil { 41 t.Fatalf("Failed to start yes command: got %v, want nil", err) 42 } 43 in := bufio.NewScanner(stdout) 44 for i := 0; i < 1000; i++ { 45 if !in.Scan() { 46 t.Fatalf("Could not scan: got %v, want nil", in.Err()) 47 } 48 if text := in.Text(); text != v.expected { 49 t.Errorf("Got %v at iteration %d, want %v", text, i, v.expected) 50 break 51 } 52 } 53 if v.closeStdout == true { 54 if err := stdout.Close(); err != nil { 55 t.Fatalf("Close standard out pipe: got %v, want nil", err) 56 } 57 if err := cmd.Wait(); err == nil || err.Error() != "signal: broken pipe" { 58 t.Errorf("Complete the child process: got %v, want 'signal: broken pipe'", err) 59 } 60 } else { 61 if err := cmd.Process.Kill(); err != nil { 62 t.Errorf("Kill the child process: got %v, want nil", err) 63 } 64 } 65 }) 66 } 67 }