github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/infra/logid/logid_v1_test.go (about)

     1  package logid
     2  
     3  import (
     4  	"math"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestV1Gen(t *testing.T) {
    12  	testV1Gen := NewV1Gen()
    13  
    14  	now := time.Now().UnixMilli()
    15  	machineID := string(testV1Gen.machineID[:])
    16  
    17  	gotLogId := testV1Gen.Gen()
    18  	assert.Len(t, gotLogId, v1Length)
    19  
    20  	info := Decode(gotLogId)
    21  	assert.True(t, info.Valid())
    22  	assert.Equal(t, byte(v1Version), info.Version())
    23  	assert.True(t, math.Abs(float64(info.(V1Info).Time().UnixMilli()-now)) <= 1)
    24  	assert.Equal(t, machineID, info.(V1Info).MachineID())
    25  	assert.Contains(t, info.String(), machineID)
    26  
    27  	gotLogId2 := testV1Gen.Gen()
    28  	info2 := Decode(gotLogId2)
    29  	assert.True(t, info2.Valid())
    30  	assert.NotEqual(t, info.(V1Info).Random(), info2.(V1Info).Random())
    31  	assert.Equal(t, info.(*v1Info).machineID, info2.(*v1Info).machineID)
    32  
    33  	info3 := Decode("1DAOLKWQALEKRALK")
    34  	assert.False(t, info3.Valid())
    35  	assert.Equal(t, "0|invalid", info3.String())
    36  }
    37  
    38  func BenchmarkV1Gen(b *testing.B) {
    39  	gen := NewV1Gen()
    40  	id1 := gen.Gen()
    41  
    42  	b.Run("generate", func(b *testing.B) {
    43  		b.ReportAllocs()
    44  		for i := 0; i < b.N; i++ {
    45  			_ = gen.Gen()
    46  		}
    47  	})
    48  
    49  	b.Run("decode", func(b *testing.B) {
    50  		b.ReportAllocs()
    51  		for i := 0; i < b.N; i++ {
    52  			_ = Decode(id1)
    53  		}
    54  	})
    55  }