github.com/AndrienkoAleksandr/go@v0.0.19/src/log/slog/internal/benchmarks/handlers_test.go (about)

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