github.com/ratrocket/u-root@v0.0.0-20180201221235-1cf9f48ee2cf/cmds/wc/wc_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  //
    18  func TestWc(t *testing.T) {
    19  	var tab = []struct {
    20  		i string
    21  		o string
    22  		s int
    23  		a []string
    24  	}{
    25  		{"simple test count words", "4\n", 0, []string{"-w"}}, // don't fail more
    26  		{"lines\nlines\n", "2\n", 0, []string{"-l"}},
    27  		{"count chars\n", "12\n", 0, []string{"-c"}},
    28  	}
    29  
    30  	tmpDir, err := ioutil.TempDir("", "TestWc")
    31  	if err != nil {
    32  		t.Fatal("TempDir failed: ", err)
    33  	}
    34  	defer os.RemoveAll(tmpDir)
    35  
    36  	testwcpath := filepath.Join(tmpDir, "testwc.exe")
    37  	out, err := exec.Command("go", "build", "-o", testwcpath, ".").CombinedOutput()
    38  	if err != nil {
    39  		t.Fatalf("go build -o %v cmds/wc: %v\n%s", testwcpath, err, string(out))
    40  	}
    41  
    42  	t.Logf("Built %v for test", testwcpath)
    43  	for _, v := range tab {
    44  		c := exec.Command(testwcpath, v.a...)
    45  		c.Stdin = bytes.NewReader([]byte(v.i))
    46  		o, err := c.CombinedOutput()
    47  		s := c.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
    48  
    49  		if s != v.s {
    50  			t.Errorf("Wc %v < %v > %v: want (exit: %v), got (exit %v)", v.a, v.i, v.o, v.s, s)
    51  			continue
    52  		}
    53  
    54  		if err != nil && s != v.s {
    55  			t.Errorf("Wc %v < %v > %v: want nil, got %v", v.a, v.i, v.o, err)
    56  			continue
    57  		}
    58  		if string(o) != v.o {
    59  			t.Errorf("Wc %v < %v: want '%v', got '%v'", v.a, v.i, v.o, string(o))
    60  			continue
    61  		}
    62  		t.Logf("[ok] Wc %v < %v: %v", v.a, v.i, v.o)
    63  	}
    64  }