45 lines
2.1 KiB
Swift
45 lines
2.1 KiB
Swift
import Foundation
|
|
|
|
final class IPResponse: URLProtocol, @unchecked Sendable {
|
|
nonisolated(unsafe) static var payload = "203.0.113.4"
|
|
nonisolated(unsafe) static var status = 200
|
|
nonisolated(unsafe) static var count = 0
|
|
override class func canInit(with request: URLRequest) -> Bool { true }
|
|
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
|
override func startLoading() {
|
|
Self.count += 1
|
|
precondition(request.url?.scheme == "https" && request.timeoutInterval == 5)
|
|
client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: Self.status, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocol(self, didLoad: Data(Self.payload.utf8))
|
|
client?.urlProtocolDidFinishLoading(self)
|
|
}
|
|
override func stopLoading() {}
|
|
}
|
|
|
|
@main struct PublicIPAddressChecks {
|
|
static func main() async {
|
|
let config = URLSessionConfiguration.ephemeral
|
|
config.protocolClasses = [IPResponse.self]
|
|
let session = URLSession(configuration: config)
|
|
defer { session.invalidateAndCancel() }
|
|
let service = PublicIPAddressService(session: session)
|
|
let first = await service.address(route: "one")
|
|
precondition(first == "203.0.113.4")
|
|
let cached = await service.address(route: "one")
|
|
precondition(cached == first && IPResponse.count == 1)
|
|
IPResponse.payload = "2001:db8::1"
|
|
let changed = await service.address(route: "two")
|
|
precondition(changed == "2001:db8::1" && IPResponse.count == 2)
|
|
IPResponse.payload = "<html>invalid</html>"
|
|
let invalid = await service.address(route: "three")
|
|
precondition(invalid == nil)
|
|
let cachedFailure = await service.address(route: "three")
|
|
precondition(cachedFailure == nil && IPResponse.count == 3)
|
|
IPResponse.payload = "203.0.113.4"
|
|
IPResponse.status = 503
|
|
let httpFailure = await service.address(route: "four")
|
|
precondition(httpFailure == nil)
|
|
print("PASS: IPv4/IPv6, route cache, invalid payload, cached failure, HTTP failure, timeout")
|
|
}
|
|
}
|