github.com/grange74/docker@v1.6.0-rc3/pkg/jsonlog/jsonlog_test.go (about)

     1  package jsonlog
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"io/ioutil"
     7  	"regexp"
     8  	"strings"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/docker/docker/pkg/timeutils"
    13  )
    14  
    15  func TestWriteLog(t *testing.T) {
    16  	var buf bytes.Buffer
    17  	e := json.NewEncoder(&buf)
    18  	testLine := "Line that thinks that it is log line from docker\n"
    19  	for i := 0; i < 30; i++ {
    20  		e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
    21  	}
    22  	w := bytes.NewBuffer(nil)
    23  	format := timeutils.RFC3339NanoFixed
    24  	if err := WriteLog(&buf, w, format); err != nil {
    25  		t.Fatal(err)
    26  	}
    27  	res := w.String()
    28  	t.Logf("Result of WriteLog: %q", res)
    29  	lines := strings.Split(strings.TrimSpace(res), "\n")
    30  	if len(lines) != 30 {
    31  		t.Fatalf("Must be 30 lines but got %d", len(lines))
    32  	}
    33  	// 30+ symbols, five more can come from system timezone
    34  	logRe := regexp.MustCompile(`.{30,} Line that thinks that it is log line from docker`)
    35  	for _, l := range lines {
    36  		if !logRe.MatchString(l) {
    37  			t.Fatalf("Log line not in expected format: %q", l)
    38  		}
    39  	}
    40  }
    41  
    42  func BenchmarkWriteLog(b *testing.B) {
    43  	var buf bytes.Buffer
    44  	e := json.NewEncoder(&buf)
    45  	testLine := "Line that thinks that it is log line from docker\n"
    46  	for i := 0; i < 30; i++ {
    47  		e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
    48  	}
    49  	r := bytes.NewReader(buf.Bytes())
    50  	w := ioutil.Discard
    51  	format := timeutils.RFC3339NanoFixed
    52  	b.SetBytes(int64(r.Len()))
    53  	b.ResetTimer()
    54  	for i := 0; i < b.N; i++ {
    55  		if err := WriteLog(r, w, format); err != nil {
    56  			b.Fatal(err)
    57  		}
    58  		b.StopTimer()
    59  		r.Seek(0, 0)
    60  		b.StartTimer()
    61  	}
    62  }