github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/client/logging/dup_test.go (about)

     1  package logging
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/require"
    11  
    12  	"github.com/datawire/dlib/dexec"
    13  	"github.com/datawire/dlib/dlog"
    14  )
    15  
    16  func head(str string, n int) string {
    17  	end := 0
    18  	for i := 0; i < n; i++ {
    19  		nl := strings.IndexByte(str[end:], '\n')
    20  		if nl < 0 {
    21  			return str
    22  		}
    23  		end += nl + 1
    24  	}
    25  	return str[:end]
    26  }
    27  
    28  func TestDupToStd(t *testing.T) {
    29  	dirname := t.TempDir()
    30  
    31  	ctx := dlog.NewTestContext(t, true)
    32  	cmd := dexec.CommandContext(ctx, os.Args[0], "-test.v", "-test.run="+t.Name()+"Helper", "--", dirname)
    33  	cmd.Env = append(os.Environ(),
    34  		"GO_WANT_HELPER_PROCESS=1")
    35  
    36  	err := cmd.Run()
    37  	var eerr *dexec.ExitError
    38  	require.ErrorAs(t, err, &eerr)
    39  	require.True(t, eerr.Exited())
    40  	require.Equal(t, 2, eerr.ExitCode())
    41  
    42  	content, err := os.ReadFile(filepath.Join(dirname, "log.txt"))
    43  	require.NoError(t, err)
    44  	require.Equal(t, "this is stdout\nthis is stderr\npanic: this is panic\n",
    45  		head(string(content), 3))
    46  }
    47  
    48  func TestMain(m *testing.M) {
    49  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
    50  		os.Exit(testDupToStdHelper())
    51  	}
    52  	os.Exit(m.Run())
    53  }
    54  
    55  func testDupToStdHelper() int {
    56  	args := os.Args
    57  	for len(args) > 0 {
    58  		if args[0] == "--" {
    59  			args = args[1:]
    60  			break
    61  		}
    62  		args = args[1:]
    63  	}
    64  	if len(args) != 1 {
    65  		fmt.Fprintf(os.Stderr, "expected exactly 1 argument, got %d\n", len(args))
    66  		return 1
    67  	}
    68  
    69  	dirname := args[0]
    70  
    71  	file, err := os.OpenFile(filepath.Join(dirname, "log.txt"), os.O_CREATE|os.O_WRONLY, 0o666)
    72  	if err != nil {
    73  		fmt.Fprintf(os.Stderr, "open: %v\n", err)
    74  		return 1
    75  	}
    76  
    77  	if err := dupToStdOut(file); err != nil {
    78  		fmt.Fprintf(os.Stderr, "dup: %v\n", err)
    79  		return 1
    80  	}
    81  
    82  	if err := dupToStdErr(file); err != nil {
    83  		fmt.Fprintf(os.Stderr, "dup: %v\n", err)
    84  		return 1
    85  	}
    86  
    87  	fmt.Println("this is stdout")
    88  	fmt.Fprintln(os.Stderr, "this is stderr")
    89  	panic("this is panic")
    90  }