SPB Git

Repository Public

ClientTests.swift 9.3 KB 190 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Core/Tests/SPSearchKitTests/ClientTests.swift10// Description      : HTTP client against a stubbed URL protocol: headers, error11//                    mapping, Retry-After, cancellation.12// Module           : SPSearchKitTests13// Repository       : https://git.spboucher.ai/sp-search-ios14// Project Website  : https://search.spboucher.ai15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Testing92@testable import SPSearchKit9394final class StubProtocol: URLProtocol, @unchecked Sendable {95    struct Reply { var status = 200; var headers: [String: String] = [:]; var body = Data(); var error: URLError?; var delay: TimeInterval = 0 }96    private static let lock = NSLock()97    nonisolated(unsafe) private static var replies: [String: Reply] = [:]98    nonisolated(unsafe) private static var seen: [String: URLRequest] = [:]99100    static func set(_ reply: Reply, for host: String) { lock.withLock { replies[host] = reply } }101    static func request(for host: String) -> URLRequest? { lock.withLock { seen[host] } }102103    override class func canInit(with request: URLRequest) -> Bool { true }104    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }105    override func stopLoading() {}106    override func startLoading() {107        let host = request.url?.host ?? ""108        let reply = Self.lock.withLock { () -> Reply in Self.seen[host] = request; return Self.replies[host] ?? Reply(status: 500) }109        let finish: @Sendable () -> Void = { [self] in110            if let e = reply.error { client?.urlProtocol(self, didFailWithError: e); return }111            let r = HTTPURLResponse(url: request.url!, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers)!112            client?.urlProtocol(self, didReceive: r, cacheStoragePolicy: .notAllowed)113            client?.urlProtocol(self, didLoad: reply.body)114            client?.urlProtocolDidFinishLoading(self)115        }116        if reply.delay > 0 { DispatchQueue.global().asyncAfter(deadline: .now() + reply.delay, execute: finish) } else { finish() }117    }118}119120@Suite struct ClientTests {121    /// Each test talks to its own invented host, so the tests can run in parallel.122    private func client(_ reply: StubProtocol.Reply, host: String = "\(UUID().uuidString.lowercased()).test") -> (SPSearchClient, String) {123        StubProtocol.set(reply, for: host)124        return (SPSearchClient(baseURL: URL(string: "https://\(host)")!, session: SPSearchClient.makeSession(protocolClasses: [StubProtocol.self]), userAgent: "SPSearch-iOS/test"), host)125    }126127    @Test func searchDecodesAndSendsPlainHeaders() async throws {128        let (c, host) = client(.init(body: try fixture("search")))129        let r = try await c.search(SearchRequest(query: "université laval", region: .canada))130        #expect(r.results.count == 5)131        let sent = try #require(StubProtocol.request(for: host))132        #expect(sent.url?.path == "/v2/search")133        #expect(sent.url?.query == "q=universit%C3%A9%20laval&limit=10&region=ca")134        #expect(sent.value(forHTTPHeaderField: "Accept") == "application/json")135        #expect(sent.value(forHTTPHeaderField: "User-Agent") == "SPSearch-iOS/test")136        #expect(sent.value(forHTTPHeaderField: "Cookie") == nil)137        #expect(sent.value(forHTTPHeaderField: "Authorization") == nil)138    }139140    @Test func suggestionsAndStats() async throws {141        let (c, _) = client(.init(body: Data(#"{"suggestions":["a"," b ","","c","d","e","f","g","h","i"]}"#.utf8)))142        #expect(try await c.suggest("x") == ["a", "b", "c", "d", "e", "f", "g", "h"])143        let (s, _) = client(.init(body: try fixture("stats")))144        #expect(try await s.stats().domains > 400_000)145    }146147    @Test func badRequestCarriesTheServerMessage() async {148        let (c, _) = client(.init(status: 400, body: Data(#"{"error":{"code":"bad_request","message":"requête vide"},"request_id":"r-1"}"#.utf8)))149        await #expect(throws: SearchError.badRequest(message: "requête vide")) { try await c.search(SearchRequest(query: "")) }150    }151152    @Test func rateLimitReadsRetryAfter() async {153        let (c, _) = client(.init(status: 429, headers: ["Retry-After": "7"], body: Data(#"{"error":{"code":"rate_limited","message":"trop"}}"#.utf8)))154        await #expect(throws: SearchError.rateLimited(retryAfter: 7)) { try await c.search(SearchRequest(query: "x")) }155        #expect(SPSearchClient.retryAfter(nil) == 5)156        #expect(SPSearchClient.retryAfter("0") == 1)157        #expect(SPSearchClient.retryAfter("9999") == 120)158        #expect(SPSearchClient.retryAfter("Wed, 21 Oct 2026 07:28:00 GMT") == 5)159    }160161    @Test func unavailableAndOtherStatuses() async {162        let (c, _) = client(.init(status: 503, body: Data("<html>".utf8)))163        await #expect(throws: SearchError.unavailable(message: nil)) { try await c.stats() }164        let (d, _) = client(.init(status: 502))165        await #expect(throws: SearchError.http(status: 502, message: nil)) { try await d.stats() }166    }167168    @Test func unreadableBodyIsAnInvalidResponse() async {169        let (c, _) = client(.init(body: Data("<html>passerelle</html>".utf8)))170        await #expect(throws: SearchError.invalidResponse) { try await c.search(SearchRequest(query: "x")) }171    }172173    @Test func transportErrorsAreNamed() async {174        let (c, _) = client(.init(error: URLError(.notConnectedToInternet)))175        await #expect(throws: SearchError.offline) { try await c.stats() }176        let (t, _) = client(.init(error: URLError(.timedOut)))177        await #expect(throws: SearchError.timedOut) { try await t.stats() }178        let (n, _) = client(.init(error: URLError(.cannotFindHost)))179        await #expect(throws: SearchError.network(code: URLError.Code.cannotFindHost.rawValue)) { try await n.stats() }180    }181182    @Test func cancellingTheTaskIsReportedAsCancelled() async {183        let (c, _) = client(.init(body: Data(#"{"suggestions":[]}"#.utf8), delay: 2))184        let task = Task { try await c.suggest("x") }185        try? await Task.sleep(for: .milliseconds(50))186        task.cancel()187        await #expect(throws: SearchError.cancelled) { try await task.value }188    }189}190
Files main
Menu

Theme