1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
19 var testTime = time.Date(2000, 1, 2, 3, 4, 5, 0, time.UTC)
21 func TestTextHandler(t *testing.T) {
22 for _, test := range []struct {
25 wantKey, wantVal string
34 String("x = y", `qu"o`),
39 Any("name", name{"Ren", "Hoek"}),
40 `name`, `"Hoek, Ren"`,
44 Any("x", &struct{ A, b int }{A: 1, b: 2}),
49 Any("t", text{"abc"}),
50 `t`, `"text{\"abc\"}"`,
53 "TextMarshaler error",
55 `t`, `"!ERROR:text: empty string"`,
63 t.Run(test.name, func(t *testing.T) {
64 for _, opts := range []struct {
68 modKey func(string) string
73 `time=2000-01-02T03:04:05.000Z level=INFO msg="a message"`,
74 func(s string) string { return s },
78 HandlerOptions{ReplaceAttr: upperCaseKey},
79 `TIME=2000-01-02T03:04:05.000Z LEVEL=INFO MSG="a message"`,
83 t.Run(opts.name, func(t *testing.T) {
85 h := NewTextHandler(&buf, &opts.opts)
86 r := NewRecord(testTime, LevelInfo, "a message", 0)
88 if err := h.Handle(context.Background(), r); err != nil {
92 // Remove final newline.
93 got = got[:len(got)-1]
94 want := opts.wantPrefix + " " + opts.modKey(test.wantKey) + "=" + test.wantVal
96 t.Errorf("\ngot %s\nwant %s", got, want)
104 // for testing fmt.Sprint
109 func (n name) String() string { return n.Last + ", " + n.First }
111 // for testing TextMarshaler
116 func (t text) String() string { return t.s } // should be ignored
118 func (t text) MarshalText() ([]byte, error) {
120 return nil, errors.New("text: empty string")
122 return []byte(fmt.Sprintf("text{%q}", t.s)), nil
125 func TestTextHandlerPreformatted(t *testing.T) {
127 var h Handler = NewTextHandler(&buf, nil)
128 h = h.WithAttrs([]Attr{Duration("dur", time.Minute), Bool("b", true)})
129 // Also test omitting time.
130 r := NewRecord(time.Time{}, 0 /* 0 Level is INFO */, "m", 0)
131 r.AddAttrs(Int("a", 1))
132 if err := h.Handle(context.Background(), r); err != nil {
135 got := strings.TrimSuffix(buf.String(), "\n")
136 want := `level=INFO msg=m dur=1m0s b=true a=1`
138 t.Errorf("got %s, want %s", got, want)
142 func TestTextHandlerAlloc(t *testing.T) {
143 testenv.SkipIfOptimizationOff(t)
144 r := NewRecord(time.Now(), LevelInfo, "msg", 0)
145 for i := 0; i < 10; i++ {
146 r.AddAttrs(Int("x = y", i))
148 var h Handler = NewTextHandler(io.Discard, nil)
149 wantAllocs(t, 0, func() { h.Handle(context.Background(), r) })
152 r.AddAttrs(Group("g", Int("a", 1)))
153 wantAllocs(t, 0, func() { h.Handle(context.Background(), r) })
156 func TestNeedsQuoting(t *testing.T) {
157 for _, test := range []struct {
169 got := needsQuoting(test.in)
170 if got != test.want {
171 t.Errorf("%q: got %t, want %t", test.in, got, test.want)