import Foundation
import Testing
@testable import HydraulophoneCore
struct BetterLyricsProviderTests {
@Test
func parsesWordRunsWithoutLosingSpacingOrTranslations() throws {
let ttml = """
Hello worldBonjour monde Line only Next Minutes First second
&secret;
""") == nil) #expect(TTMLLyricsParser.parse("Unclosed") == nil)
#expect(
TTMLLyricsParser.parse(
" Wrong root
Line
" BetterProtocol.register(title: title, status: 200, body: payload(ttml)) let provider = makeProvider() let song = Song( id: "video-id-not-sent", title: title, artist: "One Artist", album: "The Album", durationText: "3:07") let result = try await provider.lyrics(for: song) let request = try #require(BetterProtocol.lastRequest(for: title)) let url = try #require(request.url) let items = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems) let query = Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") }) #expect(url.scheme == "https") #expect(url.host == "api.betterlyrics.org") #expect(url.path == "/getLyrics") #expect(query == ["s": title, "a": "One Artist", "d": "187", "al": "The Album"]) #expect(!url.absoluteString.contains(song.id)) #expect(request.httpMethod == "GET") #expect(request.timeoutInterval == 8) #expect(request.httpShouldHandleCookies == false) #expect(request.value(forHTTPHeaderField: "Authorization") == nil) #expect(request.value(forHTTPHeaderField: "Cookie") == nil) #expect(request.value(forHTTPHeaderField: "X-API-Key") == nil) #expect(result?.isSynchronized == true) #expect(result?.source == "BetterLyrics") #expect(result?.lines.first?.text == "Line") } @Test func missingAndUncachedLyricsAreAbsenceWhileServerFailuresStayTyped() async throws { let absent = "Absent Better fixture" let gated = "Gated Better fixture" let failed = "Failed Better fixture" BetterProtocol.register(title: absent, status: 404, body: Data()) BetterProtocol.register(title: gated, status: 401, body: Data()) BetterProtocol.register(title: failed, status: 503, body: Data()) let provider = makeProvider() #expect(try await provider.lyrics(for: song(absent)) == nil) #expect(try await provider.lyrics(for: song(gated)) == nil) await #expect(throws: BetterLyricsError.httpStatus(503)) { try await provider.lyrics(for: song(failed)) } } @Test func malformedResponseIsTypedAndPrecancelledRequestSendsNothing() async throws { let malformed = "Malformed Better fixture" BetterProtocol.register(title: malformed, status: 200, body: Data("{}".utf8)) let provider = makeProvider() await #expect(throws: BetterLyricsError.invalidResponse) { try await provider.lyrics(for: song(malformed)) } let cancelled = "Cancelled Better fixture" BetterProtocol.register(title: cancelled, status: 404, body: Data()) let task = Task { withUnsafeCurrentTask { $0?.cancel() } return try await provider.lyrics(for: song(cancelled)) } await #expect(throws: CancellationError.self) { try await task.value } #expect(BetterProtocol.lastRequest(for: cancelled) == nil) } @Test func retryAfterBlocksFurtherRequestsWithoutPolling() async { let limited = "Limited Better fixture" let next = "Blocked Better fixture" BetterProtocol.register( title: limited, status: 429, body: Data(), headers: ["Retry-After": "60"]) BetterProtocol.register(title: next, status: 404, body: Data()) let provider = makeProvider() await #expect(throws: BetterLyricsError.rateLimited) { try await provider.lyrics(for: song(limited)) } await #expect(throws: BetterLyricsError.rateLimited) { try await provider.lyrics(for: song(next)) } #expect(BetterProtocol.lastRequest(for: next) == nil) } private func makeProvider() -> BetterLyricsProvider { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [BetterProtocol.self] return BetterLyricsProvider( session: URLSession(configuration: configuration), throttle: BetterLyricsRequestThrottle()) } private func song(_ title: String) -> Song { Song(id: "id", title: title, artist: "Artist") } private func payload(_ ttml: String) -> Data { (try? JSONSerialization.data(withJSONObject: ["ttml": ttml])) ?? Data() } } private final class BetterProtocol: URLProtocol { private struct Fixture: Sendable { let status: Int let body: Data let headers: [String: String] } private static let registry = Registry() static func register( title: String, status: Int, body: Data, headers: [String: String] = [:] ) { registry.register( title: title, fixture: Fixture(status: status, body: body, headers: headers)) } static func lastRequest(for title: String) -> URLRequest? { registry.lastRequest(for: title) } override class func canInit(with request: URLRequest) -> Bool { request.url?.host == "api.betterlyrics.org" } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { guard let url = request.url, let title = URLComponents(url: url, resolvingAgainstBaseURL: false)? .queryItems?.first(where: { $0.name == "s" })?.value, let fixture = Self.registry.fixture(for: title, request: request), let response = HTTPURLResponse( url: url, statusCode: fixture.status, httpVersion: "HTTP/1.1", headerFields: fixture.headers) else { client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse)) return } client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: fixture.body) client?.urlProtocolDidFinishLoading(self) } override func stopLoading() {} private final class Registry: @unchecked Sendable { private let lock = NSLock() private var fixtures: [String: Fixture] = [:] private var requests: [String: URLRequest] = [:] func register(title: String, fixture: Fixture) { lock.lock() defer { lock.unlock() } fixtures[title] = fixture requests.removeValue(forKey: title) } func fixture(for title: String, request: URLRequest) -> Fixture? { lock.lock() defer { lock.unlock() } requests[title] = request return fixtures[title] } func lastRequest(for title: String) -> URLRequest? { lock.lock() defer { lock.unlock() } return requests[title] } } }