github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/cmds/core/tee/tee_test.go (about) 1 // Copyright 2022 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 "os" 10 "path/filepath" 11 "strings" 12 "testing" 13 ) 14 15 func TestTee(t *testing.T) { 16 tests := []struct { 17 name string 18 input string 19 args []string 20 append bool 21 appendContent string 22 }{ 23 { 24 name: "default tee", 25 input: "hello", 26 args: []string{"a1", "a2"}, 27 }, 28 { 29 name: "with append flag", 30 input: "a\nb\n", 31 args: []string{"b1"}, 32 append: true, 33 appendContent: "hello", 34 }, 35 } 36 37 for _, test := range tests { 38 t.Run(test.name, func(t *testing.T) { 39 tempDir := t.TempDir() 40 41 for i := 0; i < len(test.args); i++ { 42 test.args[i] = filepath.Join(tempDir, test.args[i]) 43 } 44 45 if test.append { 46 for _, arg := range test.args { 47 err := os.WriteFile(arg, []byte(test.appendContent), 0666) 48 if err != nil { 49 t.Fatal(err) 50 } 51 } 52 } 53 54 var stdout bytes.Buffer 55 var stderr bytes.Buffer 56 cmd := newCommand(test.append, false, test.args) 57 cmd.stdin = strings.NewReader(test.input) 58 cmd.stdout = &stdout 59 cmd.stderr = &stderr 60 if err := cmd.run(); err != nil { 61 t.Fatal(err) 62 } 63 64 // test if stdin match stdout 65 if test.input != stdout.String() { 66 t.Errorf("wanted: %q, got: %q", test.input, stdout.String()) 67 } 68 69 for _, name := range test.args { 70 b, err := os.ReadFile(name) 71 if err != nil { 72 t.Error(err) 73 } 74 res := string(b) 75 expectedContent := test.input 76 77 if test.append { 78 expectedContent = test.appendContent + expectedContent 79 } 80 81 if res != expectedContent { 82 t.Errorf("wanted: %q, got %q", expectedContent, res) 83 } 84 } 85 }) 86 } 87 }