github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/timeutil/latency_test.go (about)

     1  package timeutil
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestLatencyRecorder(t *testing.T) {
    13  	lRec := NewLatencyRecorder()
    14  	time.Sleep(10 * time.Millisecond)
    15  	lRec.Mark("op1")
    16  	time.Sleep(10 * time.Millisecond)
    17  	lRec.Mark("op2")
    18  	lRec.MarkFromStartTime("op3")
    19  	lRec.MarkWithStartTime("op4", time.Now().Add(-time.Second))
    20  	time.Sleep(time.Millisecond)
    21  
    22  	var buf bytes.Buffer
    23  	latencyMap := lRec.GetLatencyMap()
    24  	logStr := lRec.Format()
    25  	_, err := lRec.WriteTo(&buf)
    26  	require.Nil(t, err)
    27  	assert.GreaterOrEqual(t, latencyMap["op1"], 10*time.Millisecond)
    28  	assert.GreaterOrEqual(t, latencyMap["op2"], 10*time.Millisecond)
    29  	assert.Less(t, latencyMap["op2"], 20*time.Millisecond)
    30  	assert.GreaterOrEqual(t, latencyMap["op3"], 20*time.Millisecond)
    31  	assert.GreaterOrEqual(t, latencyMap["op4"], time.Second)
    32  	assert.Greater(t, latencyMap["total"], 20*time.Millisecond)
    33  	assert.Regexp(t, `op1=\d+`, logStr)
    34  	assert.Regexp(t, `\s+op2=\d+`, logStr)
    35  	assert.Regexp(t, `\s+op3=\d+`, logStr)
    36  	assert.Regexp(t, `\s+op4=\d{4}`, logStr)
    37  	assert.Regexp(t, `\s+total=\d+`, logStr)
    38  
    39  	lRec.Reset()
    40  	latencyMap = lRec.GetLatencyMap()
    41  	assert.Len(t, latencyMap, 1)
    42  	assert.Contains(t, latencyMap, "total")
    43  }