github.com/ydb-platform/ydb-go-sdk/v3@v3.89.2/log/context_test.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  	"strconv"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/require"
    10  
    11  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/xtest"
    12  )
    13  
    14  func TestLevelFromContext(t *testing.T) {
    15  	for _, tt := range []struct {
    16  		ctx context.Context //nolint:containedctx
    17  		lvl Level
    18  	}{
    19  		{
    20  			ctx: context.Background(),
    21  			lvl: TRACE,
    22  		},
    23  		{
    24  			ctx: WithLevel(context.Background(), INFO),
    25  			lvl: INFO,
    26  		},
    27  		{
    28  			ctx: WithLevel(WithLevel(context.Background(), ERROR), INFO),
    29  			lvl: INFO,
    30  		},
    31  	} {
    32  		t.Run("", func(t *testing.T) {
    33  			require.Equal(t, tt.lvl, LevelFromContext(tt.ctx))
    34  		})
    35  	}
    36  }
    37  
    38  func TestNamesFromContext(t *testing.T) {
    39  	for _, tt := range []struct {
    40  		ctx   context.Context //nolint:containedctx
    41  		names []string
    42  	}{
    43  		{
    44  			ctx:   context.Background(),
    45  			names: []string{},
    46  		},
    47  		{
    48  			ctx:   WithNames(context.Background(), "a", "b"),
    49  			names: []string{"a", "b"},
    50  		},
    51  		{
    52  			ctx:   WithNames(WithNames(context.Background(), "a", "b"), "c", "d"),
    53  			names: []string{"a", "b", "c", "d"},
    54  		},
    55  	} {
    56  		t.Run("", func(t *testing.T) {
    57  			require.Equal(t, tt.names, NamesFromContext(tt.ctx))
    58  		})
    59  	}
    60  }
    61  
    62  func TestWithNamesRaceRegression(t *testing.T) {
    63  	count := 100
    64  	xtest.TestManyTimes(t, func(t testing.TB) {
    65  		ctx := WithNames(context.Background(), "test")
    66  		ctx = WithNames(ctx, "test")
    67  		ctx = WithNames(ctx, "test")
    68  		res := make([]context.Context, count)
    69  
    70  		start := make(chan bool)
    71  		finished := make(chan bool)
    72  		for i := 0; i < count; i++ {
    73  			go func(index int) {
    74  				<-start
    75  				res[index] = WithNames(ctx, strconv.Itoa(index))
    76  				finished <- true
    77  			}(i)
    78  		}
    79  
    80  		time.Sleep(time.Microsecond)
    81  		close(start)
    82  
    83  		for i := 0; i < count; i++ {
    84  			<-finished
    85  		}
    86  
    87  		for i := 0; i < count; i++ {
    88  			expected := []string{"test", "test", "test", strconv.Itoa(i)}
    89  			require.Equal(t, expected, NamesFromContext(res[i]))
    90  		}
    91  	})
    92  }