github.com/cloudwego/kitex@v0.9.0/pkg/rpcinfo/stats_util_test.go (about)

     1  /*
     2   * Copyright 2021 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *  http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package rpcinfo
    18  
    19  import (
    20  	"context"
    21  	"testing"
    22  	"time"
    23  
    24  	"github.com/cloudwego/kitex/internal/test"
    25  	"github.com/cloudwego/kitex/pkg/stats"
    26  )
    27  
    28  func TestUtil(t *testing.T) {
    29  	test.Assert(t, CalcEventCostUs(nil, nil) == 0)
    30  
    31  	ri := NewRPCInfo(
    32  		NewEndpointInfo("client", "client_method", nil, nil),
    33  		NewEndpointInfo("server", "server_method", nil, nil),
    34  		NewInvocation("service", "method"),
    35  		NewRPCConfig(),
    36  		NewRPCStats(),
    37  	)
    38  
    39  	// nil context
    40  	var ctx context.Context
    41  	Record(ctx, ri, stats.RPCStart, nil)
    42  	Record(ctx, ri, stats.RPCFinish, nil)
    43  
    44  	st := ri.Stats()
    45  	test.Assert(t, st != nil)
    46  
    47  	s, e := st.GetEvent(stats.RPCStart), st.GetEvent(stats.RPCFinish)
    48  	test.Assert(t, s == nil)
    49  	test.Assert(t, e == nil)
    50  
    51  	// stats disabled
    52  	ctx = context.Background()
    53  	Record(ctx, ri, stats.RPCStart, nil)
    54  	time.Sleep(time.Millisecond)
    55  	Record(ctx, ri, stats.RPCFinish, nil)
    56  
    57  	st = ri.Stats()
    58  	test.Assert(t, st != nil)
    59  
    60  	s, e = st.GetEvent(stats.RPCStart), st.GetEvent(stats.RPCFinish)
    61  	test.Assert(t, s == nil)
    62  	test.Assert(t, e == nil)
    63  
    64  	// stats enabled
    65  	st = ri.Stats()
    66  	st.(interface{ SetLevel(stats.Level) }).SetLevel(stats.LevelBase)
    67  
    68  	Record(ctx, ri, stats.RPCStart, nil)
    69  	time.Sleep(time.Millisecond)
    70  	Record(ctx, ri, stats.RPCFinish, nil)
    71  
    72  	s, e = st.GetEvent(stats.RPCStart), st.GetEvent(stats.RPCFinish)
    73  	test.Assert(t, s != nil, s)
    74  	test.Assert(t, e != nil, e)
    75  	test.Assert(t, CalcEventCostUs(s, e) > 0)
    76  }