github.com/turingchain2020/turingchain@v1.1.21/common/ntp_test.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package common
     6  
     7  import (
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  var NtpHosts = []string{
    15  	"time.windows.com:123",
    16  	"ntp.ubuntu.com:123",
    17  	"pool.ntp.org:123",
    18  	"cn.pool.ntp.org:123",
    19  	"time.apple.com:123",
    20  }
    21  
    22  // 在单元测试中对网络时间和本地时间进行单元测试的功能是没有意义的
    23  // 只有在实际运行过程中,通过网络时间来纠正本地时间
    24  // 本测试用例有概率导致误差大于1秒从而让测试用例运行失败
    25  func TestGetRealTime(t *testing.T) {
    26  	hosts := NtpHosts
    27  	nettime := GetRealTimeRetry(hosts, 10)
    28  	now := time.Now()
    29  	//get nettime error, ignore
    30  	if nettime.IsZero() {
    31  		return
    32  	}
    33  	nettime2 := GetRealTimeRetry(hosts, 10)
    34  	//get nettime error, ignore
    35  	delt := time.Since(now)
    36  	if nettime2.IsZero() {
    37  		return
    38  	}
    39  	assert.Equal(t, nettime2.Sub(nettime)/time.Second, delt/time.Second)
    40  }
    41  
    42  func TestSubList(t *testing.T) {
    43  	sub := maxSubList([]time.Duration{1, 2, 3, 10, 21, 22, 23, 24, 35}, time.Duration(10))
    44  	assert.Equal(t, len(sub), 4)
    45  	assert.Equal(t, sub[0], time.Duration(1))
    46  
    47  	sub = maxSubList([]time.Duration{2, 3, 10, 21, 22, 23, 24, 35}, time.Duration(10))
    48  	assert.Equal(t, len(sub), 4)
    49  	assert.Equal(t, sub[0], time.Duration(21))
    50  
    51  	sub = maxSubList([]time.Duration{2, 3, 10, 21, 22, 23, 24}, time.Duration(10))
    52  	assert.Equal(t, len(sub), 4)
    53  	assert.Equal(t, sub[0], time.Duration(21))
    54  }