audio: run the tests waiting on real time on the fake clock of synctest

TestGC, TestSameSourcePlayers, TestDeferredDeviceCreation,
TestPauseAndStopReading, TestPauseAndStopReadingWhilePaused,
TestPositionNotGrowingAfterFinished and
TestPlayerErrorDoesNotStopOtherPlayers now run in a synctest bubble, so
their sleeps and deadlines take no real time.

A bubble must not leave goroutines behind, so ResetContextForTesting
now stops the goroutine updating the players and the dummy players
reading their sources, and waits for them to exit. Before, every test
leaked them.

Updates #3716
This commit is contained in:
dualfroz committed 2026-10-03 16:06:04 +02:00
1 parent 87bac3749b
commit d22b1a2b09
3 files changed
+81 -16

No files matched your search

+20 -8
View File
@@ -73,9 +73,17 @@ type Context struct {
playingPlayers map[*playerImpl]struct{} playingPlayers map[*playerImpl]struct{}
m sync.Mutex m sync.Mutex
// cond is signalled under m when a player is added to playingPlayers. The goroutine // cond is signalled under m when a player is added to playingPlayers or when the context is
// updating the players waits on it while playingPlayers is empty. // disposed. The goroutine updating the players waits on it while playingPlayers is empty.
cond *sync.Cond cond *sync.Cond
// disposed reports that the goroutine updating the players must exit. A context lives until the
// process exits, so this is set only when a test discards the context.
disposed bool
// updater tracks the goroutine updating the players, so that a test discarding the context can wait
// for the goroutine to exit.
updater sync.WaitGroup
} }
var ( var (
@@ -162,12 +170,14 @@ func NewContext(sampleRate int) *Context {
// In the current Ebitengine implementation, update might not be called when the window is in the background (#3154). // In the current Ebitengine implementation, update might not be called when the window is in the background (#3154).
// In this case, an audio player's position is not updated correctly with AppendHookOnBeforeUpdateWithVMGuestInfo. // In this case, an audio player's position is not updated correctly with AppendHookOnBeforeUpdateWithVMGuestInfo.
// Use a distinct goroutine to update the player states. // Use a distinct goroutine to update the player states.
go func() { c.updater.Go(func() {
for { for {
// Block while there is no player to update, so that an idle context does not wake // Block while there is no player to update, so that an idle context does not wake
// up periodically. The sweep itself can remove the last player, so the check is // up periodically. The sweep itself can remove the last player, so the check is
// repeated after every sweep. // repeated after every sweep.
c.waitForPlayingPlayers() if !c.waitForPlayingPlayers() {
return
}
// A failure is local to the player which reported it. Record it and keep updating // A failure is local to the player which reported it. Record it and keep updating
// the other players (#3647). // the other players (#3647).
if err := c.updatePlayers(); err != nil { if err := c.updatePlayers(); err != nil {
@@ -175,7 +185,7 @@ func NewContext(sampleRate int) *Context {
} }
time.Sleep(time.Second / 100) time.Sleep(time.Second / 100)
} }
}() })
return c return c
} }
@@ -212,13 +222,15 @@ func (c *Context) setReady() {
c.m.Unlock() c.m.Unlock()
} }
// waitForPlayingPlayers blocks until at least one player is registered as playing. // waitForPlayingPlayers blocks until at least one player is registered as playing, and reports
func (c *Context) waitForPlayingPlayers() { // whether the players should be updated. It returns false once the context is disposed.
func (c *Context) waitForPlayingPlayers() bool {
c.m.Lock() c.m.Lock()
defer c.m.Unlock() defer c.m.Unlock()
for len(c.playingPlayers) == 0 { for len(c.playingPlayers) == 0 && !c.disposed {
c.cond.Wait() c.cond.Wait()
} }
return !c.disposed
} }
func (c *Context) addPlayingPlayer(p *playerImpl) { func (c *Context) addPlayingPlayer(p *playerImpl) {
+19 -4
View File
@@ -24,6 +24,7 @@ import (
"sync" "sync"
"sync/atomic" "sync/atomic"
"testing" "testing"
"testing/synctest"
"time" "time"
"github.com/hajimehoshi/ebiten/v2/audio" "github.com/hajimehoshi/ebiten/v2/audio"
@@ -42,6 +43,7 @@ func teardown() {
// Issue #746 // Issue #746
func TestGC(t *testing.T) { func TestGC(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
setup() setup()
defer teardown() defer teardown()
@@ -69,11 +71,12 @@ func TestGC(t *testing.T) {
if err := audio.UpdateForTesting(); err != nil { if err := audio.UpdateForTesting(); err != nil {
t.Error(err) t.Error(err)
} }
// 200[ms] should be enough for all the bytes to be consumed. // 200[ms] should be enough for all the bytes to be consumed. The test runs on the fake
// TODO: This is a dirty hack. Would it be possible to use virtual time? // clock of synctest, so this does not take real time.
time.Sleep(200 * time.Millisecond) time.Sleep(200 * time.Millisecond)
} }
t.Errorf("time out") t.Errorf("time out")
})
} }
type infiniteReader struct{} type infiniteReader struct{}
@@ -87,6 +90,7 @@ func (i *infiniteReader) Read(p []byte) (int, error) {
// Issue #853 // Issue #853
func TestSameSourcePlayers(t *testing.T) { func TestSameSourcePlayers(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
setup() setup()
defer teardown() defer teardown()
@@ -116,6 +120,7 @@ func TestSameSourcePlayers(t *testing.T) {
time.Sleep(200 * time.Millisecond) time.Sleep(200 * time.Millisecond)
} }
t.Errorf("time out") t.Errorf("time out")
})
} }
func TestPauseBeforeInit(t *testing.T) { func TestPauseBeforeInit(t *testing.T) {
@@ -166,6 +171,7 @@ func TestNonSeekableSource(t *testing.T) {
// Issue #3438 // Issue #3438
func TestDeferredDeviceCreation(t *testing.T) { func TestDeferredDeviceCreation(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
setup() setup()
defer teardown() defer teardown()
@@ -213,6 +219,7 @@ func TestDeferredDeviceCreation(t *testing.T) {
time.Sleep(200 * time.Millisecond) time.Sleep(200 * time.Millisecond)
} }
t.Errorf("time out") t.Errorf("time out")
})
} }
// Issue #3438 // Issue #3438
@@ -450,6 +457,7 @@ func TestPauseAndStopReading(t *testing.T) {
t.Skip("infinite streams in tests cannot be treated well on browsers") t.Skip("infinite streams in tests cannot be treated well on browsers")
} }
synctest.Test(t, func(t *testing.T) {
setup() setup()
defer teardown() defer teardown()
@@ -487,6 +495,7 @@ func TestPauseAndStopReading(t *testing.T) {
// The player is reusable after PauseAndStopReading. // The player is reusable after PauseAndStopReading.
p.Play() p.Play()
waitForRead(t, src, reads) waitForRead(t, src, reads)
})
} }
// Issue #3510 // Issue #3510
@@ -495,6 +504,7 @@ func TestPauseAndStopReadingWhilePaused(t *testing.T) {
t.Skip("infinite streams in tests cannot be treated well on browsers") t.Skip("infinite streams in tests cannot be treated well on browsers")
} }
synctest.Test(t, func(t *testing.T) {
setup() setup()
defer teardown() defer teardown()
@@ -524,6 +534,7 @@ func TestPauseAndStopReadingWhilePaused(t *testing.T) {
if got := src.reads.Load(); got != reads { if got := src.reads.Load(); got != reads {
t.Errorf("the source was read after PauseAndStopReading: got: %d reads, want: %d", got, reads) t.Errorf("the source was read after PauseAndStopReading: got: %d reads, want: %d", got, reads)
} }
})
} }
// Issue #3510 // Issue #3510
@@ -635,6 +646,7 @@ func TestSetBufferSize(t *testing.T) {
} }
func TestPositionNotGrowingAfterFinished(t *testing.T) { func TestPositionNotGrowingAfterFinished(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
setup() setup()
defer teardown() defer teardown()
@@ -646,8 +658,8 @@ func TestPositionNotGrowingAfterFinished(t *testing.T) {
} }
p.Play() p.Play()
// Wait until the player finishes its source. The deadline is generous because time.Sleep has // Wait until the player finishes its source. The test runs on the fake clock of synctest, so
// a several-millisecond floor on browsers, which slows draining the source down. // the deadline does not take real time.
var finished bool var finished bool
deadline := time.Now().Add(10 * time.Second) deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) { for time.Now().Before(deadline) {
@@ -680,6 +692,7 @@ func TestPositionNotGrowingAfterFinished(t *testing.T) {
if got := p.Position(); got != end { if got := p.Position(); got != end {
t.Errorf("position grew after the player finished: %v -> %v", end, got) t.Errorf("position grew after the player finished: %v -> %v", end, got)
} }
})
} }
func TestNewPlayerWithSourceOfClosedPlayer(t *testing.T) { func TestNewPlayerWithSourceOfClosedPlayer(t *testing.T) {
@@ -797,6 +810,7 @@ func TestPlayerErrorDoesNotStopOtherPlayers(t *testing.T) {
t.Skip("infinite streams in tests cannot be treated well on browsers") t.Skip("infinite streams in tests cannot be treated well on browsers")
} }
synctest.Test(t, func(t *testing.T) {
setup() setup()
defer teardown() defer teardown()
@@ -861,6 +875,7 @@ func TestPlayerErrorDoesNotStopOtherPlayers(t *testing.T) {
if err := audio.UpdateForTesting(); !errors.Is(err, errSourceFailed) { if err := audio.UpdateForTesting(); !errors.Is(err, errSourceFailed) {
t.Errorf("UpdateForTesting() after a player failed: got: %v, want: %v", err, errSourceFailed) t.Errorf("UpdateForTesting() after a player failed: got: %v, want: %v", err, errSourceFailed)
} }
})
} }
func TestPlayOnIdleContext(t *testing.T) { func TestPlayOnIdleContext(t *testing.T) {
+42 -4
View File
@@ -27,6 +27,10 @@ type (
suspendErr error suspendErr error
resumeErr error resumeErr error
// players are the players created since the context was reset last. ResetContextForTesting
// stops them, so that a player reading an infinite source does not keep reading after its test.
players []*dummyPlayer
mu sync.Mutex mu sync.Mutex
} }
dummyPlayer struct { dummyPlayer struct {
@@ -45,6 +49,9 @@ type (
// readGen is incremented by PauseAndStopReading to stop the goroutine reading r. // readGen is incremented by PauseAndStopReading to stop the goroutine reading r.
readGen int readGen int
// readers tracks the goroutines reading r, so that a test can wait for them to stop.
readers sync.WaitGroup
// err is the first non-EOF error the source returned. Like the real players, a player // err is the first non-EOF error the source returned. Like the real players, a player
// whose source failed stops for good and reports the error from Err. // whose source failed stops for good and reports the error from Err.
err error err error
@@ -54,10 +61,27 @@ type (
) )
func (c *dummyContext) NewPlayer(r io.Reader) player { func (c *dummyContext) NewPlayer(r io.Reader) player {
return &dummyPlayer{ p := &dummyPlayer{
r: r, r: r,
volume: 1, volume: 1,
} }
c.mu.Lock()
defer c.mu.Unlock()
c.players = append(c.players, p)
return p
}
// stopPlayers stops the players' goroutines reading their sources, and waits for them to exit.
func (c *dummyContext) stopPlayers() {
c.mu.Lock()
players := c.players
c.players = nil
c.mu.Unlock()
for _, p := range players {
p.PauseAndStopReading()
p.readers.Wait()
}
} }
func (c *dummyContext) MaxBufferSize() int { func (c *dummyContext) MaxBufferSize() int {
@@ -95,7 +119,7 @@ func (p *dummyPlayer) Play() {
} }
p.playing = true p.playing = true
gen := p.readGen gen := p.readGen
go func() { p.readers.Go(func() {
var buf [4096]byte var buf [4096]byte
for { for {
stopped, err := p.readOnce(gen, buf[:]) stopped, err := p.readOnce(gen, buf[:])
@@ -114,7 +138,7 @@ func (p *dummyPlayer) Play() {
if p.playing { if p.playing {
p.eof = true p.eof = true
} }
}() })
} }
// readOnce performs one read from the source with the mutex held, so that PauseAndStopReading waits // readOnce performs one read from the source with the mutex held, so that PauseAndStopReading waits
@@ -324,10 +348,24 @@ func ContextCreatedForTesting() bool {
return c.playerFactory.currentContext() != nil return c.playerFactory.currentContext() != nil
} }
// ResetContextForTesting discards the current context, so that a test can create a new one.
// ResetContextForTesting waits for the goroutines the context and its players started to exit, so
// that they do not outlive the test.
func ResetContextForTesting() { func ResetContextForTesting() {
theContextLock.Lock() theContextLock.Lock()
defer theContextLock.Unlock() c := theContext
theContext = nil theContext = nil
theContextLock.Unlock()
if c != nil {
c.m.Lock()
c.disposed = true
c.cond.Broadcast()
c.m.Unlock()
c.updater.Wait()
}
dummyContextForTesting.stopPlayers()
} }
func (i *InfiniteLoop) SetNoBlendForTesting(value bool) { func (i *InfiniteLoop) SetNoBlendForTesting(value bool) {