File: zap_encoders_test.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20230522.2e198f4-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 6,404 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 26
file content (60 lines) | stat: -rw-r--r-- 1,419 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package zap_benchmarks

import (
	"fmt"
	"strings"
	"testing"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"golang.org/x/exp/slog"
	slogbench "golang.org/x/exp/slog/benchmarks"
)

func TestEncoders(t *testing.T) {
	entry := zapcore.Entry{Time: slogbench.TestTime, Message: slogbench.TestMessage}
	fields := attrsToFields(slogbench.TestAttrs)
	t.Run("text", func(t *testing.T) {
		te := newFastTextEncoder()
		defer tePool.Put(te)
		buf, err := te.EncodeEntry(entry, fields)
		if err != nil {
			t.Fatal(err)
		}
		defer buf.Free()
		got := strings.ToLower(buf.String())
		want := strings.ToLower(slogbench.WantText)
		if got != want {
			t.Errorf("\ngot  %s\nwant %s", got, want)
		}
	})
}

func attrsToFields(attrs []slog.Attr) []zap.Field {
	var fields []zap.Field
	for _, a := range slogbench.TestAttrs {
		var f zap.Field
		k := a.Key
		v := a.Value
		switch v.Kind() {
		case slog.KindString:
			f = zap.String(k, v.String())
		case slog.KindInt64:
			f = zap.Int64(k, v.Int64())
		case slog.KindDuration:
			f = zap.Duration(k, v.Duration())
		case slog.KindTime:
			f = zap.Time(k, v.Time())
		case slog.KindAny:
			f = zap.Any(k, v)
		default:
			panic(fmt.Sprintf("unknown kind %d", v.Kind()))
		}
		fields = append(fields, f)
	}
	return fields
}