|
| 1 | +import EndpointBuilder |
| 2 | +@testable import EndpointBuilderURLSession |
| 3 | +import HTTPTypes |
| 4 | +import RoutingKit |
| 5 | +import XCTest |
| 6 | +#if canImport(FoundationNetworking) |
| 7 | +import FoundationNetworking |
| 8 | +#endif |
| 9 | + |
| 10 | +struct MockURLSession: URLRequestHandler { |
| 11 | + |
| 12 | + let requestHandler: @Sendable (URLRequest) -> Data |
| 13 | + |
| 14 | + func data(for request: URLRequest) async throws -> (Data, URLResponse) { |
| 15 | + let data = requestHandler(request) |
| 16 | + return ( |
| 17 | + data, |
| 18 | + URLResponse() |
| 19 | + ) |
| 20 | + } |
| 21 | + |
| 22 | +} |
| 23 | + |
| 24 | +final class EndpointBuilderURLSessionTests: XCTestCase { |
| 25 | + |
| 26 | + @Endpoint |
| 27 | + struct EndpointWithNoResponse { |
| 28 | + static let path: [PathComponent] = ["blank"] |
| 29 | + static let httpMethod = HTTPRequest.Method.get |
| 30 | + } |
| 31 | + |
| 32 | + @Endpoint |
| 33 | + struct EndpointWithStringResponseAndPathComponent { |
| 34 | + static let path: [PathComponent] = ["echo", ":id"] |
| 35 | + static let httpMethod = HTTPRequest.Method.post |
| 36 | + static let responseType = String.self |
| 37 | + let body: String |
| 38 | + } |
| 39 | + |
| 40 | + struct APIClient: EndpointBuilderURLSession { |
| 41 | + |
| 42 | + let serverBaseURL = URL(string: "https://api.shipyard.studio")! |
| 43 | + let urlSession: @Sendable () -> URLRequestHandler |
| 44 | + |
| 45 | + init(mockSession: MockURLSession) { |
| 46 | + let session: @Sendable () -> URLRequestHandler = { mockSession } |
| 47 | + self.urlSession = session |
| 48 | + } |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + func testEndpointWithNoResponse() async throws { |
| 53 | + let endpoint = EndpointWithNoResponse() |
| 54 | + let client = APIClient(mockSession: MockURLSession(requestHandler: { urlRequest in |
| 55 | + XCTAssertEqual(urlRequest.url?.pathComponents, ["/", "blank"]) |
| 56 | + XCTAssertEqual(urlRequest.httpMethod, "GET") |
| 57 | + return Data() |
| 58 | + })) |
| 59 | + try await client.request(endpoint) |
| 60 | + } |
| 61 | + |
| 62 | + func testEndpointWithStringResponse() async throws { |
| 63 | + let endpoint = EndpointWithStringResponseAndPathComponent( |
| 64 | + body: "hello", |
| 65 | + pathParameters: EndpointWithStringResponseAndPathComponent.PathParameters(id: "my-ids") |
| 66 | + ) |
| 67 | + let client = APIClient(mockSession: MockURLSession(requestHandler: { urlRequest in |
| 68 | + XCTAssertEqual(urlRequest.url?.pathComponents, ["/", "echo", "my-ids"]) |
| 69 | + XCTAssertEqual(urlRequest.httpMethod, "POST") |
| 70 | + XCTAssertEqual(urlRequest.httpBody, try? JSONEncoder().encode("hello")) |
| 71 | + return (try? JSONEncoder().encode("world")) ?? Data() |
| 72 | + })) |
| 73 | + let response = try await client.request(endpoint) |
| 74 | + XCTAssertEqual(response, "world") |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments