tlog.app/go/tlog@v0.23.1/context_test.go (about)

     1  package tlog
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"testing"
     7  
     8  	"github.com/nikandfor/assert"
     9  	"github.com/nikandfor/hacked/low"
    10  )
    11  
    12  func TestContextWithSpan(t *testing.T) {
    13  	var buf, bufl low.Buf
    14  	DefaultLogger = New(NewConsoleWriter(&buf, 0))
    15  	DefaultLogger.NewID = testRandID(2)
    16  
    17  	l := New(NewConsoleWriter(&bufl, 0))
    18  	l.NewID = DefaultLogger.NewID
    19  
    20  	id := ID{10, 20}
    21  
    22  	tr := Span{Logger: DefaultLogger, ID: id}
    23  
    24  	ctx := ContextWithSpan(context.Background(), tr)
    25  
    26  	res := SpanFromContext(ctx)
    27  	assert.Equal(t, tr, res)
    28  
    29  	tr = SpawnFromContext(ctx, "spawn_1")
    30  	if assert.NotZero(t, tr) {
    31  		assert.Equal(t, "spawn_1                       _s=2f8282cb  _k=s  _p=0a140000\n", string(buf))
    32  	}
    33  
    34  	//
    35  	ctx = ContextWithSpan(context.Background(), Span{})
    36  
    37  	res = SpanFromContext(ctx)
    38  	assert.Zero(t, res)
    39  
    40  	//
    41  	DefaultLogger = nil
    42  
    43  	tr = Span{Logger: l, ID: id}
    44  
    45  	ctx = ContextWithSpan(context.Background(), tr)
    46  
    47  	res = SpanFromContext(ctx)
    48  	assert.Equal(t, tr, res)
    49  
    50  	tr = SpawnFromContext(ctx, "spawn_2")
    51  	if assert.NotZero(t, tr) {
    52  		assert.Equal(t, "spawn_2                       _s=d967dc28  _k=s  _p=0a140000\n", string(bufl))
    53  	}
    54  }
    55  
    56  func TestContextResetSpan(t *testing.T) {
    57  	defer func(old *Logger) {
    58  		DefaultLogger = old
    59  	}(DefaultLogger)
    60  
    61  	var buf bytes.Buffer
    62  	DefaultLogger = New(NewConsoleWriter(&buf, 0))
    63  	DefaultLogger.NewID = testRandID(3)
    64  
    65  	tr := Start("root")
    66  
    67  	ctx := ContextWithSpan(context.Background(), tr)
    68  
    69  	//
    70  	ctx2 := ContextWithSpan(ctx, tr.V("nope"))
    71  
    72  	tr2 := SpawnFromContext(ctx2, "spawn")
    73  	assert.Zero(t, tr2)
    74  }