github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/src/log/log_test.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package log
     6  
     7  // These tests are too simple.
     8  
     9  import (
    10  	"bytes"
    11  	"fmt"
    12  	"os"
    13  	"regexp"
    14  	"strings"
    15  	"testing"
    16  	"time"
    17  )
    18  
    19  const (
    20  	Rdate         = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`
    21  	Rtime         = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`
    22  	Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`
    23  	Rline         = `(57|59):` // must update if the calls to l.Printf / l.Print below move
    24  	Rlongfile     = `.*/[A-Za-z0-9_\-]+\.go:` + Rline
    25  	Rshortfile    = `[A-Za-z0-9_\-]+\.go:` + Rline
    26  )
    27  
    28  type tester struct {
    29  	flag    int
    30  	prefix  string
    31  	pattern string // regexp that log output must match; we add ^ and expected_text$ always
    32  }
    33  
    34  var tests = []tester{
    35  	// individual pieces:
    36  	{0, "", ""},
    37  	{0, "XXX", "XXX"},
    38  	{Ldate, "", Rdate + " "},
    39  	{Ltime, "", Rtime + " "},
    40  	{Ltime | Lmicroseconds, "", Rtime + Rmicroseconds + " "},
    41  	{Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time
    42  	{Llongfile, "", Rlongfile + " "},
    43  	{Lshortfile, "", Rshortfile + " "},
    44  	{Llongfile | Lshortfile, "", Rshortfile + " "}, // shortfile overrides longfile
    45  	// everything at once:
    46  	{Ldate | Ltime | Lmicroseconds | Llongfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " "},
    47  	{Ldate | Ltime | Lmicroseconds | Lshortfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " "},
    48  }
    49  
    50  // Test using Println("hello", 23, "world") or using Printf("hello %d world", 23)
    51  func testPrint(t *testing.T, flag int, prefix string, pattern string, useFormat bool) {
    52  	buf := new(bytes.Buffer)
    53  	SetOutput(buf)
    54  	SetFlags(flag)
    55  	SetPrefix(prefix)
    56  	if useFormat {
    57  		Printf("hello %d world", 23)
    58  	} else {
    59  		Println("hello", 23, "world")
    60  	}
    61  	line := buf.String()
    62  	line = line[0 : len(line)-1]
    63  	pattern = "^" + pattern + "hello 23 world$"
    64  	matched, err4 := regexp.MatchString(pattern, line)
    65  	if err4 != nil {
    66  		t.Fatal("pattern did not compile:", err4)
    67  	}
    68  	if !matched {
    69  		t.Errorf("log output should match %q is %q", pattern, line)
    70  	}
    71  	SetOutput(os.Stderr)
    72  }
    73  
    74  func TestAll(t *testing.T) {
    75  	for _, testcase := range tests {
    76  		testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, false)
    77  		testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, true)
    78  	}
    79  }
    80  
    81  func TestOutput(t *testing.T) {
    82  	const testString = "test"
    83  	var b bytes.Buffer
    84  	l := New(&b, "", 0)
    85  	l.Println(testString)
    86  	if expect := testString + "\n"; b.String() != expect {
    87  		t.Errorf("log output should match %q is %q", expect, b.String())
    88  	}
    89  }
    90  
    91  func TestOutputRace(t *testing.T) {
    92  	var b bytes.Buffer
    93  	l := New(&b, "", 0)
    94  	for i := 0; i < 100; i++ {
    95  		go func() {
    96  			l.SetFlags(0)
    97  		}()
    98  		l.Output(0, "")
    99  	}
   100  }
   101  
   102  func TestFlagAndPrefixSetting(t *testing.T) {
   103  	var b bytes.Buffer
   104  	l := New(&b, "Test:", LstdFlags)
   105  	f := l.Flags()
   106  	if f != LstdFlags {
   107  		t.Errorf("Flags 1: expected %x got %x", LstdFlags, f)
   108  	}
   109  	l.SetFlags(f | Lmicroseconds)
   110  	f = l.Flags()
   111  	if f != LstdFlags|Lmicroseconds {
   112  		t.Errorf("Flags 2: expected %x got %x", LstdFlags|Lmicroseconds, f)
   113  	}
   114  	p := l.Prefix()
   115  	if p != "Test:" {
   116  		t.Errorf(`Prefix: expected "Test:" got %q`, p)
   117  	}
   118  	l.SetPrefix("Reality:")
   119  	p = l.Prefix()
   120  	if p != "Reality:" {
   121  		t.Errorf(`Prefix: expected "Reality:" got %q`, p)
   122  	}
   123  	// Verify a log message looks right, with our prefix and microseconds present.
   124  	l.Print("hello")
   125  	pattern := "^Reality:" + Rdate + " " + Rtime + Rmicroseconds + " hello\n"
   126  	matched, err := regexp.Match(pattern, b.Bytes())
   127  	if err != nil {
   128  		t.Fatalf("pattern %q did not compile: %s", pattern, err)
   129  	}
   130  	if !matched {
   131  		t.Error("message did not match pattern")
   132  	}
   133  }
   134  
   135  func TestUTCFlag(t *testing.T) {
   136  	var b bytes.Buffer
   137  	l := New(&b, "Test:", LstdFlags)
   138  	l.SetFlags(Ldate | Ltime | LUTC)
   139  	// Verify a log message looks right in the right time zone. Quantize to the second only.
   140  	now := time.Now().UTC()
   141  	l.Print("hello")
   142  	want := fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n",
   143  		now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
   144  	got := b.String()
   145  	if got == want {
   146  		return
   147  	}
   148  	// It's possible we crossed a second boundary between getting now and logging,
   149  	// so add a second and try again. This should very nearly always work.
   150  	now = now.Add(time.Second)
   151  	want = fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n",
   152  		now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
   153  	if got == want {
   154  		return
   155  	}
   156  	t.Errorf("got %q; want %q", got, want)
   157  }
   158  
   159  func TestEmptyPrintCreatesLine(t *testing.T) {
   160  	var b bytes.Buffer
   161  	l := New(&b, "Header:", LstdFlags)
   162  	l.Print()
   163  	l.Println("non-empty")
   164  	output := b.String()
   165  	if n := strings.Count(output, "Header"); n != 2 {
   166  		t.Errorf("expected 2 headers, got %d", n)
   167  	}
   168  	if n := strings.Count(output, "\n"); n != 2 {
   169  		t.Errorf("expected 2 lines, got %d", n)
   170  	}
   171  }
   172  
   173  func BenchmarkItoa(b *testing.B) {
   174  	dst := make([]byte, 0, 64)
   175  	for i := 0; i < b.N; i++ {
   176  		dst = dst[0:0]
   177  		itoa(&dst, 2015, 4)   // year
   178  		itoa(&dst, 1, 2)      // month
   179  		itoa(&dst, 30, 2)     // day
   180  		itoa(&dst, 12, 2)     // hour
   181  		itoa(&dst, 56, 2)     // minute
   182  		itoa(&dst, 0, 2)      // second
   183  		itoa(&dst, 987654, 6) // microsecond
   184  	}
   185  }
   186  
   187  func BenchmarkPrintln(b *testing.B) {
   188  	const testString = "test"
   189  	var buf bytes.Buffer
   190  	l := New(&buf, "", LstdFlags)
   191  	for i := 0; i < b.N; i++ {
   192  		buf.Reset()
   193  		l.Println(testString)
   194  	}
   195  }
   196  
   197  func BenchmarkPrintlnNoFlags(b *testing.B) {
   198  	const testString = "test"
   199  	var buf bytes.Buffer
   200  	l := New(&buf, "", 0)
   201  	for i := 0; i < b.N; i++ {
   202  		buf.Reset()
   203  		l.Println(testString)
   204  	}
   205  }