src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/logutil/logutil_test.go (about)

     1  package logutil
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"regexp"
     7  	"testing"
     8  
     9  	"src.elv.sh/pkg/must"
    10  )
    11  
    12  func TestLogger(t *testing.T) {
    13  	logger := GetLogger("foo ")
    14  
    15  	r, w := must.Pipe()
    16  	SetOutput(w)
    17  	logger.Println("out 1")
    18  	w.Close()
    19  	wantOut1 := must.OK1(regexp.Compile("^foo .*out 1\n$"))
    20  	if out := must.ReadAllAndClose(r); !wantOut1.Match(out) {
    21  		t.Errorf("got out %q, want one matching %q", out, wantOut1)
    22  	}
    23  
    24  	outPath := filepath.Join(t.TempDir(), "out")
    25  	must.OK(SetOutputFile(outPath))
    26  	logger.Println("out 2")
    27  	must.OK(SetOutputFile(""))
    28  	wantOut2 := must.OK1(regexp.Compile("^foo .*out 2\n$"))
    29  	if out := must.ReadAllAndClose(must.OK1(os.Open(outPath))); !wantOut2.Match(out) {
    30  		t.Errorf("got out %q, want one matching %q", out, wantOut2)
    31  	}
    32  }
    33  
    34  func TestSetOutput_Error(t *testing.T) {
    35  	err := SetOutputFile("/bad/file/path")
    36  	if err == nil {
    37  		t.Errorf("want non-nil error, got nil")
    38  	}
    39  }