github.com/whoyao/protocol@v0.0.0-20230519045905-2d8ace718ca5/utils/timed_version_test.go (about) 1 package utils 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/require" 8 ) 9 10 func TestTimedVersion(t *testing.T) { 11 t.Run("timed versions are monotonic and comparable", func(t *testing.T) { 12 gen := NewDefaultTimedVersionGenerator() 13 tv1 := gen.New() 14 tv2 := gen.New() 15 tv3 := gen.New() 16 17 require.True(t, tv3.After(tv1)) 18 require.True(t, tv3.After(tv2)) 19 require.True(t, tv2.After(tv1)) 20 21 tv2.Update(tv3) 22 require.True(t, tv2.After(tv1)) 23 // tv3 and tv2 are equivalent after update 24 require.False(t, tv3.After(tv2)) 25 26 require.Equal(t, 0, tv1.Compare(tv1)) 27 require.Equal(t, -1, tv1.Compare(tv2)) 28 require.Equal(t, 1, tv2.Compare(tv1)) 29 }) 30 31 t.Run("protobuf roundtrip", func(t *testing.T) { 32 gen := NewDefaultTimedVersionGenerator() 33 tv1 := gen.New() 34 tv2 := NewTimedVersionFromProto(tv1.ToProto()) 35 require.Equal(t, tv1.v.Load(), tv2.v.Load()) 36 }) 37 38 t.Run("from zero time yields epoch version", func(t *testing.T) { 39 gen := NewDefaultTimedVersionGenerator() 40 tv1 := NewTimedVersionFromTime(time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC)) 41 tv2 := gen.New() 42 require.True(t, tv2.After(tv1)) 43 }) 44 45 t.Run("time.Time roundtrip", func(t *testing.T) { 46 ts1 := time.Now().Round(time.Microsecond) 47 tv1 := NewTimedVersionFromTime(ts1) 48 ts2 := tv1.Time() 49 tv2 := NewTimedVersionFromTime(ts2) 50 require.Equal(t, ts1, ts2) 51 require.Equal(t, tv1.v.Load(), tv2.v.Load()) 52 }) 53 }