cond_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package syncx
  2. import (
  3. "sync"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestTimeoutCondWait(t *testing.T) {
  9. var wait sync.WaitGroup
  10. cond := NewCond()
  11. wait.Add(2)
  12. go func() {
  13. cond.Wait()
  14. wait.Done()
  15. }()
  16. time.Sleep(time.Duration(50) * time.Millisecond)
  17. go func() {
  18. cond.Signal()
  19. wait.Done()
  20. }()
  21. wait.Wait()
  22. }
  23. func TestTimeoutCondWaitTimeout(t *testing.T) {
  24. var wait sync.WaitGroup
  25. cond := NewCond()
  26. wait.Add(1)
  27. go func() {
  28. cond.WaitWithTimeout(time.Duration(500) * time.Millisecond)
  29. wait.Done()
  30. }()
  31. wait.Wait()
  32. }
  33. func TestTimeoutCondWaitTimeoutRemain(t *testing.T) {
  34. var wait sync.WaitGroup
  35. cond := NewCond()
  36. wait.Add(2)
  37. ch := make(chan time.Duration, 1)
  38. defer close(ch)
  39. timeout := time.Duration(2000) * time.Millisecond
  40. go func() {
  41. remainTimeout, _ := cond.WaitWithTimeout(timeout)
  42. ch <- remainTimeout
  43. wait.Done()
  44. }()
  45. sleep(200)
  46. go func() {
  47. cond.Signal()
  48. wait.Done()
  49. }()
  50. wait.Wait()
  51. remainTimeout := <-ch
  52. assert.True(t, remainTimeout < timeout, "expect remainTimeout %v < %v", remainTimeout, timeout)
  53. assert.True(t, remainTimeout >= time.Duration(200)*time.Millisecond,
  54. "expect remainTimeout %v >= 200 millisecond", remainTimeout)
  55. }
  56. func TestSignalNoWait(t *testing.T) {
  57. cond := NewCond()
  58. cond.Signal()
  59. }
  60. func sleep(millisecond int) {
  61. time.Sleep(time.Duration(millisecond) * time.Millisecond)
  62. }
  63. func currentTimeMillis() int64 {
  64. return time.Now().UnixNano() / int64(time.Millisecond)
  65. }