wake_detector_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package nebula
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestWakeDetector(t *testing.T) {
  8. delta := time.Duration(0)
  9. ok := true
  10. w := &wakeDetector{read: func() (time.Duration, bool) { return delta, ok }}
  11. // The first sample primes the baseline and never reports a wake, even with a pre-existing spread
  12. delta = 3 * time.Hour
  13. slept, sok := w.Sample()
  14. assert.True(t, sok)
  15. assert.Equal(t, time.Duration(0), slept)
  16. // A stable spread means the machine never slept
  17. slept, sok = w.Sample()
  18. assert.True(t, sok)
  19. assert.Equal(t, time.Duration(0), slept)
  20. // The spread grows by exactly the time spent suspended
  21. delta += 42 * time.Second
  22. slept, sok = w.Sample()
  23. assert.True(t, sok)
  24. assert.Equal(t, 42*time.Second, slept)
  25. // A wake is reported once, then the baseline moves with it
  26. slept, sok = w.Sample()
  27. assert.True(t, sok)
  28. assert.Equal(t, time.Duration(0), slept)
  29. // Negative jitter from the non-atomic clock pair reads clamps to zero
  30. delta -= time.Microsecond
  31. slept, sok = w.Sample()
  32. assert.True(t, sok)
  33. assert.Equal(t, time.Duration(0), slept)
  34. // Consecutive suspends both report; the clamped jitter moved the baseline so it is not double-counted
  35. delta += time.Minute
  36. slept, _ = w.Sample()
  37. assert.Equal(t, time.Minute, slept)
  38. delta += time.Hour
  39. slept, _ = w.Sample()
  40. assert.Equal(t, time.Hour, slept)
  41. // An unsupported platform read reports not-ok
  42. ok = false
  43. _, sok = w.Sample()
  44. assert.False(t, sok)
  45. }
  46. // TestWakeDetectorPlatformClock smoke tests the real clock pair: two samples close together must not report a
  47. // wake on a machine that isn't suspending mid-test.
  48. func TestWakeDetectorPlatformClock(t *testing.T) {
  49. w := newWakeDetector()
  50. if _, ok := w.Sample(); !ok {
  51. t.Skip("platform has no suspend clock pair")
  52. }
  53. slept, ok := w.Sample()
  54. assert.True(t, ok)
  55. assert.Less(t, slept, time.Second)
  56. }