github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/dpipe/dpipe_test.go (about) 1 package dpipe 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "os" 8 "os/exec" //nolint:depguard // This short script has no logging and no Contexts. 9 "runtime" 10 "testing" 11 "time" 12 13 "github.com/sirupsen/logrus" 14 "github.com/stretchr/testify/assert" 15 16 "github.com/datawire/dlib/dlog" 17 ) 18 19 var echoBinary string 20 21 func TestMain(m *testing.M) { 22 ebf, err := os.CreateTemp("", "echo") 23 if err != nil { 24 fmt.Fprintln(os.Stderr, err) 25 os.Exit(1) 26 } 27 echoBinary = ebf.Name() 28 if runtime.GOOS == "windows" { 29 echoBinary += ".exe" 30 } 31 ebf.Close() 32 if err = exec.Command("go", "build", "-o", echoBinary, "./testdata/echo").Run(); err != nil { 33 fmt.Fprintln(os.Stderr, err) 34 os.Exit(1) 35 } 36 defer os.Remove(echoBinary) 37 m.Run() 38 } 39 40 type bufClose struct { 41 bytes.Buffer 42 } 43 44 func (b *bufClose) Close() error { 45 return nil 46 } 47 48 func makeLoggerOn(bf *bytes.Buffer) context.Context { 49 logger := logrus.New() 50 logger.SetLevel(logrus.ErrorLevel) 51 logger.SetOutput(bf) 52 return dlog.WithLogger(context.Background(), dlog.WrapLogrus(logger)) 53 } 54 55 // Test that stdout of a process executed by DPipe is sent to peer. 56 func TestDPipe_stdout(t *testing.T) { 57 log := &bytes.Buffer{} 58 ctx := makeLoggerOn(log) 59 peer := &bufClose{} 60 assert.NoError(t, DPipe(ctx, peer, echoBinary, "-d", "1", "hello stdout")) 61 assert.Empty(t, log) 62 assert.Equal(t, "hello stdout\n", peer.String()) 63 } 64 65 // Test that stderr of a process executed by DPipe is logged as errors. 66 func TestDPipe_stderr(t *testing.T) { 67 log := &bytes.Buffer{} 68 ctx := makeLoggerOn(log) 69 peer := &bufClose{} 70 assert.NoError(t, DPipe(ctx, peer, echoBinary, "-d", "2", "hello stderr")) 71 time.Sleep(time.Second) 72 assert.Contains(t, log.String(), `level=error msg="hello stderr"`) 73 assert.Empty(t, peer.String()) 74 }