From 6af93023744264c2d49de0d21588604c62d0b60c Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Sat, 11 Oct 2014 18:03:14 -0500 Subject: [PATCH] More false positive prevention in new time tests. This commit extends the same logic in the previous commit to the comparison of offsets returned from the median time source in the tests. In particular it modifies the tests to allow for the offsets to differ by a second due to a boundary condition to prevent false positives. --- mediantime.go | 3 ++- mediantime_test.go | 13 +++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/mediantime.go b/mediantime.go index b11fcd341..1026edc96 100644 --- a/mediantime.go +++ b/mediantime.go @@ -118,7 +118,8 @@ func (m *medianTime) AddTimeSample(sourceID string, timeVal time.Time) { // of offsets while respecting the maximum number of allowed entries by // replacing the oldest entry with the new entry once the maximum number // of entries is reached. - offsetSecs := int64(time.Now().Sub(timeVal).Seconds()) + now := time.Unix(time.Now().Unix(), 0) + offsetSecs := int64(now.Sub(timeVal).Seconds()) numOffsets := len(m.offsets) if numOffsets == maxMedianTimeEntries && maxMedianTimeEntries > 0 { m.offsets = m.offsets[1:] diff --git a/mediantime_test.go b/mediantime_test.go index 98e720c7e..d191c9c9a 100644 --- a/mediantime_test.go +++ b/mediantime_test.go @@ -62,8 +62,8 @@ func TestMedianTime(t *testing.T) { filter := btcchain.NewMedianTime() for j, offset := range test.in { id := strconv.Itoa(j) - tOffset := time.Now().Add(time.Duration(offset) * - time.Second) + now := time.Unix(time.Now().Unix(), 0) + tOffset := now.Add(time.Duration(offset) * time.Second) filter.AddTimeSample(id, tOffset) // Ensure the duplicate IDs are ignored. @@ -76,11 +76,16 @@ func TestMedianTime(t *testing.T) { } } + // Since it is possible that the time.Now call in AddTimeSample + // and the time.Now calls here in the tests will be off by one + // second, allow a fudge factor to compensate. gotOffset := filter.Offset() wantOffset := time.Duration(test.wantOffset) * time.Second - if gotOffset != wantOffset { + wantOffset2 := time.Duration(test.wantOffset-1) * time.Second + if gotOffset != wantOffset && gotOffset != wantOffset2 { t.Errorf("Offset #%d: unexpected offset -- got %v, "+ - "want %v", i, gotOffset, wantOffset) + "want %v or %v", i, gotOffset, wantOffset, + wantOffset2) continue }