github.com/nikandfor/tlog@v0.21.5-0.20231108111739-3ef89426a96d/context_test.go (about)

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