github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/log/log_test.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package log_test
     6  
     7  import (
     8  	"os"
     9  	"testing"
    10  
    11  	"github.com/Schaudge/grailbase/log"
    12  )
    13  
    14  type testOutputter struct {
    15  	level    log.Level
    16  	messages map[log.Level][]string
    17  }
    18  
    19  func newTestOutputter(level log.Level) *testOutputter {
    20  	return &testOutputter{level, make(map[log.Level][]string)}
    21  }
    22  
    23  func (t *testOutputter) Empty() bool {
    24  	for _, m := range t.messages {
    25  		if len(m) != 0 {
    26  			return false
    27  		}
    28  	}
    29  	return true
    30  }
    31  
    32  func (t *testOutputter) Next(level log.Level) string {
    33  	if len(t.messages[level]) == 0 {
    34  		return ""
    35  	}
    36  	var m string
    37  	m, t.messages[level] = t.messages[level][0], t.messages[level][1:]
    38  	return m
    39  }
    40  
    41  func (t *testOutputter) Level() log.Level {
    42  	return t.level
    43  }
    44  
    45  func (t *testOutputter) Output(calldepth int, level log.Level, s string) error {
    46  	t.messages[level] = append(t.messages[level], s)
    47  	return nil
    48  }
    49  
    50  func TestLog(t *testing.T) {
    51  	out := newTestOutputter(log.Info)
    52  	defer log.SetOutputter(log.SetOutputter(out))
    53  	log.Printf("hello %q", "world")
    54  	if got, want := out.Next(log.Info), `hello "world"`; got != want {
    55  		t.Errorf("got %v, want %v", got, want)
    56  	}
    57  	log.Error.Print(1, 2, 3)
    58  	if got, want := out.Next(log.Error), "1 2 3"; got != want {
    59  		t.Errorf("got %v, want %v", got, want)
    60  	}
    61  	log.Debug.Print("x")
    62  	if got, want := out.Next(log.Debug), ""; got != want {
    63  		t.Errorf("got %v, want %v", got, want)
    64  	}
    65  	if !out.Empty() {
    66  		t.Error("extra messages")
    67  	}
    68  }
    69  
    70  func Example() {
    71  	log.SetOutput(os.Stdout)
    72  	log.SetFlags(0)
    73  	log.Print("hello, world!")
    74  	log.Error.Print("hello from error")
    75  	log.Debug.Print("invisible")
    76  
    77  	// Output:
    78  	// hello, world!
    79  	// hello from error
    80  }