github.com/stevenmatthewt/agent@v3.5.4+incompatible/stdin/main_test.go (about) 1 package stdin_test 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "log" 7 "os" 8 "os/exec" 9 "runtime" 10 "testing" 11 12 "github.com/buildkite/agent/stdin" 13 ) 14 15 // Derived from TestStatStdin in https://golang.org/src/os/os_test.go 16 17 func TestMain(m *testing.M) { 18 switch os.Getenv("GO_WANT_HELPER_PROCESS") { 19 case "": 20 // Normal test mode 21 os.Exit(m.Run()) 22 23 case "1": 24 fmt.Printf("%v", stdin.IsReadable()) 25 os.Exit(0) 26 } 27 } 28 29 func TestIsStdinIsNotReadableByDefault(t *testing.T) { 30 var cmd *exec.Cmd 31 if runtime.GOOS == `windows` { 32 cmd = exec.Command("cmd", "/c", os.Args[0]) 33 } else { 34 cmd = exec.Command("/bin/sh", "-c", os.Args[0]) 35 } 36 cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1") 37 cmd.Stdin = nil 38 39 output, err := cmd.CombinedOutput() 40 if err != nil { 41 t.Fatalf("Failed to spawn child process: %v %q", err, string(output)) 42 } 43 44 if g, e := string(output), "false"; g != e { 45 t.Errorf("Stdin should not be readable, wanted %q, got %q", e, g) 46 } 47 } 48 49 func TestIsStdinIsReadableWithAPipe(t *testing.T) { 50 var cmd *exec.Cmd 51 if runtime.GOOS == `windows` { 52 cmd = exec.Command("cmd", "/c", `echo output | `+os.Args[0]) 53 } else { 54 cmd = exec.Command("/bin/sh", "-c", `echo output | `+os.Args[0]) 55 } 56 cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1") 57 58 output, err := cmd.CombinedOutput() 59 if err != nil { 60 t.Fatalf("Failed to spawn child process: %v %q", err, string(output)) 61 } 62 63 if g, e := string(output), "true"; g != e { 64 t.Errorf("Stdin should be readable from a pipe, wanted %q, got %q", e, g) 65 } 66 } 67 68 func TestIsStdinIsReadableWithOutputRedirection(t *testing.T) { 69 tmpfile, err := ioutil.TempFile("", "output-redirect") 70 if err != nil { 71 log.Fatal(err) 72 } 73 74 defer os.Remove(tmpfile.Name()) 75 76 if _, err := tmpfile.Write([]byte("output")); err != nil { 77 t.Fatal(err) 78 } 79 if err := tmpfile.Close(); err != nil { 80 t.Fatal(err) 81 } 82 83 var cmd *exec.Cmd 84 if runtime.GOOS == `windows` { 85 cmd = exec.Command("cmd", "/c", os.Args[0]+`< `+tmpfile.Name()) 86 } else { 87 cmd = exec.Command("/bin/sh", "-c", os.Args[0]+`< `+tmpfile.Name()) 88 } 89 cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1") 90 91 output, err := cmd.CombinedOutput() 92 if err != nil { 93 t.Fatalf("Failed to spawn child process: %v %q", err, string(output)) 94 } 95 96 if g, e := string(output), "true"; g != e { 97 t.Errorf("Stdin should be readable from a file, wanted %q, got %q", e, g) 98 } 99 }