Do separate TestingURLProtocol responses per-test.

This commit is contained in:
Brent Simmons committed 2026-09-09 08:44:18 -07:00
1 parent 181a1744d3
commit 1dff40fa4a
7 files changed
+198 -65

No files matched your search

@@ -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")
}
}
@@ -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 == [])
}
}
@@ -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)
}
}
@@ -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 {
}
@@ -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)
@@ -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)
@@ -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
}
}