github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/cmds/grep/grep_test.go (about)

     1  // Copyright 2016-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  	"syscall"
    14  	"testing"
    15  )
    16  
    17  // GrepTest is a table-driven which spawns grep with a variety of options and inputs.
    18  // We need to look at any output data, as well as exit status for things like the -q switch.
    19  func TestGrep(t *testing.T) {
    20  	var tab = []struct {
    21  		i string
    22  		o string
    23  		s int
    24  		a []string
    25  	}{
    26  		// BEWARE: the IO package seems to want this to be newline terminated.
    27  		// If you just use hix with no newline the test will fail. Yuck.
    28  		{"hix\n", "hix\n", 0, []string{"."}},
    29  		{"hix\n", "", 0, []string{"-q", "."}},
    30  		{"hix\n", "", 1, []string{"-q", "hox"}},
    31  	}
    32  
    33  	tmpDir, err := ioutil.TempDir("", "TestGrep")
    34  	if err != nil {
    35  		t.Fatal("TempDir failed: ", err)
    36  	}
    37  	defer os.RemoveAll(tmpDir)
    38  
    39  	testgreppath := filepath.Join(tmpDir, "testgrep.exe")
    40  	out, err := exec.Command("go", "build", "-o", testgreppath, ".").CombinedOutput()
    41  	if err != nil {
    42  		t.Fatalf("go build -o %v cmds/grep: %v\n%s", testgreppath, err, string(out))
    43  	}
    44  
    45  	t.Logf("Built %v for test", testgreppath)
    46  	for _, v := range tab {
    47  		t.Logf("Run %v args %v", testgreppath, v)
    48  		c := exec.Command(testgreppath, v.a...)
    49  		c.Stdin = bytes.NewReader([]byte(v.i))
    50  		o, err := c.CombinedOutput()
    51  		s := c.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
    52  
    53  		if s != v.s {
    54  			t.Errorf("Grep %v < %v > %v: want (exit: %v), got (exit %v)", v.a, v.i, v.o, v.s, s)
    55  			continue
    56  		}
    57  
    58  		if err != nil && s != v.s {
    59  			t.Errorf("Grep %v < %v > %v: want nil, got %v", v.a, v.i, v.o, err)
    60  			continue
    61  		}
    62  		if string(o) != v.o {
    63  			t.Errorf("Grep %v < %v: want '%v', got '%v'", v.a, v.i, v.o, string(o))
    64  			continue
    65  		}
    66  		t.Logf("Grep %v < %v: %v", v.a, v.i, v.o)
    67  	}
    68  }