github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/daemon/logger/jsonfilelog/jsonlog/jsonlogbytes_test.go (about) 1 package jsonlog // import "github.com/docker/docker/daemon/logger/jsonfilelog/jsonlog" 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "regexp" 8 "testing" 9 "time" 10 11 "gotest.tools/v3/assert" 12 ) 13 14 func TestJSONLogsMarshalJSONBuf(t *testing.T) { 15 logs := map[*JSONLogs]string{ 16 {Log: []byte(`"A log line with \\"`)}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":`, 17 {Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"time\":`, 18 {Log: []byte("A log line with \r")}: `^{\"log\":\"A log line with \\r\",\"time\":`, 19 {Log: []byte("A log line with & < >")}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":`, 20 {Log: []byte("A log line with utf8 : 🚀 ψ ω β")}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":`, 21 {Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":`, 22 {Stream: "stdout", Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"stream\":\"stdout\",\"time\":`, 23 {Created: time.Date(2017, 9, 1, 1, 1, 1, 1, time.UTC)}: `^{\"time\":"2017-09-01T01:01:01.000000001Z"}$`, 24 25 {}: `^{\"time\":"0001-01-01T00:00:00Z"}$`, 26 // These ones are a little weird 27 {Log: []byte("\u2028 \u2029")}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":`, 28 {Log: []byte{0xaF}}: `^{\"log\":\"\\ufffd\",\"time\":`, 29 {Log: []byte{0x7F}}: `^{\"log\":\"\x7f\",\"time\":`, 30 // with raw attributes 31 {Log: []byte("A log line"), RawAttrs: []byte(`{"hello":"world","value":1234}`)}: `^{\"log\":\"A log line\",\"attrs\":{\"hello\":\"world\",\"value\":1234},\"time\":`, 32 // with Tag set 33 {Log: []byte("A log line with tag"), RawAttrs: []byte(`{"hello":"world","value":1234}`)}: `^{\"log\":\"A log line with tag\",\"attrs\":{\"hello\":\"world\",\"value\":1234},\"time\":`, 34 } 35 for jsonLog, expression := range logs { 36 var buf bytes.Buffer 37 err := jsonLog.MarshalJSONBuf(&buf) 38 assert.NilError(t, err) 39 40 assert.Assert(t, regexP(buf.String(), expression)) 41 assert.NilError(t, json.Unmarshal(buf.Bytes(), &map[string]interface{}{})) 42 } 43 } 44 45 func regexP(value string, pattern string) func() (bool, string) { 46 return func() (bool, string) { 47 re := regexp.MustCompile(pattern) 48 msg := fmt.Sprintf("%q did not match pattern %q", value, pattern) 49 return re.MatchString(value), msg 50 } 51 }