Files
bitchat/bitchatTests/VoiceNotePlaybackControllerTests.swift
T
jackandClaude Opus 5 ac13a0c22f Make the flake class unrepeatable, not just fixed
Raising four deadlines fixed the four tests that happened to fire. The
class was still there: fourteen separate waitUntil helpers, most defaulting
to 1.0s, plus wait call sites with literal budgets. The fifth instance
would have landed the same way, on someone else's unrelated PR.

The rule, now written down in TestConstants.settleTimeout: **a wait
deadline is not a latency budget.** It exists so a genuine hang eventually
fails the suite, so size it for the worst-case scheduler, never for how
long the operation should take. Waits return as soon as their condition
holds, so a generous deadline is free in the passing case and only extends
genuine failures.

- Every wait helper now defaults to TestConstants.settleTimeout (30s), and
  the literal wait call sites below the floor were converted too — sixteen
  sites across ten files.
- TestTimingHygieneTests enforces it by scanning the test sources: wait
  defaults and wait call sites must be at least minimumSettleTimeout, and
  no test may assert an upper bound on elapsed wall-clock time (the
  assertion that started this, which cannot separate correct behaviour from
  a slow machine).
- Both rules waive per line with "test-timing-ok: <reason>", accepted on
  the line or in the comment block above it so the reason has room to be a
  sentence. One legitimate use so far: a NEGATIVE wait in NoiseCoverageTests
  asserting a promotion has *not* completed within 50ms, where a long
  deadline would only make the suite slow while still passing.

Injected production timeouts are deliberately not matched — the Noise
handshake timeouts are the behaviour under test, and short values are
correct there.

Verified the guard actually fails: a canary file with both banned shapes
was flagged with file and line, and the suite went green again once it was
removed. Full suite passes with all 18 cores saturated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 22:23:40 +01:00

159 lines
6.3 KiB
Swift

//
// VoiceNotePlaybackControllerTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Testing
import AVFoundation
import Foundation
@testable import bitchat
/// Thread-safe: the coordinator invokes it on its private serial queue (the
/// blocking session IPC runs off the main thread) while the test reads from
/// the main actor.
private final class RecordingAudioSession: SessionApplying, @unchecked Sendable {
private let lock = NSLock()
private var _activationCalls: [Bool] = []
private var _categoryCallCount = 0
private var _categoryError: Error?
var activationCalls: [Bool] { lock.withLock { _activationCalls } }
var categoryCallCount: Int { lock.withLock { _categoryCallCount } }
var categoryError: Error? {
get { lock.withLock { _categoryError } }
set { lock.withLock { _categoryError = newValue } }
}
func setCategory(_ category: AudioSessionCoordinator.Category) throws {
try lock.withLock {
_categoryCallCount += 1
if let error = _categoryError {
_categoryError = nil
throw error
}
}
}
func setActive(_ active: Bool, notifyOthersOnDeactivation: Bool) throws {
lock.withLock { _activationCalls.append(active) }
}
}
private struct PlaybackSessionError: Error {}
@MainActor
struct VoiceNotePlaybackControllerTests {
/// A short silent PCM file `AVAudioPlayer` can open on the test host.
private func makeTempVoiceNote(seconds: Double = 0.2) throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("voice-note-test-\(UUID().uuidString).caf")
let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1))
let file = try AVAudioFile(forWriting: url, settings: format.settings)
let frames = AVAudioFrameCount(seconds * 16_000)
let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames))
buffer.frameLength = frames
try file.write(from: buffer)
return url
}
/// Waits for an async settle, then asserts.
///
/// The deadline is deliberately far larger than the work it waits on. Every
/// condition here depends on a `@MainActor` Task that playback schedules
/// (the session acquire and its failure path), and on a CI runner executing
/// many suites in parallel that Task can simply not be scheduled for
/// seconds. At five seconds this timed out on CI and reported *two*
/// failures — the wait itself, and the `!isPlaying` that the un-run failure
/// path had not yet reset — which reads like a playback bug rather than a
/// starved scheduler.
///
/// A generous deadline costs nothing when the condition holds, since this
/// returns as soon as it does; it only extends the genuine-failure case.
private func waitUntil(
_ condition: () -> Bool,
sourceLocation: SourceLocation = #_sourceLocation
) async {
let deadline = ContinuousClock.now.advanced(by: .seconds(TestConstants.settleTimeout))
while !condition(), ContinuousClock.now < deadline {
await Task.yield()
try? await Task.sleep(nanoseconds: 1_000_000)
}
#expect(condition(), sourceLocation: sourceLocation)
}
@Test func seekWhilePausedDoesNotAcquireSession() throws {
let session = RecordingAudioSession()
let coordinator = AudioSessionCoordinator(session: session)
let url = try makeTempVoiceNote()
defer { try? FileManager.default.removeItem(at: url) }
let controller = VoiceNotePlaybackController(
url: url,
sessionCoordinator: coordinator,
exclusivity: VoiceNotePlaybackCoordinator()
)
controller.seek(to: 0.5)
// The scrub position moved (the player is real and ready)...
#expect(controller.progress > 0.25)
// ...but nothing is audible, so the session must not be held: an
// acquired-while-paused token on a discarded row would pin the
// session (and any escalated category) forever.
#expect(session.activationCalls.isEmpty)
#expect(!controller.isPlaying)
}
@Test func deinitReleasesSessionAndStopsPlayback() async throws {
let session = RecordingAudioSession()
let coordinator = AudioSessionCoordinator(session: session)
let url = try makeTempVoiceNote()
defer { try? FileManager.default.removeItem(at: url) }
// Fresh exclusivity slot: a parallel test's play() must not pause
// this controller while its session acquire is in flight.
var controller: VoiceNotePlaybackController? = VoiceNotePlaybackController(
url: url,
sessionCoordinator: coordinator,
exclusivity: VoiceNotePlaybackCoordinator()
)
controller?.play()
// The session acquire is asynchronous now (its blocking IPC runs off
// the main thread), so await the activation instead of asserting
// right after play().
await waitUntil { session.activationCalls == [true] }
// Navigating away discards the row's @StateObject mid-playback:
// deinit must release the session hold (a fire-and-forget hop onto
// the coordinator's queue).
controller = nil
await waitUntil { session.activationCalls == [true, false] }
}
@Test func activationFailureDoesNotStartUnregisteredPlayback() async throws {
let session = RecordingAudioSession()
session.categoryError = PlaybackSessionError()
let coordinator = AudioSessionCoordinator(session: session)
let url = try makeTempVoiceNote(seconds: 30)
defer { try? FileManager.default.removeItem(at: url) }
let controller = VoiceNotePlaybackController(
url: url,
sessionCoordinator: coordinator,
exclusivity: VoiceNotePlaybackCoordinator()
)
controller.play()
await waitUntil {
session.categoryCallCount == 1 && !controller.isPlaybackStartPending
}
#expect(session.activationCalls.isEmpty)
#expect(!controller.isPlaying)
#expect(controller.currentTime == 0)
}
}