timeoutlimit_test.go 701 B

123456789101112131415161718192021222324252627282930313233
  1. package syncx
  2. import (
  3. "sync"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestTimeoutLimit(t *testing.T) {
  9. limit := NewTimeoutLimit(2)
  10. assert.Nil(t, limit.Borrow(time.Millisecond*200))
  11. assert.Nil(t, limit.Borrow(time.Millisecond*200))
  12. var wait1, wait2, wait3 sync.WaitGroup
  13. wait1.Add(1)
  14. wait2.Add(1)
  15. wait3.Add(1)
  16. go func() {
  17. wait1.Wait()
  18. wait2.Done()
  19. assert.Nil(t, limit.Return())
  20. wait3.Done()
  21. }()
  22. wait1.Done()
  23. wait2.Wait()
  24. assert.Nil(t, limit.Borrow(time.Second))
  25. wait3.Wait()
  26. assert.Equal(t, ErrTimeout, limit.Borrow(time.Millisecond*100))
  27. assert.Nil(t, limit.Return())
  28. assert.Nil(t, limit.Return())
  29. assert.Equal(t, ErrLimitReturn, limit.Return())
  30. }