github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/timeutil/stopwatch_test.go (about) 1 // Copyright 2019 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package timeutil 12 13 import ( 14 "testing" 15 "time" 16 17 "github.com/stretchr/testify/require" 18 ) 19 20 // TestStopWatchStart makes sure that consequent calls to Start do not reset 21 // the internal startedAt time. 22 func TestStopWatchStart(t *testing.T) { 23 timeSource := NewTestTimeSource() 24 w := newStopWatch(timeSource.Now) 25 26 w.Start() 27 timeSource.Advance() 28 w.Start() 29 timeSource.Advance() 30 w.Stop() 31 32 expected, actual := timeSource.Elapsed(), w.Elapsed() 33 require.Equal(t, expected, actual) 34 } 35 36 // TestStopWatchStop makes sure that only the first call to Stop changes the 37 // state of the stop watch. 38 func TestStopWatchStop(t *testing.T) { 39 timeSource := NewTestTimeSource() 40 w := newStopWatch(timeSource.Now) 41 42 w.Start() 43 timeSource.Advance() 44 w.Stop() 45 46 expected, actual := timeSource.Elapsed(), w.Elapsed() 47 require.Equal(t, expected, actual) 48 49 timeSource.Advance() 50 w.Stop() 51 require.Equal(t, actual, w.Elapsed(), "consequent call to StopWatch.Stop changed the elapsed time") 52 } 53 54 // TestStopWatchElapsed makes sure that the stop watch records the elapsed time 55 // correctly. 56 func TestStopWatchElapsed(t *testing.T) { 57 timeSource := NewTestTimeSource() 58 w := newStopWatch(timeSource.Now) 59 expected := time.Duration(10) 60 61 w.Start() 62 for i := int64(0); i < int64(expected); i++ { 63 timeSource.Advance() 64 } 65 w.Stop() 66 67 require.Equal(t, expected, w.Elapsed()) 68 }