...

Source file src/github.com/linkerd/linkerd2/testutil/annotations_test.go

Documentation: github.com/linkerd/linkerd2/testutil

     1  package testutil
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os"
     7  	"strings"
     8  	"testing"
     9  )
    10  
    11  func TestMain(m *testing.M) {
    12  	os.Setenv(envFlag, "true")
    13  	os.Exit(m.Run())
    14  }
    15  
    16  func redirectStdout(t *testing.T) (*os.File, chan string) {
    17  	origStdout := os.Stdout
    18  	newStdout, w, pipeErr := os.Pipe()
    19  	if pipeErr != nil {
    20  		t.Fatalf("error creating os.Pipe(): %s", pipeErr)
    21  	}
    22  	os.Stdout = w
    23  
    24  	// retrieve the payload sent to newStdout in a separate goroutine
    25  	// to avoid blocking
    26  	outC := make(chan string)
    27  	go func() {
    28  		var buf bytes.Buffer
    29  		io.Copy(&buf, newStdout)
    30  		outC <- buf.String()
    31  	}()
    32  
    33  	return origStdout, outC
    34  }
    35  
    36  func restoreStdout(outC chan string, origStdout *os.File) string {
    37  	os.Stdout.Close()
    38  	out := <-outC
    39  	os.Stdout = origStdout
    40  	return out
    41  }
    42  
    43  func TestError(t *testing.T) {
    44  	msg := "This is an error"
    45  
    46  	// redirect stdout temporarily to catch the GitHub annotation output
    47  	origStdout, outC := redirectStdout(t)
    48  	Error(&testing.T{}, msg)
    49  	out := restoreStdout(outC, origStdout)
    50  
    51  	if !strings.HasSuffix(strings.TrimSpace(out), "testutil/annotations_test.go,line=48:: - This is an error") {
    52  		t.Fatalf("unexpected stdout content: %s", out)
    53  	}
    54  }
    55  
    56  func TestAnnotatedErrorf(t *testing.T) {
    57  	msgFormat := "This is a detailed error: %s"
    58  	str := "foobar"
    59  	msgDesc := "This is a generic error"
    60  
    61  	// redirect stdout temporarily to catch the GitHub annotation output
    62  	origStdout, outC := redirectStdout(t)
    63  	AnnotatedErrorf(&testing.T{}, msgDesc, msgFormat, str)
    64  	out := restoreStdout(outC, origStdout)
    65  
    66  	if !strings.HasSuffix(strings.TrimSpace(out), "testutil/annotations_test.go,line=63:: - This is a generic error") {
    67  		t.Fatalf("unexpected stdout content: %s", out)
    68  	}
    69  }
    70  

View as plain text