mount public data from the atmosphere to a virtual filesystem (macos only) pdfs.at
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

test(atproto): add URLProtocol stub utility

+60
+60
Packages/ATProto/Tests/ATProtoTests/Support/URLProtocolStub.swift
··· 1 + import Foundation 2 + 3 + /// In-process HTTP stub for URLSession tests. Not thread-safe across concurrent 4 + /// tests; invoke each test serially or guard with `@Suite(.serialized)`. 5 + final class URLProtocolStub: URLProtocol, @unchecked Sendable { 6 + struct Response { 7 + let statusCode: Int 8 + let headers: [String: String] 9 + let body: Data 10 + 11 + static func json(_ string: String, status: Int = 200) -> Response { 12 + Response(statusCode: status, headers: ["Content-Type": "application/json"], body: Data(string.utf8)) 13 + } 14 + static func bytes(_ data: Data, contentType: String = "application/octet-stream", status: Int = 200) -> Response { 15 + Response(statusCode: status, headers: ["Content-Type": contentType], body: data) 16 + } 17 + static func text(_ s: String, status: Int = 200) -> Response { 18 + Response(statusCode: status, headers: ["Content-Type": "text/plain"], body: Data(s.utf8)) 19 + } 20 + } 21 + 22 + nonisolated(unsafe) static var handler: ((URLRequest) -> Response)? 23 + nonisolated(unsafe) static var recordedRequests: [URLRequest] = [] 24 + 25 + static func install(handler: @escaping (URLRequest) -> Response) -> URLSession { 26 + Self.handler = handler 27 + Self.recordedRequests = [] 28 + let config = URLSessionConfiguration.ephemeral 29 + config.protocolClasses = [URLProtocolStub.self] 30 + return URLSession(configuration: config) 31 + } 32 + 33 + static func reset() { 34 + handler = nil 35 + recordedRequests = [] 36 + } 37 + 38 + override class func canInit(with request: URLRequest) -> Bool { true } 39 + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } 40 + 41 + override func startLoading() { 42 + Self.recordedRequests.append(request) 43 + guard let handler = Self.handler else { 44 + client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse)) 45 + return 46 + } 47 + let response = handler(request) 48 + let httpResponse = HTTPURLResponse( 49 + url: request.url!, 50 + statusCode: response.statusCode, 51 + httpVersion: "HTTP/1.1", 52 + headerFields: response.headers 53 + )! 54 + client?.urlProtocol(self, didReceive: httpResponse, cacheStoragePolicy: .notAllowed) 55 + client?.urlProtocol(self, didLoad: response.body) 56 + client?.urlProtocolDidFinishLoading(self) 57 + } 58 + 59 + override func stopLoading() {} 60 + }