lesiw.io/buzzybox@v0.0.0-20240312044635-72f204fc5bd3/hive/cat_test.go (about)

     1  package hive_test
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  	"testing"
     9  
    10  	"lesiw.io/buzzybox/hive"
    11  )
    12  
    13  type catTest struct {
    14  	name  string
    15  	stdin []string
    16  	files []string
    17  	args  []string
    18  	want  string
    19  }
    20  
    21  func TestCat(t *testing.T) {
    22  	tests := []catTest{{
    23  		name:  "stdin with newline",
    24  		stdin: []string{"hello world\n"},
    25  		want:  "hello world\n",
    26  	}, {
    27  		name:  "stdin without newline",
    28  		stdin: []string{"hello world"},
    29  		want:  "hello world",
    30  	}, {
    31  		name:  "one file",
    32  		files: []string{"foo\n"},
    33  		args:  []string{"f0"},
    34  		want:  "foo\n",
    35  	}, {
    36  		name:  "two files",
    37  		files: []string{"foo\n", "bar\n"},
    38  		args:  []string{"f0", "f1"},
    39  		want:  "foo\nbar\n",
    40  	}, {
    41  		name:  "same file",
    42  		files: []string{"foo\n"},
    43  		args:  []string{"f0", "f0"},
    44  		want:  "foo\nfoo\n",
    45  	}, {
    46  		name:  "file then stdin",
    47  		files: []string{"file contents\n"},
    48  		stdin: []string{"stdin contents\n"},
    49  		args:  []string{"f0", "-"},
    50  		want:  "file contents\nstdin contents\n",
    51  	}, {
    52  		name:  "stdin then file",
    53  		files: []string{"file contents\n"},
    54  		stdin: []string{"stdin contents\n"},
    55  		args:  []string{"-", "f0"},
    56  		want:  "stdin contents\nfile contents\n",
    57  	}, {
    58  		name:  "multiple stdin",
    59  		stdin: []string{"one\n", "two\n"},
    60  		args:  []string{"-", "-"},
    61  		want:  "one\ntwo\n",
    62  	}}
    63  	for _, tt := range tests {
    64  		t.Run(tt.name, func(t *testing.T) {
    65  			testCat(t, tt)
    66  		})
    67  	}
    68  }
    69  
    70  func testCat(t *testing.T, tt catTest) {
    71  	stdin := newMultiStringReader(tt.stdin)
    72  	stdout := &strings.Builder{}
    73  	if len(tt.files) > 0 {
    74  		dir := t.TempDir()
    75  		for i, f := range tt.files {
    76  			path := filepath.Join(dir, fmt.Sprintf("f%d", i))
    77  			if err := os.WriteFile(path, []byte(f), 0600); err != nil {
    78  				t.Fatal(err)
    79  			}
    80  		}
    81  		if err := os.Chdir(dir); err != nil {
    82  			t.Fatal(err)
    83  		}
    84  	}
    85  	args := append([]string{"cat"}, tt.args...)
    86  	cmd := hive.Command(args...)
    87  	cmd.Stdin = stdin
    88  	cmd.Stdout = stdout
    89  	if code := cmd.Run(); code != 0 {
    90  		t.Errorf("exit status %d, want 0", code)
    91  	}
    92  	if got := stdout.String(); got != tt.want {
    93  		t.Errorf("got %q, want %q", got, tt.want)
    94  	}
    95  }