ticker_test.go 703 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package timex
  2. import (
  3. "sync/atomic"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestRealTickerDoTick(t *testing.T) {
  9. ticker := NewTicker(time.Millisecond * 10)
  10. defer ticker.Stop()
  11. var count int
  12. for range ticker.Chan() {
  13. count++
  14. if count > 5 {
  15. break
  16. }
  17. }
  18. }
  19. func TestFakeTicker(t *testing.T) {
  20. const total = 5
  21. ticker := NewFakeTicker()
  22. defer ticker.Stop()
  23. var count int32
  24. go func() {
  25. for {
  26. select {
  27. case <-ticker.Chan():
  28. if atomic.AddInt32(&count, 1) == total {
  29. ticker.Done()
  30. }
  31. }
  32. }
  33. }()
  34. for i := 0; i < 5; i++ {
  35. ticker.Tick()
  36. }
  37. assert.Nil(t, ticker.Wait(time.Second))
  38. assert.Equal(t, int32(total), atomic.LoadInt32(&count))
  39. }