debounce_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package watch
  14. import (
  15. "context"
  16. "slices"
  17. "testing"
  18. "time"
  19. "github.com/jonboulle/clockwork"
  20. "gotest.tools/v3/assert"
  21. )
  22. func Test_BatchDebounceEvents(t *testing.T) {
  23. ch := make(chan FileEvent)
  24. clock := clockwork.NewFakeClock()
  25. ctx, stop := context.WithCancel(context.Background())
  26. t.Cleanup(stop)
  27. eventBatchCh := BatchDebounceEvents(ctx, clock, ch)
  28. for i := 0; i < 100; i++ {
  29. path := "/a"
  30. if i%2 == 0 {
  31. path = "/b"
  32. }
  33. ch <- FileEvent(path)
  34. }
  35. // we sent 100 events + the debouncer
  36. err := clock.BlockUntilContext(ctx, 101)
  37. assert.NilError(t, err)
  38. clock.Advance(QuietPeriod)
  39. select {
  40. case batch := <-eventBatchCh:
  41. slices.Sort(batch)
  42. assert.Equal(t, len(batch), 2)
  43. assert.Equal(t, batch[0], FileEvent("/a"))
  44. assert.Equal(t, batch[1], FileEvent("/b"))
  45. case <-time.After(50 * time.Millisecond):
  46. t.Fatal("timed out waiting for events")
  47. }
  48. err = clock.BlockUntilContext(ctx, 1)
  49. assert.NilError(t, err)
  50. clock.Advance(QuietPeriod)
  51. // there should only be a single batch
  52. select {
  53. case batch := <-eventBatchCh:
  54. t.Fatalf("unexpected events: %v", batch)
  55. case <-time.After(50 * time.Millisecond):
  56. // channel is empty
  57. }
  58. }