github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/cmds/exp/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  	"fmt"
    10  	"regexp"
    11  	"strings"
    12  	"testing"
    13  
    14  	"github.com/mvdan/u-root-coreutils/pkg/testutil"
    15  )
    16  
    17  var tests = []struct {
    18  	stdin  string // input
    19  	stdout string // output (regular expression)
    20  	stderr string // output (regular expression)
    21  	ret    int    // output
    22  }{
    23  	// TODO: Create a `-c` flag for rush so stdout does not contain
    24  	// prompts, or have the prompt be derived from $PS1.
    25  	{"echo|wc\n", ".*", "", 0},
    26  	{"true\n", "% % ", "", 0},
    27  	{"false\n", "% % ", "wait: exit status 1\n", 0},
    28  }
    29  
    30  func TestRush(t *testing.T) {
    31  	// Table-driven testing
    32  	for i, tt := range tests {
    33  		t.Run(fmt.Sprintf("test%d", i), func(t *testing.T) {
    34  			// Run command
    35  			cmd := testutil.Command(t)
    36  			cmd.Stdin = strings.NewReader(tt.stdin)
    37  			var stdout bytes.Buffer
    38  			cmd.Stdout = &stdout
    39  			var stderr bytes.Buffer
    40  			cmd.Stderr = &stderr
    41  			err := cmd.Run()
    42  
    43  			// Check stdout
    44  			strout := stdout.String()
    45  			// If you need the ^$ anchor put it in the test array.
    46  			if !regexp.MustCompile(tt.stdout).MatchString(strout) {
    47  				t.Errorf("Want: %#v; Got: %#v", tt.stdout, strout)
    48  			}
    49  
    50  			// Check stderr
    51  			strerr := stderr.String()
    52  			if !regexp.MustCompile("^" + tt.stderr + "$").MatchString(strerr) {
    53  				t.Errorf("Want: %#v; Got: %#v", tt.stderr, strerr)
    54  			}
    55  
    56  			// Check return code
    57  			if err := testutil.IsExitCode(err, tt.ret); err != nil {
    58  				t.Error(err)
    59  			}
    60  		})
    61  	}
    62  }
    63  
    64  func TestMain(m *testing.M) {
    65  	testutil.Run(m, main)
    66  }