From 1dff40fa4ac85393c220e29673a336bd591f93f6 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 9 Sep 2026 08:44:18 -0700 Subject: [PATCH] Do separate TestingURLProtocol responses per-test. --- .../Feedbin/FeedbinFeedNameTests.swift | 45 +++++----- .../Feedbin/FeedbinStatusSendTests.swift | 67 +++++++-------- .../TestingURLProtocol+Responses.swift | 2 +- .../Tests/AccountTests/WebserviceTests.swift | 18 ++++ .../WebServices/TestingURLProtocol.swift | 42 +++++++--- .../WebServices/URLSession+Webservice.swift | 7 ++ .../TestingURLProtocolIsolationTests.swift | 82 +++++++++++++++++++ 7 files changed, 198 insertions(+), 65 deletions(-) create mode 100644 Modules/Account/Tests/AccountTests/WebserviceTests.swift create mode 100644 Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift index 81180029b..d44a0276f 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift @@ -9,31 +9,34 @@ import Testing import RSWeb @testable import Account -@MainActor struct FeedbinFeedNameTests { +extension WebserviceTests { - private static let daringFireballFeedID = "1296379" + @MainActor struct FeedbinFeedNameTests { - private let accountManager = TestAccountManager() + private static let daringFireballFeedID = "1296379" - @Test func refreshLeavesEditedNameAlone() async throws { - TestingURLProtocol.reset() - TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json") - TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json") + private let accountManager = TestAccountManager() - let account = accountManager.createAccount(type: .feedbin) - defer { - accountManager.deleteAccount(account) + @Test func refreshLeavesEditedNameAlone() async throws { + TestingURLProtocol.reset() + TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json") + TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json") + + let account = accountManager.createAccount(type: .feedbin) + defer { + accountManager.deleteAccount(account) + } + + try await account.refreshAll() + let feed = try #require(account.idToFeedDictionary[Self.daringFireballFeedID]) + feed.editedName = "Edited Name" + + // A second refresh sees the same server name and must not touch the rename. + try await account.refreshAll() + + #expect(feed.editedName == "Edited Name") + #expect(feed.name == "Daring Fireball") + #expect(feed.nameForDisplay == "Edited Name") } - - try await account.refreshAll() - let feed = try #require(account.idToFeedDictionary[Self.daringFireballFeedID]) - feed.editedName = "Edited Name" - - // A second refresh sees the same server name and must not touch the rename. - try await account.refreshAll() - - #expect(feed.editedName == "Edited Name") - #expect(feed.name == "Daring Fireball") - #expect(feed.nameForDisplay == "Edited Name") } } diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift index 90d3a4621..4a20a8167 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift @@ -11,40 +11,43 @@ import RSWeb import SyncDatabase @testable import Account -@MainActor struct FeedbinStatusSendTests { +extension WebserviceTests { - /// A permanently-rejected unread status used to abort the remaining groups, - /// so starring and unstarring never reached the server again. - @Test func failingUnreadGroupStillSendsStarredGroup() async throws { - TestingURLProtocol.reset() - defer { + @MainActor struct FeedbinStatusSendTests { + + /// A permanently-rejected unread status used to abort the remaining groups, + /// so starring and unstarring never reached the server again. + @Test func failingUnreadGroupStillSendsStarredGroup() async throws { TestingURLProtocol.reset() + defer { + TestingURLProtocol.reset() + } + + // Matching is by URL substring, so both unread calls fail and both starred calls + // fall through to the default 200. + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: "unread_entries.json") + + let account = TestAccountManager.shared.createAccount(type: .feedbin) + defer { + TestAccountManager.shared.deleteAccount(account) + } + + let databasePath = URL(filePath: account.dataFolder).appendingPathComponent("Sync.sqlite3").path + let syncDatabase = SyncDatabase(databasePath: databasePath) + await syncDatabase.insertStatuses([ + SyncStatus(articleID: "1", key: .read, flag: false), + SyncStatus(articleID: "2", key: .starred, flag: true) + ]) + + await #expect(throws: (any Error).self) { + try await account.sendArticleStatus() + } + + let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() + #expect(pendingReadArticleIDs == ["1"]) + + let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() + #expect(pendingStarredArticleIDs == []) } - - // Matching is by URL substring, so both unread calls fail and both starred calls - // fall through to the default 200. - TestingURLProtocol.responses["unread_entries.json"] = TestingURLProtocol.Response(statusCode: 422) - - let account = TestAccountManager.shared.createAccount(type: .feedbin) - defer { - TestAccountManager.shared.deleteAccount(account) - } - - let databasePath = URL(filePath: account.dataFolder).appendingPathComponent("Sync.sqlite3").path - let syncDatabase = SyncDatabase(databasePath: databasePath) - await syncDatabase.insertStatuses([ - SyncStatus(articleID: "1", key: .read, flag: false), - SyncStatus(articleID: "2", key: .starred, flag: true) - ]) - - await #expect(throws: (any Error).self) { - try await account.sendArticleStatus() - } - - let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() - #expect(pendingReadArticleIDs == ["1"]) - - let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() - #expect(pendingStarredArticleIDs == []) } } diff --git a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift index fad4f9911..6b5cbf91f 100644 --- a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift +++ b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift @@ -21,6 +21,6 @@ extension TestingURLProtocol { } catch { fatalError("Unable to read response file at \(fileURL) because \(error).") } - responses[urlSubstring] = Response(statusCode: statusCode, data: data) + setResponse(Response(statusCode: statusCode, data: data), forURLContaining: urlSubstring) } } diff --git a/Modules/Account/Tests/AccountTests/WebserviceTests.swift b/Modules/Account/Tests/AccountTests/WebserviceTests.swift new file mode 100644 index 000000000..04872ee53 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/WebserviceTests.swift @@ -0,0 +1,18 @@ +// +// WebserviceTests.swift +// AccountTests +// +// Created by Brent Simmons on 9/7/26. +// + +import Testing + +/// Parent of every suite that registers canned responses with `TestingURLProtocol`. +/// +/// They share one global response table, and Swift Testing runs tests in parallel by default, +/// so one suite's `reset()` can wipe another's registrations while its requests are in flight. +/// `.serialized` applies to nested suites, so nesting here keeps them from interleaving. +/// +/// Any new suite that stubs webservice responses belongs here, whatever the account type. +@Suite(.serialized) struct WebserviceTests { +} diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift index ab81185b0..52f2e07cd 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift @@ -21,23 +21,44 @@ public final class TestingURLProtocol: URLProtocol { } } - /// Maps a URL substring to the response to return for matching requests. - /// Written by tests, read on the URL loading system's thread, so it's behind a lock. - private static let responses = OSAllocatedUnfairLock<[String: Response]>(initialState: [:]) + /// Identifies the running test. A session built by `URLSession.makeWebserviceSession()` + /// inside a scope where this is bound carries it, so concurrent tests registering the + /// same URL substring don't see each other's responses. + @TaskLocal public static var currentTestID: String? + + /// 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 + /// built outside a `currentTestID` scope use `sharedTestID`. + private static let responses = OSAllocatedUnfairLock<[String: [String: 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) { - responses.withLock { $0[urlSubstring] = response } + let testID = currentTestID ?? sharedTestID + responses.withLock { $0[testID, default: [:]][urlSubstring] = response } } - /// Clears all registered responses. Call between tests. + /// Clears the responses registered by the current test. Call between tests. public static func reset() { - responses.withLock { $0 = [:] } + removeResponses(forTestID: currentTestID ?? sharedTestID) } - private static func response(forURLString urlString: String) -> Response? { - responses.withLock { responses in - responses.first { urlString.contains($0.key) }?.value + /// Discards one test's responses, for a scope that is ending. + public static func removeResponses(forTestID testID: String) { + responses.withLock { $0[testID] = nil } + } + + private static func response(for request: URLRequest) -> Response? { + guard let urlString = request.url?.absoluteString else { + return nil + } + + let testID = request.value(forHTTPHeaderField: testIDHeaderField) ?? sharedTestID + return responses.withLock { responses in + responses[testID]?.first { urlString.contains($0.key) }?.value } } @@ -56,8 +77,7 @@ public final class TestingURLProtocol: URLProtocol { return } - let urlString = url.absoluteString - let match = Self.response(forURLString: urlString) + let match = Self.response(for: request) let httpResponse = HTTPURLResponse(url: url, statusCode: match?.statusCode ?? 200, httpVersion: "HTTP/1.1", headerFields: nil)! client?.urlProtocol(self, didReceive: httpResponse, cacheStoragePolicy: .notAllowed) diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift index 5e2738076..85e1bf1ae 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift @@ -58,6 +58,13 @@ nonisolated extension URLSession { if Platform.isRunningUnitTests { sessionConfiguration.protocolClasses = [TestingURLProtocol.self] + + // Stamp the session so the protocol can tell this test's requests from another's. + if let testID = TestingURLProtocol.currentTestID { + var headers = sessionConfiguration.httpAdditionalHeaders ?? [:] + headers[TestingURLProtocol.testIDHeaderField] = testID + sessionConfiguration.httpAdditionalHeaders = headers + } } return URLSession(configuration: sessionConfiguration) diff --git a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift new file mode 100644 index 000000000..daa5db3d6 --- /dev/null +++ b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift @@ -0,0 +1,82 @@ +// +// TestingURLProtocolIsolationTests.swift +// RSWebTests +// +// Created by Brent Simmons on 9/7/26. +// + +import Foundation +import Testing +import RSCore +@testable import RSWeb + +struct TestingURLProtocolIsolationTests { + + private static let url = URL(string: "https://example.com/subscriptions.json")! + private static let urlSubstring = "subscriptions.json" + + @Test func concurrentTestsDoNotSeeEachOthersResponses() async throws { + try #require(Platform.isRunningUnitTests) + + async let first = Self.statusCode(forTestID: "first", registering: 418) + async let second = Self.statusCode(forTestID: "second", registering: 503) + + let (firstStatusCode, secondStatusCode) = try await (first, second) + #expect(firstStatusCode == 418) + #expect(secondStatusCode == 503) + } + + @Test func resetClearsOnlyTheCurrentTestsResponses() async throws { + try #require(Platform.isRunningUnitTests) + + TestingURLProtocol.$currentTestID.withValue("keeper") { + TestingURLProtocol.setResponse(.init(statusCode: 418), forURLContaining: Self.urlSubstring) + } + defer { + TestingURLProtocol.removeResponses(forTestID: "keeper") + } + + TestingURLProtocol.$currentTestID.withValue("resetter") { + TestingURLProtocol.setResponse(.init(statusCode: 503), forURLContaining: Self.urlSubstring) + TestingURLProtocol.reset() + } + + let statusCode = try await TestingURLProtocol.$currentTestID.withValue("keeper") { + try await Self.statusCode(for: Self.url) + } + #expect(statusCode == 418) + } + + @Test func aSessionBuiltOutsideATestScopeUsesTheSharedResponses() async throws { + try #require(Platform.isRunningUnitTests) + + TestingURLProtocol.setResponse(.init(statusCode: 404), forURLContaining: Self.urlSubstring) + defer { + TestingURLProtocol.reset() + } + + let statusCode = try await Self.statusCode(for: Self.url) + #expect(statusCode == 404) + } +} + +private extension TestingURLProtocolIsolationTests { + + /// Registers a response and fetches it, all inside one test-ID scope, so the session + /// created here carries that ID. + static func statusCode(forTestID testID: String, registering statusCode: Int) async throws -> Int { + try await TestingURLProtocol.$currentTestID.withValue(testID) { + defer { + TestingURLProtocol.removeResponses(forTestID: testID) + } + TestingURLProtocol.setResponse(.init(statusCode: statusCode), forURLContaining: urlSubstring) + return try await Self.statusCode(for: url) + } + } + + static func statusCode(for url: URL) async throws -> Int { + let session = URLSession.makeWebserviceSession() + let (_, response) = try await session.data(from: url) + return try #require(response as? HTTPURLResponse).statusCode + } +}