github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/exp/ash/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 "fmt" 10 "io/ioutil" 11 "os" 12 "regexp" 13 "strings" 14 "testing" 15 16 "github.com/u-root/u-root/pkg/testutil" 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 \d+.\d{3}\nuser \d+.\d{3}\nsys \d+.\d{3}\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 // Table-driven testing 44 for i, tt := range tests { 45 t.Run(fmt.Sprintf("test%d", i), func(t *testing.T) { 46 // Run command 47 cmd := testutil.Command(t) 48 cmd.Stdin = strings.NewReader(tt.stdin) 49 var stdout bytes.Buffer 50 cmd.Stdout = &stdout 51 var stderr bytes.Buffer 52 cmd.Stderr = &stderr 53 err := cmd.Run() 54 55 // Check stdout 56 strout := string(stdout.Bytes()) 57 if !regexp.MustCompile("^" + tt.stdout + "$").MatchString(strout) { 58 t.Errorf("Want: %#v; Got: %#v", tt.stdout, strout) 59 } 60 61 // Check stderr 62 strerr := string(stderr.Bytes()) 63 if !regexp.MustCompile("^" + tt.stderr + "$").MatchString(strerr) { 64 t.Errorf("Want: %#v; Got: %#v", tt.stderr, strerr) 65 } 66 67 // Check return code 68 if err := testutil.IsExitCode(err, tt.ret); err != nil { 69 t.Error(err) 70 } 71 }) 72 } 73 } 74 75 func TestMain(m *testing.M) { 76 testutil.Run(m, main) 77 }