time.go 1.9 KB

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