src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

time.go (1916B)


      1 package sdk
      2 
      3 import (
      4 	"context"
      5 	"time"
      6 )
      7 
      8 func init() {
      9 	NowTime = time.Now
     10 	Sleep = time.Sleep
     11 	SleepWithContext = sleepWithContext
     12 }
     13 
     14 // NowTime is a value for getting the current time. This value can be overridden
     15 // for testing mocking out current time.
     16 var NowTime func() time.Time
     17 
     18 // Sleep is a value for sleeping for a duration. This value can be overridden
     19 // for testing and mocking out sleep duration.
     20 var Sleep func(time.Duration)
     21 
     22 // SleepWithContext will wait for the timer duration to expire, or the context
     23 // is canceled. Which ever happens first. If the context is canceled the Context's
     24 // error will be returned.
     25 //
     26 // This value can be overridden for testing and mocking out sleep duration.
     27 var SleepWithContext func(context.Context, time.Duration) error
     28 
     29 // sleepWithContext will wait for the timer duration to expire, or the context
     30 // is canceled. Which ever happens first. If the context is canceled the
     31 // Context's error will be returned.
     32 func sleepWithContext(ctx context.Context, dur time.Duration) error {
     33 	t := time.NewTimer(dur)
     34 	defer t.Stop()
     35 
     36 	select {
     37 	case <-t.C:
     38 		break
     39 	case <-ctx.Done():
     40 		return ctx.Err()
     41 	}
     42 
     43 	return nil
     44 }
     45 
     46 // noOpSleepWithContext does nothing, returns immediately.
     47 func noOpSleepWithContext(context.Context, time.Duration) error {
     48 	return nil
     49 }
     50 
     51 func noOpSleep(time.Duration) {}
     52 
     53 // TestingUseNopSleep is a utility for disabling sleep across the SDK for
     54 // testing.
     55 func TestingUseNopSleep() func() {
     56 	SleepWithContext = noOpSleepWithContext
     57 	Sleep = noOpSleep
     58 
     59 	return func() {
     60 		SleepWithContext = sleepWithContext
     61 		Sleep = time.Sleep
     62 	}
     63 }
     64 
     65 // TestingUseReferenceTime is a utility for swapping the time function across the SDK to return a specific reference time
     66 // for testing purposes.
     67 func TestingUseReferenceTime(referenceTime time.Time) func() {
     68 	NowTime = func() time.Time {
     69 		return referenceTime
     70 	}
     71 	return func() {
     72 		NowTime = time.Now
     73 	}
     74 }