github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/pkg/jsonlog/jsonlogbytes_test.go (about)

     1  package jsonlog
     2  
     3  import (
     4  	"bytes"
     5  	"regexp"
     6  	"testing"
     7  )
     8  
     9  func TestJSONLogsMarshalJSONBuf(t *testing.T) {
    10  	logs := map[*JSONLogs]string{
    11  		&JSONLogs{Log: []byte(`"A log line with \\"`)}:           `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":}$`,
    12  		&JSONLogs{Log: []byte("A log line")}:                     `^{\"log\":\"A log line\",\"time\":}$`,
    13  		&JSONLogs{Log: []byte("A log line with \r")}:             `^{\"log\":\"A log line with \\r\",\"time\":}$`,
    14  		&JSONLogs{Log: []byte("A log line with & < >")}:          `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":}$`,
    15  		&JSONLogs{Log: []byte("A log line with utf8 : 🚀 ψ ω β")}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":}$`,
    16  		&JSONLogs{Stream: "stdout"}:                              `^{\"stream\":\"stdout\",\"time\":}$`,
    17  		&JSONLogs{Stream: "stdout", Log: []byte("A log line")}:   `^{\"log\":\"A log line\",\"stream\":\"stdout\",\"time\":}$`,
    18  		&JSONLogs{Created: "time"}:                               `^{\"time\":time}$`,
    19  		&JSONLogs{}:                                              `^{\"time\":}$`,
    20  		// These ones are a little weird
    21  		&JSONLogs{Log: []byte("\u2028 \u2029")}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":}$`,
    22  		&JSONLogs{Log: []byte{0xaF}}:            `^{\"log\":\"\\ufffd\",\"time\":}$`,
    23  		&JSONLogs{Log: []byte{0x7F}}:            `^{\"log\":\"\x7f\",\"time\":}$`,
    24  		// with raw attributes
    25  		&JSONLogs{Log: []byte("A log line"), RawAttrs: []byte(`{"hello":"world","value":1234}`)}: `^{\"log\":\"A log line\",\"attrs\":{\"hello\":\"world\",\"value\":1234},\"time\":}$`,
    26  	}
    27  	for jsonLog, expression := range logs {
    28  		var buf bytes.Buffer
    29  		if err := jsonLog.MarshalJSONBuf(&buf); err != nil {
    30  			t.Fatal(err)
    31  		}
    32  		res := buf.String()
    33  		t.Logf("Result of WriteLog: %q", res)
    34  		logRe := regexp.MustCompile(expression)
    35  		if !logRe.MatchString(res) {
    36  			t.Fatalf("Log line not in expected format [%v]: %q", expression, res)
    37  		}
    38  	}
    39  }