Skip to content

Commit

Permalink
add debounce tests
Browse files Browse the repository at this point in the history
  • Loading branch information
illia-li committed Nov 21, 2024
1 parent 6afad7b commit b96879c
Showing 1 changed file with 105 additions and 0 deletions.
105 changes: 105 additions & 0 deletions debounce/simple_debouncer2_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package debounce

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

// TestSimpleDebouncerRace tests SimpleDebouncer for the fact that it does not allow concurrent writing, reading.
// So, if it`s not true `DATA RACE` will be detected.
func TestSimpleDebouncerRace(t *testing.T) {
operations := 1000000
runs := 100
count := 3

d := NewSimpleDebouncer()
for r := 0; r < runs; r++ {
var wg sync.WaitGroup
wg.Add(count)

// The map it`s better choice for `DATA RACE` detection
item := make(map[int]int)

dFunc := func() {
for i := 0; i < operations; i++ {
item[1] = 1
tmp := item[1]
item[1] = tmp + 1
}
}

results := make([]bool, count)
for c := range results {
i := &results[c]
go func() {
*i = d.Debounce(dFunc)
wg.Done()
}()
}
wg.Wait()

// check results
if len(item) == 0 {
t.Fatalf("The Debounce function was not executed")
}

finished := 0
for _, done := range results {
if done {
finished++
}
}
if finished < 2 {
t.Fatalf("In one run should be finished more than 2 `Debounce` method calls, but finished %d", finished)
}
}
}

// TestDebouncerExtreme tests SimpleDebouncer in extreme conditions.
func TestDebouncerExtreme(t *testing.T) {
type runResult struct {
callN int32
executedN int32
done bool
}

runs := 10000
count := 10

d := NewSimpleDebouncer()
var wg sync.WaitGroup
for r := 0; r < runs; r++ {
var callsC, executionsC atomic.Int32
wg.Add(count)

results := make([]runResult, count)

for c := range results {
i := &results[c]

go func() {
i.callN = callsC.Add(1)
i.done = d.Debounce(func() {
i.executedN = executionsC.Add(1)
})
wg.Done()
}()
}
wg.Wait()

// check results
finished := 0
for _, result := range results {
if result.done {
if result.executedN == 0 || result.callN == 0 {
t.Fatalf("Wrong execution detected: \n%#v", result)
}
finished++
}
}
if finished < 2 {
t.Fatalf("In one run should be finished more than 2 `Debounce` method calls, but finished %d", finished)
}
}
}

0 comments on commit b96879c

Please sign in to comment.