Black Lives Matter. Support the Equal Justice Initiative.

Source file src/log/log_test.go

Documentation: log

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

View as plain text