Fix mid computation in timesource

Additionally improved test suite
This commit is contained in:
Dmitry Shulyak 2018-05-15 18:59:25 +03:00 committed by Dmitry Shulyak
parent f5a8be08de
commit ee60b7e727
2 changed files with 22 additions and 3 deletions

View File

@ -97,7 +97,7 @@ func computeOffset(timeQuery ntpQuery, servers []string, allowedFailures int) (t
sort.SliceStable(offsets, func(i, j int) bool {
return offsets[i] > offsets[j]
})
mid := len(servers) / 2
mid := len(offsets) / 2
if len(offsets)%2 == 0 {
return (offsets[mid-1] + offsets[mid]) / 2, nil
}

View File

@ -17,7 +17,7 @@ const (
// we don't user real servers for tests, but logic depends on
// actual number of involved NTP servers.
var mockedServers = []string{"ntp1", "ntp2", "ntp3"}
var mockedServers = []string{"ntp1", "ntp2", "ntp3", "ntp4"}
type testCase struct {
description string
@ -51,6 +51,7 @@ func newTestCases() []*testCase {
{Offset: 10 * time.Second},
{Offset: 10 * time.Second},
{Offset: 10 * time.Second},
{Offset: 10 * time.Second},
},
expected: 10 * time.Second,
},
@ -60,6 +61,7 @@ func newTestCases() []*testCase {
responses: []queryResponse{
{Offset: 10 * time.Second},
{Offset: 20 * time.Second},
{Offset: 20 * time.Second},
{Offset: 30 * time.Second},
},
expected: 20 * time.Second,
@ -80,6 +82,7 @@ func newTestCases() []*testCase {
{Offset: 10 * time.Second},
{Error: errors.New("test")},
{Offset: 30 * time.Second},
{Offset: 30 * time.Second},
},
expected: time.Duration(0),
expectError: true,
@ -91,6 +94,7 @@ func newTestCases() []*testCase {
{Error: errors.New("test 1")},
{Error: errors.New("test 2")},
{Error: errors.New("test 3")},
{Error: errors.New("test 3")},
},
expected: time.Duration(0),
expectError: true,
@ -102,6 +106,7 @@ func newTestCases() []*testCase {
responses: []queryResponse{
{Offset: 10 * time.Second},
{Error: errors.New("test")},
{Offset: 20 * time.Second},
{Offset: 30 * time.Second},
},
expected: 20 * time.Second,
@ -114,6 +119,7 @@ func newTestCases() []*testCase {
{Offset: 10 * time.Second},
{Error: errors.New("test")},
{Error: errors.New("test")},
{Error: errors.New("test")},
},
expected: time.Duration(0),
expectError: true,
@ -121,15 +127,28 @@ func newTestCases() []*testCase {
{
description: "AllFailed",
servers: mockedServers,
allowedFailures: 3,
allowedFailures: 4,
responses: []queryResponse{
{Error: errors.New("test")},
{Error: errors.New("test")},
{Error: errors.New("test")},
{Error: errors.New("test")},
},
expected: time.Duration(0),
expectError: true,
},
{
description: "HalfTolerable",
servers: mockedServers,
allowedFailures: 2,
responses: []queryResponse{
{Offset: 10 * time.Second},
{Offset: 20 * time.Second},
{Error: errors.New("test")},
{Error: errors.New("test")},
},
expected: 15 * time.Second,
},
}
}