aboutsummaryrefslogtreecommitdiff
path: root/internal/watcher/debounce_test.go
blob: 007dbd4e6049514f540000a45e7b79d64fd3b8b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package watcher

import (
	"sync/atomic"
	"testing"
	"time"
)

func TestDebounceCollapsesNotifications(t *testing.T) {
	done := make(chan struct{}, 1)
	var calls atomic.Int32

	w := New(Config{
		Debounce: 25 * time.Millisecond,
		OnChange: func() {
			calls.Add(1)

			select {
			case done <- struct{}{}:
			default:
			}
		},
	})

	go w.debounceLoop(t.Context())

	for range 10 {
		w.notify()
	}

	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("timed out waiting for callback")
	}

	if got := calls.Load(); got != 1 {
		t.Fatalf("expected 1 callback, got %d", got)
	}
}

func TestDebounceSeparateBursts(t *testing.T) {
	done := make(chan struct{}, 2)
	var calls atomic.Int32

	w := New(Config{
		Debounce: 20 * time.Millisecond,
		OnChange: func() {
			calls.Add(1)

			select {
			case done <- struct{}{}:
			default:
			}
		},
	})

	go w.debounceLoop(t.Context())

	w.notify()

	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("timed out waiting for first callback")
	}

	w.notify()

	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("timed out waiting for second callback")
	}

	if got := calls.Load(); got != 2 {
		t.Fatalf("expected 2 callbacks, got %d", got)
	}
}