ghettoptt/debouncer/debouncer_test.go

90 lines
1.9 KiB
Go
Raw Normal View History

2024-10-10 20:40:29 +00:00
package debouncer_test
import (
"testing"
"time"
"git.t-juice.club/torjus/ghettoptt/debouncer"
)
func TestDebouncer(t *testing.T) {
t.Run("Simple", func(t *testing.T) {
ch := make(chan bool)
2024-10-10 21:13:00 +00:00
d := debouncer.New(ch, 200*time.Millisecond)
2024-10-10 20:40:29 +00:00
go func() {
ch <- true
close(ch)
}()
if v := <-d.C; v != true {
t.Errorf("Expected true, got %v", v)
}
})
t.Run("TrueTrueTrueFalse", func(t *testing.T) {
ch := make(chan bool)
2024-10-10 21:13:00 +00:00
d := debouncer.New(ch, 200*time.Millisecond)
2024-10-10 20:40:29 +00:00
go func() {
ch <- true
ch <- true
ch <- true
ch <- false
close(ch)
}()
if v := <-d.C; v != true {
t.Errorf("Expected true, got %v", v)
}
if v := <-d.C; v != false {
t.Errorf("Expected false, got %v", v)
}
})
t.Run("Debounce", func(t *testing.T) {
ch := make(chan bool)
2024-10-10 21:13:00 +00:00
d := debouncer.New(ch, 200*time.Millisecond)
2024-10-10 20:40:29 +00:00
go func() {
ch <- true
time.Sleep(10 * time.Millisecond)
ch <- false
time.Sleep(1 * time.Millisecond)
ch <- true
time.Sleep(1 * time.Millisecond)
ch <- false
time.Sleep(10 * time.Millisecond)
close(ch)
}()
if v := <-d.C; v != true {
t.Errorf("Expected first value to be true, got %v", v)
}
if v := <-d.C; v != false {
t.Errorf("Expected second value to be false, got %v", v)
}
if v, ok := <-d.C; ok {
t.Errorf("Expected closed channel, got %v", v)
}
})
t.Run("DebounceDelay", func(t *testing.T) {
ch := make(chan bool)
2024-10-10 21:13:00 +00:00
d := debouncer.New(ch, 200*time.Millisecond)
2024-10-10 20:40:29 +00:00
go func() {
ch <- true
ch <- false
close(ch)
}()
start := time.Now()
if v := <-d.C; v != true {
t.Errorf("Expected first value to be true, got %v", v)
}
if v, ok := <-d.C; v != false || !ok {
if ok {
t.Errorf("Expected second value to be false, got %v", v)
} else {
t.Error("Unexpected closed channel")
}
}
if duration := time.Since(start); duration < 200*time.Millisecond {
t.Errorf("Got false too soon: %s", duration)
}
})
}