...

Source file src/github.com/cybertec-postgresql/pgwatch/v6/internal/testutil/log.go

Documentation: github.com/cybertec-postgresql/pgwatch/v6/internal/testutil

     1  package testutil
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  	"sync"
     7  	"testing"
     8  
     9  	"github.com/cybertec-postgresql/pgwatch/v6/internal/log"
    10  	"github.com/sirupsen/logrus"
    11  )
    12  
    13  // SafeBuffer is a goroutine-safe string buffer that satisfies io.Writer.
    14  // Use String() to read the accumulated output.
    15  type SafeBuffer struct {
    16  	mu sync.Mutex
    17  	sb strings.Builder
    18  }
    19  
    20  func (b *SafeBuffer) Write(p []byte) (int, error) {
    21  	b.mu.Lock()
    22  	defer b.mu.Unlock()
    23  	return b.sb.Write(p)
    24  }
    25  
    26  // String returns a snapshot of the accumulated log output.
    27  func (b *SafeBuffer) String() string {
    28  	b.mu.Lock()
    29  	defer b.mu.Unlock()
    30  	return b.sb.String()
    31  }
    32  
    33  // NewTestLogger creates a capturing logger at the given level, injects it into
    34  // a context derived from t.Context(), and returns both the context and the
    35  // output buffer. Use the buffer in assertions to verify log output:
    36  //
    37  //	ctx, out := testutil.NewTestLogger(t, logrus.WarnLevel)
    38  //	doSomething(ctx)
    39  //	assert.Contains(t, out.String(), "expected warning")
    40  func NewTestLogger(t *testing.T, level logrus.Level) (context.Context, *SafeBuffer) {
    41  	t.Helper()
    42  	var out SafeBuffer
    43  	l := logrus.New()
    44  	l.SetOutput(&out)
    45  	l.SetLevel(level)
    46  	return log.WithLogger(t.Context(), l), &out
    47  }
    48