github.com/matrixorigin/matrixone@v1.2.0/pkg/perfcounter/context_test.go (about)

     1  // Copyright 2023 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package perfcounter
    16  
    17  import (
    18  	"context"
    19  	"github.com/stretchr/testify/require"
    20  	"testing"
    21  
    22  	"github.com/stretchr/testify/assert"
    23  )
    24  
    25  func TestWithCounterSetFrom(t *testing.T) {
    26  	var c1, c2 CounterSet
    27  	ctx := WithCounterSet(context.Background(), &c1, &c2)
    28  	ctx2 := WithCounterSetFrom(context.Background(), ctx)
    29  	Update(ctx2, func(set *CounterSet) {
    30  		set.DistTAE.Logtail.Entries.Add(1)
    31  	})
    32  	assert.Equal(t, int64(1), c1.DistTAE.Logtail.Entries.Load())
    33  }
    34  
    35  func makeCounterSetArray(cnt int) []*CounterSet {
    36  	var s []*CounterSet
    37  
    38  	for i := 0; i < cnt; i++ {
    39  		s = append(s, new(CounterSet))
    40  	}
    41  
    42  	return s
    43  }
    44  
    45  func BenchmarkWithCounterSetNonNested(b *testing.B) {
    46  	sets := makeCounterSetArray(100)
    47  
    48  	ctx, cancel := context.WithCancel(context.Background())
    49  	defer cancel()
    50  
    51  	for i := 0; i < b.N; i++ {
    52  		WithCounterSet(ctx, sets...)
    53  	}
    54  }
    55  
    56  func BenchmarkWithCounterSetNested(b *testing.B) {
    57  	sets := makeCounterSetArray(100)
    58  
    59  	ctx, cancel := context.WithCancel(context.Background())
    60  	defer cancel()
    61  
    62  	for i := 0; i < b.N; i++ {
    63  		ctx = WithCounterSet(ctx, sets...)
    64  	}
    65  }
    66  
    67  func TestAddDuplicateCounterSetToContext(t *testing.T) {
    68  	cs1 := new(CounterSet)
    69  	cs2 := new(CounterSet)
    70  
    71  	counterSets := CounterSets{}
    72  	counterSets[cs1] = struct{}{}
    73  	counterSets[cs2] = struct{}{}
    74  
    75  	ctx1 := context.WithValue(context.Background(), CtxKeyCounters, counterSets)
    76  
    77  	// storing an existing counter set into ctx
    78  	ctx2 := WithCounterSet(ctx1, cs1)
    79  	require.Equal(t, ctx1, ctx2)
    80  
    81  	// storing a new counter set into ctx
    82  	cs3 := new(CounterSet)
    83  	ctx3 := WithCounterSet(ctx1, cs3)
    84  	require.NotEqual(t, ctx1, ctx3)
    85  }