trpc.group/trpc-go/trpc-go@v1.0.3/metrics/timer_test.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package metrics_test
    15  
    16  import (
    17  	"testing"
    18  	"time"
    19  
    20  	"trpc.group/trpc-go/trpc-go/metrics"
    21  )
    22  
    23  // 这里 timer 的误差精度设定为 1s,通过 time.sleep 来打桩模拟业务操作,测试 timer 的工作效果
    24  func Test_timer_Record(t *testing.T) {
    25  
    26  	precision := time.Second
    27  
    28  	tests := []struct {
    29  		name string
    30  		wait time.Duration
    31  	}{
    32  		{"timer-1us", time.Microsecond},
    33  		{"timer-10us", time.Microsecond * 10},
    34  		{"timer-1ms", time.Millisecond},
    35  		{"timer-10ms", time.Millisecond * 10},
    36  		{"timer-1s", time.Second},
    37  		{"timer-2s", time.Second * 2},
    38  	}
    39  	for _, tt := range tests {
    40  		t.Run(tt.name, func(t *testing.T) {
    41  			tm := metrics.Timer(tt.name)
    42  			// do something
    43  			time.Sleep(tt.wait)
    44  			passed := tm.Record()
    45  			deviation := passed - tt.wait
    46  			if !(passed >= tt.wait && deviation <= precision) {
    47  				t.Fatalf("timer record duration, want = %v, got = %v, deviation = %v",
    48  					tt.wait, passed, deviation)
    49  			} else {
    50  				t.Logf("timer record duration, want = %v, got = %v, deviation = %v",
    51  					tt.wait, passed, deviation)
    52  			}
    53  		})
    54  	}
    55  }