Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json: AppendTimeLayout should add field separators #799

Merged
merged 1 commit into from Mar 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions zapcore/json_encoder.go
Expand Up @@ -267,6 +267,7 @@ func (enc *jsonEncoder) AppendString(val string) {
}

func (enc *jsonEncoder) AppendTimeLayout(time time.Time, layout string) {
enc.addElementSeparator()
enc.buf.AppendByte('"')
enc.buf.AppendTime(time, layout)
enc.buf.AppendByte('"')
Expand Down
52 changes: 52 additions & 0 deletions zapcore/json_encoder_impl_test.go
Expand Up @@ -385,6 +385,58 @@ func TestJSONEncoderArrays(t *testing.T) {
}
}

func TestJSONEncoderTimeArrays(t *testing.T) {
times := []time.Time{
time.Unix(1008720000, 0).UTC(), // 2001-12-19
time.Unix(1040169600, 0).UTC(), // 2002-12-18
time.Unix(1071619200, 0).UTC(), // 2003-12-17
}

tests := []struct {
desc string
encoder TimeEncoder
want string
}{
{
desc: "epoch",
encoder: EpochTimeEncoder,
want: `[1008720000,1040169600,1071619200]`,
},
{
desc: "epoch millis",
encoder: EpochMillisTimeEncoder,
want: `[1008720000000,1040169600000,1071619200000]`,
},
{
desc: "iso8601",
encoder: ISO8601TimeEncoder,
want: `["2001-12-19T00:00:00.000Z","2002-12-18T00:00:00.000Z","2003-12-17T00:00:00.000Z"]`,
},
{
desc: "rfc3339",
encoder: RFC3339TimeEncoder,
want: `["2001-12-19T00:00:00Z","2002-12-18T00:00:00Z","2003-12-17T00:00:00Z"]`,
},
}

for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
cfg := _defaultEncoderConfig
cfg.EncodeTime = tt.encoder

enc := &jsonEncoder{buf: bufferpool.Get(), EncoderConfig: &cfg}
err := enc.AddArray("array", ArrayMarshalerFunc(func(arr ArrayEncoder) error {
for _, time := range times {
arr.AppendTime(time)
}
return nil
}))
assert.NoError(t, err)
assert.Equal(t, `"array":`+tt.want, enc.buf.String())
})
}
}

func assertJSON(t *testing.T, expected string, enc *jsonEncoder) {
assert.Equal(t, expected, enc.buf.String(), "Encoded JSON didn't match expectations.")
}
Expand Down