github.com/saferwall/pe@v1.5.2/log/global_test.go (about)

     1  package log
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  	"testing"
     9  )
    10  
    11  func TestGlobalLog(t *testing.T) {
    12  	buffer := &bytes.Buffer{}
    13  	SetLogger(NewStdLogger(buffer))
    14  
    15  	testCases := []struct {
    16  		level   Level
    17  		content []interface{}
    18  	}{
    19  		{
    20  			LevelDebug,
    21  			[]interface{}{"test debug"},
    22  		},
    23  		{
    24  			LevelInfo,
    25  			[]interface{}{"test info"},
    26  		},
    27  		{
    28  			LevelInfo,
    29  			[]interface{}{"test %s", "info"},
    30  		},
    31  		{
    32  			LevelWarn,
    33  			[]interface{}{"test warn"},
    34  		},
    35  		{
    36  			LevelError,
    37  			[]interface{}{"test error"},
    38  		},
    39  		{
    40  			LevelError,
    41  			[]interface{}{"test %s", "error"},
    42  		},
    43  	}
    44  
    45  	expected := []string{}
    46  	for _, tc := range testCases {
    47  		msg := fmt.Sprintf(tc.content[0].(string), tc.content[1:]...)
    48  		switch tc.level {
    49  		case LevelDebug:
    50  			Debugf(tc.content[0].(string), tc.content[1:]...)
    51  			expected = append(expected, fmt.Sprintf("%s msg=%s", "DEBUG", msg))
    52  		case LevelInfo:
    53  			Infof(tc.content[0].(string), tc.content[1:]...)
    54  			expected = append(expected, fmt.Sprintf("%s msg=%s", "INFO", msg))
    55  		case LevelWarn:
    56  			Warnf(tc.content[0].(string), tc.content[1:]...)
    57  			expected = append(expected, fmt.Sprintf("%s msg=%s", "WARN", msg))
    58  		case LevelError:
    59  			Errorf(tc.content[0].(string), tc.content[1:]...)
    60  			expected = append(expected, fmt.Sprintf("%s msg=%s", "ERROR", msg))
    61  		}
    62  	}
    63  	expected = append(expected, "")
    64  
    65  	t.Logf("Content: %s", buffer.String())
    66  	if buffer.String() != strings.Join(expected, "\n") {
    67  		t.Errorf("Expected: %s, got: %s", strings.Join(expected, "\n"), buffer.String())
    68  	}
    69  }
    70  
    71  func TestGlobalLogUpdate(t *testing.T) {
    72  	l := &loggerAppliance{}
    73  	l.SetLogger(NewStdLogger(os.Stdout))
    74  	LOG := NewHelper(l)
    75  	LOG.Info("Log to stdout")
    76  
    77  	buffer := &bytes.Buffer{}
    78  	l.SetLogger(NewStdLogger(buffer))
    79  	LOG.Info("Log to buffer")
    80  
    81  	expected := "INFO msg=Log to buffer\n"
    82  	if buffer.String() != expected {
    83  		t.Errorf("Expected: %s, got: %s", expected, buffer.String())
    84  	}
    85  }