| 1 | import Foundation |
| 2 | import Darwin |
| 3 | import XCTest |
| 4 | @testable import RastrilloApple |
| 5 | |
| 6 | private final class Outcomes: @unchecked Sendable { |
| 7 | private let lock = NSLock() |
| 8 | private var recorded: [NativeTransportOutcome] = [] |
| 9 | func append(_ outcome: NativeTransportOutcome) { lock.withLock { recorded.append(outcome) } } |
| 10 | var values: [NativeTransportOutcome] { lock.withLock { recorded } } |
| 11 | } |
| 12 | |
| 13 | final class TypedErrorTests: XCTestCase { |
| 14 | /// A loopback port nothing listens on: bound by the kernel, then released. |
| 15 | private func closedPort() throws -> UInt16 { |
| 16 | let fd = socket(AF_INET, SOCK_STREAM, 0) |
| 17 | guard fd >= 0 else { throw NativeClientError.message("socket failed") } |
| 18 | defer { close(fd) } |
| 19 | var address = sockaddr_in() |
| 20 | address.sin_family = sa_family_t(AF_INET) |
| 21 | address.sin_addr.s_addr = inet_addr("127.0.0.1") |
| 22 | address.sin_port = 0 |
| 23 | var length = socklen_t(MemoryLayout<sockaddr_in>.size) |
| 24 | let bound = withUnsafeMutablePointer(to: &address) { |
| 25 | $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer -> Int32 in |
| 26 | guard Darwin.bind(fd, pointer, length) == 0 else { return -1 } |
| 27 | return getsockname(fd, pointer, &length) |
| 28 | } |
| 29 | } |
| 30 | guard bound == 0 else { throw NativeClientError.message("bind failed") } |
| 31 | return UInt16(bigEndian: address.sin_port) |
| 32 | } |
| 33 | |
| 34 | /// The machine is online; only the server is missing. That still reads as |
| 35 | /// `.offline`, never as an ended session or a generic failure. |
| 36 | func testClosedPortIsOfflineForEveryCall() async throws { |
| 37 | let port = try closedPort() |
| 38 | let outcomes = Outcomes() |
| 39 | let client = NativeHTTP(origin: URL(string: "http://127.0.0.1:\(port)")!, |
| 40 | observer: { outcomes.append($0) }) |
| 41 | let offline = NativeClientError.offline(.cannotConnectToHost) |
| 42 | do { |
| 43 | _ = try await client.responseDetails("/d/1") |
| 44 | XCTFail("A closed port answered") |
| 45 | } catch { XCTAssertEqual(error as? NativeClientError, offline, "Got \(error)") } |
| 46 | do { |
| 47 | struct Empty: Decodable {} |
| 48 | let _: Empty = try await client.request("/d/1", method: "POST", body: Data("{}".utf8)) |
| 49 | XCTFail("A closed port answered") |
| 50 | } catch { XCTAssertEqual(error as? NativeClientError, offline, "Got \(error)") } |
| 51 | do { |
| 52 | try await client.stream("/d/1/stream") { _ in XCTFail("A closed port streamed") } |
| 53 | XCTFail("A closed port streamed") |
| 54 | } catch { XCTAssertEqual(error as? NativeClientError, offline, "Got \(error)") } |
| 55 | do { |
| 56 | let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 57 | try await client.download("/export", to: file) |
| 58 | XCTFail("A closed port exported") |
| 59 | } catch { XCTAssertEqual(error as? NativeClientError, offline, "Got \(error)") } |
| 60 | XCTAssertEqual(offline.retryClass, .offline) |
| 61 | XCTAssertEqual(outcomes.values, Array(repeating: .offline(.cannotConnectToHost), count: 4)) |
| 62 | } |
| 63 | |
| 64 | /// A server that accepts the connection and never answers, so the request |
| 65 | /// is cancelled while URLSession is still waiting for response headers. |
| 66 | func testCancelledRequestThrowsCancellationError() async throws { |
| 67 | let fd = socket(AF_INET, SOCK_STREAM, 0) |
| 68 | XCTAssertGreaterThanOrEqual(fd, 0) |
| 69 | defer { close(fd) } |
| 70 | var address = sockaddr_in() |
| 71 | address.sin_family = sa_family_t(AF_INET) |
| 72 | address.sin_addr.s_addr = inet_addr("127.0.0.1") |
| 73 | var length = socklen_t(MemoryLayout<sockaddr_in>.size) |
| 74 | let listening = withUnsafeMutablePointer(to: &address) { |
| 75 | $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer -> Int32 in |
| 76 | guard Darwin.bind(fd, pointer, length) == 0, listen(fd, 8) == 0 else { return -1 } |
| 77 | return getsockname(fd, pointer, &length) |
| 78 | } |
| 79 | } |
| 80 | XCTAssertEqual(listening, 0) |
| 81 | let outcomes = Outcomes() |
| 82 | let client = NativeHTTP(origin: URL(string: "http://127.0.0.1:\(UInt16(bigEndian: address.sin_port))")!, |
| 83 | observer: { outcomes.append($0) }) |
| 84 | for call in ["responseDetails", "stream", "download"] { |
| 85 | let task = Task { |
| 86 | switch call { |
| 87 | case "responseDetails": _ = try await client.responseDetails("/silent") |
| 88 | case "stream": try await client.stream("/silent") { _ in } |
| 89 | default: try await client.download("/silent", to: FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)) |
| 90 | } |
| 91 | } |
| 92 | try await Task.sleep(nanoseconds: 200_000_000) |
| 93 | task.cancel() |
| 94 | do { |
| 95 | try await task.value |
| 96 | XCTFail("\(call): a cancelled request completed") |
| 97 | } catch { XCTAssertTrue(error is CancellationError, "\(call): expected CancellationError, got \(error)") } |
| 98 | } |
| 99 | XCTAssertEqual(outcomes.values, [], "Cancellation is not evidence about connectivity") |
| 100 | } |
| 101 | |
| 102 | func testOfflineClassification() { |
| 103 | let offline: [URLError.Code] = [.notConnectedToInternet, .networkConnectionLost, .cannotFindHost, .cannotConnectToHost, |
| 104 | .dnsLookupFailed, .timedOut, .dataNotAllowed, .internationalRoamingOff] |
| 105 | for code in offline { |
| 106 | XCTAssertEqual(NativeClientError.classify(URLError(code)) as? NativeClientError, .offline(code)) |
| 107 | } |
| 108 | // A TLS failure is a real fault. Calling it offline would hide it. |
| 109 | for code in [URLError.Code.secureConnectionFailed, .serverCertificateUntrusted, .serverCertificateHasBadDate, |
| 110 | .serverCertificateNotYetValid, .serverCertificateHasUnknownRoot] { |
| 111 | let typed = NativeClientError.classify(URLError(code)) as? NativeClientError |
| 112 | XCTAssertEqual(typed, .transport(code)) |
| 113 | XCTAssertEqual(typed?.retryClass, .transient) |
| 114 | } |
| 115 | XCTAssertTrue(NativeClientError.classify(URLError(.cancelled)) is CancellationError) |
| 116 | XCTAssertTrue(NativeClientError.classify(CancellationError()) is CancellationError) |
| 117 | } |
| 118 | |
| 119 | func testRetryAfterAcceptsSecondsAndHTTPDate() { |
| 120 | let now = Date(timeIntervalSince1970: 1_790_000_000) |
| 121 | XCTAssertEqual(NativeClientError.retryAfter("120", now: now), 120) |
| 122 | let formatter = DateFormatter() |
| 123 | formatter.locale = Locale(identifier: "en_US_POSIX") |
| 124 | formatter.timeZone = TimeZone(identifier: "GMT") |
| 125 | formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss 'GMT'" |
| 126 | XCTAssertEqual(NativeClientError.retryAfter(formatter.string(from: now.addingTimeInterval(30)), now: now), 30) |
| 127 | XCTAssertEqual(NativeClientError.retryAfter(formatter.string(from: now.addingTimeInterval(-30)), now: now), 0) |
| 128 | XCTAssertNil(NativeClientError.retryAfter("soon", now: now)) |
| 129 | XCTAssertNil(NativeClientError.retryAfter(nil, now: now)) |
| 130 | } |
| 131 | |
| 132 | /// Callers that show `localizedDescription` read what they read before. |
| 133 | func testDescriptionsAreTodaysStrings() { |
| 134 | XCTAssertEqual(NativeClientError.unauthorized.localizedDescription, "Your session has ended. Sign out and sign in again.") |
| 135 | XCTAssertEqual(NativeClientError.notFound.localizedDescription, "This server does not support this native feature yet.") |
| 136 | XCTAssertEqual(NativeClientError.server(status: 500).localizedDescription, |
| 137 | "The request could not be completed (500). Your changes have not been confirmed.") |
| 138 | XCTAssertEqual(NativeClientError.message("Invalid server path.").localizedDescription, "Invalid server path.") |
| 139 | } |
| 140 | } |
| 141 | |