github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/cmds/comm/comm_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  	"fmt"
     9  	"io/ioutil"
    10  	"os"
    11  	"os/exec"
    12  	"path/filepath"
    13  	"testing"
    14  
    15  	"github.com/u-root/u-root/pkg/testutil"
    16  )
    17  
    18  var commTests = []struct {
    19  	flags []string
    20  	in1   string
    21  	in2   string
    22  	out   string
    23  }{
    24  	{
    25  		// Empty files
    26  		flags: []string{},
    27  		in1:   "",
    28  		in2:   "",
    29  		out:   "",
    30  	}, {
    31  		// Equal files
    32  		flags: []string{},
    33  		in1:   "Line1\nlIne2\nline2\nline3",
    34  		in2:   "Line1\nlIne2\nline2\nline3",
    35  		out:   "\t\tLine1\n\t\tlIne2\n\t\tline2\n\t\tline3\n",
    36  	}, {
    37  		// Empty file 1
    38  		flags: []string{},
    39  		in1:   "",
    40  		in2:   "Line1\nlIne2\n",
    41  		out:   "\tLine1\n\tlIne2\n",
    42  	}, {
    43  		// Empty file 2
    44  		flags: []string{},
    45  		in1:   "Line1\nlIne2\n",
    46  		in2:   "",
    47  		out:   "Line1\nlIne2\n",
    48  	}, {
    49  		// Mix of matchine lines
    50  		flags: []string{},
    51  		in1:   "1\n3\n5\n",
    52  		in2:   "2\n3\n4\n",
    53  		out:   "1\n\t2\n\t\t3\n\t4\n5\n",
    54  	},
    55  }
    56  
    57  // TestComm implements a table-drivent test.
    58  func TestComm(t *testing.T) {
    59  	// Compile comm.
    60  	tmpDir, commPath := testutil.CompileInTempDir(t)
    61  	defer os.RemoveAll(tmpDir)
    62  
    63  	for _, test := range commTests {
    64  		// Write inputs into the two files
    65  		var files [2]string
    66  		for i, contents := range []string{test.in1, test.in2} {
    67  			files[i] = filepath.Join(tmpDir, fmt.Sprintf("txt%d", i))
    68  			if err := ioutil.WriteFile(files[i], []byte(contents), 0600); err != nil {
    69  				t.Errorf("Failed to create test file %d: %v", i, err)
    70  				continue
    71  			}
    72  		}
    73  
    74  		// Execute comm.go
    75  		args := append(append([]string{}, test.flags...), files[0], files[1])
    76  		cmd := exec.Command(commPath, args...)
    77  		if output, err := cmd.CombinedOutput(); err != nil {
    78  			t.Errorf("Comm exited with error: %v; output:\n%s", err, string(output))
    79  		} else if string(output) != test.out {
    80  			t.Errorf("Fail: want\n %#v\n got\n %#v", test.out, string(output))
    81  		}
    82  	}
    83  }