import Foundation import HydraulophoneCore import XCTest @testable import Hydraulophone @MainActor final class PlaybackCancellationTests: XCTestCase { func testStartingAnotherSongInvalidatesPreviousStreamRequest() async throws { let service = CancellationRecordingMusicService() let controller = PlaybackController(service: service) let first = Song(id: "first", title: "First", artist: "Artist") let second = Song(id: "second", title: "Second", artist: "Artist") controller.play(first) try await waitUntil { await service.requestedIDs().contains("first") } controller.play(second) try await waitUntil { await service.requestedIDs().contains("second") } XCTAssertEqual(controller.currentSong?.id, second.id) let requestedIDs = await service.requestedIDs() XCTAssertEqual(requestedIDs, ["first", "second"]) XCTAssertFalse(controller.isPlaying) controller.stop() } private func waitUntil( _ condition: @escaping @Sendable () async -> Bool ) async throws { for _ in 0..<100 { if await condition() { return } try await Task.sleep(nanoseconds: 10_000_000) } XCTFail("Timed out waiting for playback request") } } private actor CancellationRecordingMusicService: MusicService { private var ids: [String] = [] private var pending: [String: CheckedContinuation] = [:] func requestedIDs() -> [String] { ids } func search(query: String) async throws -> [SearchResult] { [] } func playlists() async throws -> [Playlist] { [] } func tracks(in playlist: Playlist) async throws -> [Song] { [] } func stream(for song: Song) async throws -> URL { ids.append(song.id) return try await withTaskCancellationHandler( operation: { try await withCheckedThrowingContinuation { continuation in pending[song.id] = continuation } }, onCancel: { Task { await self.cancelPendingRequest(for: song.id) } } ) } private func cancelPendingRequest(for songID: String) { pending.removeValue(forKey: songID)?.resume(throwing: CancellationError()) } }