Fix TestSenseContinuous to be more robust

pull/113/head
George Sexton 4 months ago
parent 3483a63475
commit b07b8920f0

@ -5,8 +5,6 @@
package lps2x package lps2x
import ( import (
"sync"
"sync/atomic"
"testing" "testing"
"time" "time"
@ -152,31 +150,41 @@ func TestSenseContinuous(t *testing.T) {
t.Error("expected error on insufficient sense continuous duration") t.Error("expected error on insufficient sense continuous duration")
} }
counter := atomic.Int32{}
chEnd := make(chan struct{})
chRead, err := dev.SenseContinuous(d) chRead, err := dev.SenseContinuous(d)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
wg := sync.WaitGroup{}
wg.Add(1) expectedCount := 10
go func(ch <-chan physic.Env, chEnd chan struct{}) { start := time.Now()
var env physic.Env
for { // Read exactly expectedCount samples
for i := 0; i < expectedCount; i++ {
select { select {
case env = <-ch: case env := <-chRead:
t.Logf("received %#v", env) t.Logf("received reading %d: %#v", i+1, env)
counter.Add(1) case <-time.After(3 * d):
case <-chEnd: t.Fatalf("Timed out waiting for reading %d (waited %v)", i+1, 3*d)
wg.Done()
break
} }
} }
}(chRead, chEnd)
time.Sleep(10 * d) elapsed := time.Since(start)
chEnd <- struct{}{}
wg.Wait() // Verify timing: expectedCount readings at interval d should take approximately (expectedCount-1)*d to expectedCount*d
if counter.Load() != 10 { // Lower bound: readings shouldn't come faster than the ticker interval
t.Errorf("Expected reading count of 10, received %d", counter.Load()) minDuration := time.Duration(expectedCount-1) * d
// Upper bound: allow some slack for CI/scheduling delays (1.5x the expected maximum)
maxDuration := time.Duration(expectedCount) * d * 3 / 2
if elapsed < minDuration {
t.Errorf("Readings too fast! Got %d readings in %v, expected at least %v. Sample rate may be ignored.",
expectedCount, elapsed, minDuration)
}
if elapsed > maxDuration {
t.Errorf("Readings too slow! Got %d readings in %v, expected at most %v. Sample rate may be too slow.",
expectedCount, elapsed, maxDuration)
} }
// Clean up: stop the background goroutine
_ = dev.Halt()
} }

Loading…
Cancel
Save