github.com/ratrocket/u-root@v0.0.0-20180201221235-1cf9f48ee2cf/cmds/rush/rush_test.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 main 6 7 import ( 8 "bytes" 9 "io/ioutil" 10 "os" 11 "os/exec" 12 "path/filepath" 13 "regexp" 14 "strings" 15 "syscall" 16 "testing" 17 ) 18 19 var tests = []struct { 20 stdin string // input 21 stdout string // output (regular expression) 22 stderr string // output (regular expression) 23 ret int // output 24 }{ 25 // TODO: Create a `-c` flag for rush so stdout does not contain 26 // prompts, or have the prompt be derived from $PS1. 27 {"exit\n", "% ", "", 0}, 28 {"exit 77\n", "% ", "", 77}, 29 {"exit 1 2 3\n", "% % ", "Too many arguments\n", 0}, 30 {"exit abcd\n", "% % ", "Non numeric argument\n", 0}, 31 {"time cd .\n", "% % ", `real 0.0\d\d\n`, 0}, 32 {"time sleep 0.25\n", "% % ", `real 0.2\d\d\nuser 0.00\d\nsys 0.00\d\n`, 0}, 33 } 34 35 func TestRush(t *testing.T) { 36 // Create temp directory 37 tmpDir, err := ioutil.TempDir("", "TestExit") 38 if err != nil { 39 t.Fatal("TempDir failed: ", err) 40 } 41 defer os.RemoveAll(tmpDir) 42 43 // Compile rush 44 rushPath := filepath.Join(tmpDir, "rush") 45 out, err := exec.Command("go", "build", "-o", rushPath).CombinedOutput() 46 if err != nil { 47 t.Fatalf("go build -o %v cmds/rush: %v\n%s", rushPath, err, string(out)) 48 } 49 50 // Table-driven testing 51 for _, tt := range tests { 52 // Run command 53 cmd := exec.Command(rushPath) 54 cmd.Stdin = strings.NewReader(tt.stdin) 55 var stdout bytes.Buffer 56 cmd.Stdout = &stdout 57 var stderr bytes.Buffer 58 cmd.Stderr = &stderr 59 err := cmd.Run() 60 61 // Check stdout 62 strout := string(stdout.Bytes()) 63 if !regexp.MustCompile("^" + tt.stdout + "$").MatchString(strout) { 64 t.Errorf("Want: %#v; Got: %#v", tt.stdout, strout) 65 } 66 67 // Check stderr 68 strerr := string(stderr.Bytes()) 69 if !regexp.MustCompile("^" + tt.stderr + "$").MatchString(strerr) { 70 t.Errorf("Want: %#v; Got: %#v", tt.stderr, strerr) 71 } 72 73 // Check return code 74 retCode := 0 75 if err != nil { 76 exitErr, ok := err.(*exec.ExitError) 77 if !ok { 78 t.Errorf("Error running rush: %v", err) 79 continue 80 } 81 retCode = exitErr.Sys().(syscall.WaitStatus).ExitStatus() 82 } 83 if retCode != tt.ret { 84 t.Errorf("Want: %d; Got: %d", tt.ret, retCode) 85 } 86 } 87 }