blockchain: Mock time.Now for utxo cache tests.

This updates the utxo cache flush tests to use a mock function for
getting the current time.  Without this the flush tests will fail if
the flush happens fast enough for time.Now to not have elapsed any time.
This commit is contained in:
Ryan Staudt 2021-02-25 05:41:22 -06:00 committed by Dave Collins
parent 786c4319c4
commit cfea094400
2 changed files with 16 additions and 3 deletions

View File

@ -121,6 +121,11 @@ type UtxoCache struct {
// are used to measure the overall cache hit ratio.
hits uint64
misses uint64
// timeNow defines the function to use to get the current local time. It
// defaults to time.Now but an alternative function can be provided for
// testing purposes.
timeNow func() time.Time
}
// UtxoCacheConfig is a descriptor which specifies the utxo cache instance
@ -151,6 +156,7 @@ func NewUtxoCache(config *UtxoCacheConfig) *UtxoCache {
maxSize: config.MaxSize,
entries: make(map[wire.OutPoint]*UtxoEntry, uint64(maxEntries)),
lastFlushTime: time.Now(),
timeNow: time.Now,
}
}
@ -556,7 +562,7 @@ func (c *UtxoCache) flush(bestHash *chainhash.Hash, bestHeight uint32, logFlush
// Update the last flush on the cache instance now that the flush has been
// completed.
c.lastFlushHash = *bestHash
c.lastFlushTime = time.Now()
c.lastFlushTime = c.timeNow()
// Update the last eviction height on the cache instance if we evicted just
// now.

View File

@ -975,7 +975,14 @@ func TestMaybeFlush(t *testing.T) {
utxoCache.maxSize = test.maxSize
utxoCache.lastEvictionHeight = test.lastEvictionHeight
utxoCache.lastFlushHash = *test.lastFlushHash
origLastFlushTime := utxoCache.lastFlushTime
// Mock the current time as 1 minute after the last flush time. This allows
// for validating that the last flush time is correctly updated to the
// current time when a flush occurs.
mockedCurrentTime := utxoCache.lastFlushTime.Add(time.Minute)
utxoCache.timeNow = func() time.Time {
return mockedCurrentTime
}
// Add entries specified by the test to the test database.
err := db.Update(func(dbTx database.Tx) error {
@ -1036,7 +1043,7 @@ func TestMaybeFlush(t *testing.T) {
t.Fatalf("%q: unexpected last flush hash -- got %x, want %x", test.name,
utxoCache.lastFlushHash, *test.wantLastFlushHash)
}
updatedLastFlushTime := utxoCache.lastFlushTime != origLastFlushTime
updatedLastFlushTime := utxoCache.lastFlushTime == mockedCurrentTime
if updatedLastFlushTime != test.wantUpdatedLastFlushTime {
t.Fatalf("%q: unexpected updated last flush time -- got %v, want %v",
test.name, updatedLastFlushTime, test.wantUpdatedLastFlushTime)