diff --git a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift index 6b5cbf91f..6e2780486 100644 --- a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift +++ b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift @@ -13,7 +13,7 @@ extension TestingURLProtocol { /// Register the response to return for any request whose URL contains `urlSubstring`. /// The body is loaded from `file`, relative to the test bundle resources (e.g. "JSON/tags_add.json"). - static func setResponse(_ urlSubstring: String, file: String, statusCode: Int = 200) { + static func setResponse(_ urlSubstring: String, file: String, statusCode: Int = 200, httpMethod: String? = nil) { let fileURL = Bundle.module.resourceURL!.appendingPathComponent(file) let data: Data do { @@ -21,6 +21,6 @@ extension TestingURLProtocol { } catch { fatalError("Unable to read response file at \(fileURL) because \(error).") } - setResponse(Response(statusCode: statusCode, data: data), forURLContaining: urlSubstring) + setResponse(Response(statusCode: statusCode, data: data), forURLContaining: urlSubstring, httpMethod: httpMethod) } } diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift index 52f2e07cd..38dc0ee72 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift @@ -29,16 +29,25 @@ public final class TestingURLProtocol: URLProtocol { /// Carries `currentTestID` from the session's configuration to `startLoading`. public static let testIDHeaderField = "X-NetNewsWire-Testing-ID" - /// Maps a test ID to that test's URL-substring-to-response table. Requests from a session + /// What a registered response answers: a URL substring, and optionally one HTTP method. + private struct ResponseKey: Hashable { + let urlSubstring: String + let httpMethod: String? + } + + /// Maps a test ID to that test's registered responses. Requests from a session /// built outside a `currentTestID` scope use `sharedTestID`. - private static let responses = OSAllocatedUnfairLock<[String: [String: Response]]>(initialState: [:]) + private static let responses = OSAllocatedUnfairLock<[String: [ResponseKey: Response]]>(initialState: [:]) private static let sharedTestID = "shared" /// Register the response to return for requests whose URL contains `urlSubstring`. - public static func setResponse(_ response: Response, forURLContaining urlSubstring: String) { + /// Pass `httpMethod` — `HTTPMethod.post` and friends — to answer only that method. + /// A registration without one answers any method no method-specific registration claims. + public static func setResponse(_ response: Response, forURLContaining urlSubstring: String, httpMethod: String? = nil) { let testID = currentTestID ?? sharedTestID - responses.withLock { $0[testID, default: [:]][urlSubstring] = response } + let key = ResponseKey(urlSubstring: urlSubstring, httpMethod: httpMethod) + responses.withLock { $0[testID, default: [:]][key] = response } } /// Clears the responses registered by the current test. Call between tests. @@ -58,7 +67,18 @@ public final class TestingURLProtocol: URLProtocol { let testID = request.value(forHTTPHeaderField: testIDHeaderField) ?? sharedTestID return responses.withLock { responses in - responses[testID]?.first { urlString.contains($0.key) }?.value + guard let responsesForTest = responses[testID] else { + return nil + } + + func response(forHTTPMethod httpMethod: String?) -> Response? { + responsesForTest.first { key, _ in + key.httpMethod == httpMethod && urlString.contains(key.urlSubstring) + }?.value + } + + // A registration for this request's method wins over one that answers any method. + return response(forHTTPMethod: request.httpMethod) ?? response(forHTTPMethod: nil) } } diff --git a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift new file mode 100644 index 000000000..fb8820040 --- /dev/null +++ b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift @@ -0,0 +1,88 @@ +// +// TestingURLProtocolMethodMatchingTests.swift +// RSWebTests +// +// Created by Brent Simmons on 9/14/26. +// + +import Foundation +import Testing +import RSCore +@testable import RSWeb + +struct TestingURLProtocolMethodMatchingTests { + + private static let url = URL(string: "https://example.com/unread_entries.json")! + private static let urlSubstring = "unread_entries.json" + + @Test func aMethodSpecificResponseAnswersOnlyThatMethod() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.post) + + let postStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.post) + #expect(postStatusCode == 422) + + let getStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.get) + #expect(getStatusCode == 200) + } + } + + @Test func aResponseWithNoMethodAnswersEveryMethod() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + TestingURLProtocol.setResponse(.init(statusCode: 404), forURLContaining: Self.urlSubstring) + + let postStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.post) + #expect(postStatusCode == 404) + + let getStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.get) + #expect(getStatusCode == 404) + + let deleteStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.delete) + #expect(deleteStatusCode == 404) + } + } + + @Test func aMethodSpecificResponseWinsOverOneWithNoMethod() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + TestingURLProtocol.setResponse(.init(statusCode: 404), forURLContaining: Self.urlSubstring) + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.post) + + let postStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.post) + #expect(postStatusCode == 422) + + let getStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.get) + #expect(getStatusCode == 404) + } + } +} + +private extension TestingURLProtocolMethodMatchingTests { + + /// Runs `body` against its own response table. RSWebTests has no trait to do this + /// (`IsolatedWebserviceResponsesTrait` lives in AccountTests), so it's done by hand — + /// without it these tests share one table and clear each other's registrations. + static func withItsOwnResponses(_ body: () async throws -> Void) async throws { + let testID = UUID().uuidString + try await TestingURLProtocol.$currentTestID.withValue(testID) { + defer { + TestingURLProtocol.removeResponses(forTestID: testID) + } + try await body() + } + } + + static func statusCode(httpMethod: String) async throws -> Int { + var request = URLRequest(url: url) + request.httpMethod = httpMethod + + let session = URLSession.makeWebserviceSession() + let (_, response) = try await session.data(for: request) + return try #require(response as? HTTPURLResponse).statusCode + } +}