github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/timed_version_test.go (about)

     1  // Copyright 2023 LiveKit, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package utils
    16  
    17  import (
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/stretchr/testify/require"
    22  )
    23  
    24  func TestTimedVersion(t *testing.T) {
    25  	t.Run("timed versions are monotonic and comparable", func(t *testing.T) {
    26  		gen := NewDefaultTimedVersionGenerator()
    27  		tv1 := gen.Next()
    28  		tv2 := gen.Next()
    29  		tv3 := gen.Next()
    30  
    31  		require.True(t, tv3.After(tv1))
    32  		require.True(t, tv3.After(tv2))
    33  		require.True(t, tv2.After(tv1))
    34  
    35  		tv2.Update(tv3)
    36  		require.True(t, tv2.After(tv1))
    37  		// tv3 and tv2 are equivalent after update
    38  		require.False(t, tv3.After(tv2))
    39  
    40  		require.Equal(t, 0, tv1.Compare(tv1))
    41  		require.Equal(t, -1, tv1.Compare(tv2))
    42  		require.Equal(t, 1, tv2.Compare(tv1))
    43  	})
    44  
    45  	t.Run("protobuf roundtrip", func(t *testing.T) {
    46  		gen := NewDefaultTimedVersionGenerator()
    47  		tv1 := gen.Next()
    48  		tv2 := TimedVersionFromProto(tv1.ToProto())
    49  		require.Equal(t, tv1, tv2)
    50  	})
    51  
    52  	t.Run("from zero time yields epoch version", func(t *testing.T) {
    53  		gen := NewDefaultTimedVersionGenerator()
    54  		tv1 := TimedVersionFromTime(time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC))
    55  		tv2 := gen.Next()
    56  		require.True(t, tv2.After(tv1))
    57  	})
    58  
    59  	t.Run("time.Time roundtrip", func(t *testing.T) {
    60  		ts1 := time.Now().Round(time.Microsecond)
    61  		tv1 := TimedVersionFromTime(ts1)
    62  		ts2 := tv1.Time()
    63  		tv2 := TimedVersionFromTime(ts2)
    64  		require.Equal(t, ts1, ts2)
    65  		require.Equal(t, tv1, tv2)
    66  	})
    67  
    68  	t.Run("timed version from nil is zero", func(t *testing.T) {
    69  		require.True(t, TimedVersionFromProto(nil).IsZero())
    70  	})
    71  }