Source file src/log/slog/internal/benchmarks/handlers_test.go

     1  // Copyright 2023 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.
     4  
     5  package benchmarks
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"log/slog"
    11  	"slices"
    12  	"testing"
    13  )
    14  
    15  func TestHandlers(t *testing.T) {
    16  	ctx := context.Background()
    17  	r := slog.NewRecord(testTime, slog.LevelInfo, testMessage, 0)
    18  	r.AddAttrs(testAttrs...)
    19  	t.Run("text", func(t *testing.T) {
    20  		var b bytes.Buffer
    21  		h := newFastTextHandler(&b)
    22  		if err := h.Handle(ctx, r); err != nil {
    23  			t.Fatal(err)
    24  		}
    25  		got := b.String()
    26  		if got != wantText {
    27  			t.Errorf("\ngot  %q\nwant %q", got, wantText)
    28  		}
    29  	})
    30  	t.Run("async", func(t *testing.T) {
    31  		h := newAsyncHandler()
    32  		if err := h.Handle(ctx, r); err != nil {
    33  			t.Fatal(err)
    34  		}
    35  		got := h.ringBuffer[0]
    36  		if !got.Time.Equal(r.Time) || !slices.EqualFunc(attrSlice(got), attrSlice(r), slog.Attr.Equal) {
    37  			t.Errorf("got %+v, want %+v", got, r)
    38  		}
    39  	})
    40  }
    41  
    42  func attrSlice(r slog.Record) []slog.Attr {
    43  	var as []slog.Attr
    44  	r.Attrs(func(a slog.Attr) bool { as = append(as, a); return true })
    45  	return as
    46  }
    47  

View as plain text