github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/pdutil/clock_test.go (about)

     1  // Copyright 2021 PingCAP, 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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package pdutil
    15  
    16  import (
    17  	"context"
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/stretchr/testify/require"
    22  	"github.com/tikv/client-go/v2/oracle"
    23  	pd "github.com/tikv/pd/client"
    24  )
    25  
    26  // MockPDClient mocks pd.Client to facilitate unit testing.
    27  type MockPDClient struct {
    28  	pd.Client
    29  }
    30  
    31  // GetTS implements pd.Client.GetTS.
    32  func (m *MockPDClient) GetTS(ctx context.Context) (int64, int64, error) {
    33  	return oracle.GetPhysical(time.Now()), 0, nil
    34  }
    35  
    36  func TestTimeFromPD(t *testing.T) {
    37  	t.Parallel()
    38  	mockPDClient := &MockPDClient{}
    39  	clock, err := NewClock(context.Background(), mockPDClient)
    40  	require.NoError(t, err)
    41  
    42  	go clock.Run(context.Background())
    43  	defer clock.Stop()
    44  	time.Sleep(1 * time.Second)
    45  
    46  	t1 := clock.CurrentTime()
    47  
    48  	time.Sleep(400 * time.Millisecond)
    49  	// assume that the gc safe point updated one hour ago
    50  	t2 := clock.CurrentTime()
    51  	// should return new time
    52  	require.NotEqual(t, t1, t2)
    53  }
    54  
    55  func TestEventTimeAndProcessingTime(t *testing.T) {
    56  	t.Parallel()
    57  
    58  	ctx, cancel := context.WithCancel(context.Background())
    59  	defer cancel()
    60  	mockPDClient := &MockPDClient{}
    61  	clock, err := NewClock(ctx, mockPDClient)
    62  	require.NoError(t, err)
    63  
    64  	// Disable update in test by setting a very long update interval.
    65  	clock.updateInterval = time.Hour
    66  	go clock.Run(ctx)
    67  	defer clock.Stop()
    68  
    69  	sleep := time.Second
    70  	time.Sleep(sleep)
    71  	t1 := clock.CurrentTime()
    72  	now := time.Now()
    73  	require.Nil(t, err)
    74  	require.Less(t, now.Sub(t1), sleep/2)
    75  }