mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-11-30 01:10:38 +00:00
Merge branch 'main' of https://github.com/Ranchero-Software/NetNewsWire
This commit is contained in:
commit
47f62e5eec
26 files changed
+772
-103
No files matched your search
@@ -257,15 +257,8 @@ let appName = "NetNewsWire"
|
||||
refreshTimer = AccountRefreshTimer()
|
||||
ArticleStatusSyncTimer.shared.start()
|
||||
|
||||
UNUserNotificationCenter.current().requestAuthorization(options: [.badge]) { _, _ in }
|
||||
|
||||
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
|
||||
if settings.authorizationStatus == .authorized {
|
||||
DispatchQueue.main.async {
|
||||
NSApplication.shared.registerForRemoteNotifications()
|
||||
}
|
||||
}
|
||||
}
|
||||
// Silent CloudKit pushes don’t need notification permission.
|
||||
NSApplication.shared.registerForRemoteNotifications()
|
||||
|
||||
UNUserNotificationCenter.current().delegate = self
|
||||
UserNotificationManager.shared.start()
|
||||
|
||||
@@ -12,7 +12,7 @@ import Account
|
||||
|
||||
final class AccountsDetailViewController: NSViewController {
|
||||
|
||||
private let account: Account
|
||||
let account: Account
|
||||
private var accountsWindowController: NSWindowController?
|
||||
|
||||
init(account: Account) {
|
||||
|
||||
@@ -27,6 +27,7 @@ final class AccountsPreferencesViewController: NSViewController {
|
||||
var addAccountsViewController: NSHostingController<AddAccountsView>?
|
||||
|
||||
private var sortedAccounts = [Account]()
|
||||
private var isReloadingTable = false
|
||||
private var selectedAccount: Account? {
|
||||
account(at: tableView.selectedRow)
|
||||
}
|
||||
@@ -144,12 +145,11 @@ extension AccountsPreferencesViewController: NSTableViewDelegate {
|
||||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||||
updateDeleteButtonState()
|
||||
|
||||
if let selectedAccount {
|
||||
let controller = AccountsDetailViewController(account: selectedAccount)
|
||||
showController(controller)
|
||||
} else {
|
||||
hideController()
|
||||
// A reload can report its selection more than once, so reloadTable(selecting:) updates the detail view when it settles.
|
||||
if isReloadingTable {
|
||||
return
|
||||
}
|
||||
updateDetailView()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,11 +245,31 @@ private extension AccountsPreferencesViewController {
|
||||
|
||||
func reloadTable(selecting accountToSelect: Account?) {
|
||||
updateSortedAccounts()
|
||||
|
||||
isReloadingTable = true
|
||||
tableView.reloadData()
|
||||
if let accountToSelect, let row = sortedAccounts.firstIndex(of: accountToSelect) {
|
||||
tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
|
||||
}
|
||||
isReloadingTable = false
|
||||
|
||||
updateDeleteButtonState()
|
||||
updateDetailView()
|
||||
}
|
||||
|
||||
/// Reuses the existing detail view controller when it's already showing the selected account, so an in-progress edit isn't destroyed.
|
||||
func updateDetailView() {
|
||||
guard let selectedAccount else {
|
||||
hideController()
|
||||
return
|
||||
}
|
||||
|
||||
let accountShowingInDetailView = (children.first as? AccountsDetailViewController)?.account
|
||||
if accountShowingInDetailView == selectedAccount {
|
||||
return
|
||||
}
|
||||
|
||||
showController(AccountsDetailViewController(account: selectedAccount))
|
||||
}
|
||||
|
||||
func updateDeleteButtonState() {
|
||||
|
||||
@@ -301,10 +301,8 @@ import ActivityLog
|
||||
}
|
||||
|
||||
public func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async {
|
||||
Task {
|
||||
for account in activeAccounts {
|
||||
await account.receiveRemoteNotification(userInfo: userInfo)
|
||||
}
|
||||
for account in activeAccounts {
|
||||
await account.receiveRemoteNotification(userInfo: userInfo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,10 +314,13 @@ import ActivityLog
|
||||
}
|
||||
}
|
||||
|
||||
public func refreshAll(errorHandler: ErrorHandlerCallback? = nil) async {
|
||||
/// Returns `true` if the refresh ran, `false` if it was skipped
|
||||
/// due to no network connection.
|
||||
@discardableResult
|
||||
public func refreshAll(errorHandler: ErrorHandlerCallback? = nil) async -> Bool {
|
||||
guard NetworkMonitor.shared.isConnected else {
|
||||
Self.logger.info("AccountManager: skipping refreshAll — not connected to internet.")
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
CombinedRefreshProgress.shared.start()
|
||||
@@ -338,6 +339,8 @@ import ActivityLog
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
public func sendArticleStatusAll() async {
|
||||
|
||||
@@ -188,12 +188,15 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable {
|
||||
return false
|
||||
}
|
||||
|
||||
let sentCount = try await sendArticleStatus(account: account, showProgress: false)
|
||||
let sendResult = try await sendArticleStatus(account: account, showProgress: false)
|
||||
try await refreshArticleStatus()
|
||||
|
||||
let didReceiveChanges = !(articlesZoneHasNoChanges && accountZoneHasNoChanges)
|
||||
let didWork = sentCount > 0 || didReceiveChanges
|
||||
if didWork {
|
||||
let didWork = sendResult.sentCount > 0 || didReceiveChanges
|
||||
|
||||
// A failed send means statuses are still waiting to go out, so this isn't a quiet
|
||||
// period. Backing off here would also skip receiving for the next half hour.
|
||||
if didWork || sendResult.didFail {
|
||||
lastNoChangeSyncDate = nil
|
||||
} else {
|
||||
lastNoChangeSyncDate = Date()
|
||||
@@ -1130,10 +1133,10 @@ private extension CloudKitAccountDelegate {
|
||||
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete")
|
||||
}
|
||||
|
||||
/// Returns the number of statuses successfully sent.
|
||||
func sendArticleStatus(account: Account, showProgress: Bool) async throws -> Int {
|
||||
/// Returns the number of statuses successfully sent, and whether any failed to send.
|
||||
func sendArticleStatus(account: Account, showProgress: Bool) async throws -> (sentCount: Int, didFail: Bool) {
|
||||
Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)")
|
||||
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Int, Error>) in
|
||||
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<(sentCount: Int, didFail: Bool), Error>) in
|
||||
let op = CloudKitSendStatusOperation(account: account,
|
||||
articlesZone: articlesZone,
|
||||
database: syncDatabase,
|
||||
@@ -1144,7 +1147,7 @@ private extension CloudKitAccountDelegate {
|
||||
if mainThreadOperation.isCanceled {
|
||||
continuation.resume(throwing: CloudKitAccountDelegateError.unknown)
|
||||
} else {
|
||||
continuation.resume(returning: op.sentCount)
|
||||
continuation.resume(returning: (op.sentCount, op.didFail))
|
||||
}
|
||||
}
|
||||
mainThreadOperationQueue.add(op)
|
||||
|
||||
@@ -182,7 +182,8 @@ final class CloudKitArticlesZone: CloudKitZone {
|
||||
return 0
|
||||
}
|
||||
|
||||
var modifyRecords = [CKRecord]()
|
||||
var statusRecords = [CKRecord]()
|
||||
var articleRecords = [CKRecord]()
|
||||
var newRecords = [CKRecord]()
|
||||
var deleteRecordIDs = [CKRecord.ID]()
|
||||
var contentUploadCount = 0
|
||||
@@ -193,9 +194,8 @@ final class CloudKitArticlesZone: CloudKitZone {
|
||||
for statusUpdate in statusUpdates {
|
||||
switch statusUpdate.record {
|
||||
case .all:
|
||||
modifyRecords.append(self.makeStatusRecord(statusUpdate))
|
||||
modifyRecords.append(self.makeArticleRecord(statusUpdate.article!))
|
||||
contentUploadCount += 1
|
||||
statusRecords.append(self.makeStatusRecord(statusUpdate))
|
||||
articleRecords.append(self.makeArticleRecord(statusUpdate.article!))
|
||||
case .new:
|
||||
newRecords.append(self.makeStatusRecord(statusUpdate))
|
||||
if statusUpdate.article!.status.starred || syncUnreadContent {
|
||||
@@ -207,22 +207,38 @@ final class CloudKitArticlesZone: CloudKitZone {
|
||||
case .delete:
|
||||
deleteRecordIDs.append(CKRecord.ID(recordName: self.statusID(statusUpdate.articleID), zoneID: zoneID))
|
||||
case .statusOnly:
|
||||
modifyRecords.append(self.makeStatusRecord(statusUpdate))
|
||||
statusRecords.append(self.makeStatusRecord(statusUpdate))
|
||||
deleteRecordIDs.append(CKRecord.ID(recordName: self.articleID(statusUpdate.articleID), zoneID: zoneID))
|
||||
}
|
||||
}
|
||||
|
||||
await Task.detached(priority: .userInitiated) {
|
||||
self.compressArticleRecords(modifyRecords)
|
||||
self.compressArticleRecords(articleRecords)
|
||||
self.compressArticleRecords(newRecords)
|
||||
}.value
|
||||
|
||||
// Statuses go first, and on their own. They're what sync correctness depends on, and
|
||||
// `modify` is atomic, so batching them with content records means one article too big
|
||||
// to store rejects every status in the request. Sending them first is also the right
|
||||
// order: an article record references its status record.
|
||||
do {
|
||||
try await modify(recordsToSave: modifyRecords, recordIDsToDelete: deleteRecordIDs)
|
||||
try await modify(recordsToSave: statusRecords, recordIDsToDelete: deleteRecordIDs)
|
||||
try await saveIfNew(newRecords)
|
||||
} catch {
|
||||
try await handleModifyArticlesError(error, statusUpdates: statusUpdates)
|
||||
return contentUploadCount
|
||||
}
|
||||
|
||||
// Content is an optimization, so a failure here leaves the statuses sent.
|
||||
if !articleRecords.isEmpty {
|
||||
do {
|
||||
try await modify(recordsToSave: articleRecords, recordIDsToDelete: [])
|
||||
contentUploadCount += articleRecords.count
|
||||
} catch {
|
||||
Self.logger.error("CloudKitArticlesZone: modifyArticles content upload failed: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
return contentUploadCount
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl
|
||||
/// operation completes.
|
||||
private(set) var sentCount = 0
|
||||
|
||||
/// Whether any statuses failed to send. Read after the operation completes.
|
||||
private(set) var didFail = false
|
||||
|
||||
init(account: Account, articlesZone: CloudKitArticlesZone, database: SyncDatabase, syncArticleContentForUnreadArticles: @escaping @Sendable () -> Bool, syncErrorHandler: CloudKitSyncErrorHandler?) {
|
||||
self.account = account
|
||||
self.accountID = account.accountID
|
||||
@@ -64,6 +67,7 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl
|
||||
activityLog.didComplete(id: activityID, message: message)
|
||||
}
|
||||
} catch {
|
||||
self.didFail = true
|
||||
Self.logger.debug("iCloud: Send status error: \(error.localizedDescription)")
|
||||
activityLog.didFail(id: activityID, error: error)
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
private let syncDatabase: SyncDatabase
|
||||
let syncDatabase: SyncDatabase
|
||||
private let caller: FeedbinAPICaller
|
||||
private var articlesRefreshedCount = 0
|
||||
private static let logger = Feedbin.logger
|
||||
@@ -119,19 +119,39 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
|
||||
}
|
||||
|
||||
var sentCount = 0
|
||||
var savedError: Error?
|
||||
|
||||
let createUnreadStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == false })
|
||||
sentCount += try await sendArticleStatuses(createUnreadStatuses, apiCall: caller.createUnreadEntries)
|
||||
do {
|
||||
sentCount += try await sendArticleStatuses(createUnreadStatuses, apiCall: caller.createUnreadEntries)
|
||||
} catch {
|
||||
savedError = error
|
||||
}
|
||||
|
||||
let deleteUnreadStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == true })
|
||||
sentCount += try await sendArticleStatuses(deleteUnreadStatuses, apiCall: caller.deleteUnreadEntries)
|
||||
do {
|
||||
sentCount += try await sendArticleStatuses(deleteUnreadStatuses, apiCall: caller.deleteUnreadEntries)
|
||||
} catch {
|
||||
savedError = error
|
||||
}
|
||||
|
||||
let createStarredStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.starred && $0.flag == true })
|
||||
sentCount += try await sendArticleStatuses(createStarredStatuses, apiCall: caller.createStarredEntries)
|
||||
do {
|
||||
sentCount += try await sendArticleStatuses(createStarredStatuses, apiCall: caller.createStarredEntries)
|
||||
} catch {
|
||||
savedError = error
|
||||
}
|
||||
|
||||
let deleteStarredStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.starred && $0.flag == false })
|
||||
sentCount += try await sendArticleStatuses(deleteStarredStatuses, apiCall: caller.deleteStarredEntries)
|
||||
do {
|
||||
sentCount += try await sendArticleStatuses(deleteStarredStatuses, apiCall: caller.deleteStarredEntries)
|
||||
} catch {
|
||||
savedError = error
|
||||
}
|
||||
|
||||
if let savedError {
|
||||
throw savedError
|
||||
}
|
||||
return sentCount
|
||||
}
|
||||
} catch {
|
||||
@@ -569,7 +589,8 @@ private extension FeedbinAccountDelegate {
|
||||
}
|
||||
|
||||
func refreshArticlesAndStatuses(_ account: Account) async throws {
|
||||
try await sendArticleStatus()
|
||||
// A failed status send must not block fetching new articles.
|
||||
try? await sendArticleStatus()
|
||||
try await refreshArticleStatus()
|
||||
try await refreshArticles(account)
|
||||
try await refreshMissingArticles(account)
|
||||
|
||||
@@ -57,6 +57,8 @@ import Secrets
|
||||
|
||||
var credentials: Credentials? {
|
||||
didSet {
|
||||
reauthorizationDidFailDefinitively = false
|
||||
|
||||
#if DEBUG
|
||||
// https://developer.feedly.com/v3/developer/
|
||||
if let devToken = ProcessInfo.processInfo.environment["FEEDLY_DEV_ACCESS_TOKEN"], !devToken.isEmpty {
|
||||
@@ -106,6 +108,9 @@ import Secrets
|
||||
// endpoint read as abuse to Feedly and earn the 403 ban.
|
||||
private var reauthorizeTask: Task<Bool, Never>?
|
||||
|
||||
// A rejected refresh token is rejected on the next 401 too.
|
||||
private var reauthorizationDidFailDefinitively = false
|
||||
|
||||
// The refresh timer, background refresh, and the Refresh command can all fire
|
||||
// refreshAll — overlapping runs double the request volume and corrupt progress.
|
||||
private var refreshAllIsRunning = false
|
||||
@@ -1227,6 +1232,9 @@ extension FeedlyAccountDelegate: FeedlyAPICallerDelegate {
|
||||
/// Storing credentials updates `self.credentials` via `Account.storeCredentials`, which in turn
|
||||
/// hands the fresh access token to the caller.
|
||||
func reauthorizeFeedlyAPICaller() async -> Bool {
|
||||
guard !reauthorizationDidFailDefinitively else {
|
||||
return false
|
||||
}
|
||||
if let reauthorizeTask {
|
||||
return await reauthorizeTask.value
|
||||
}
|
||||
@@ -1272,6 +1280,7 @@ extension FeedlyAccountDelegate: FeedlyAPICallerDelegate {
|
||||
} catch {
|
||||
Self.logger.error("Feedly: Refresh access token failed: \(error.localizedDescription)")
|
||||
if isDefinitiveReauthorizationError(error) {
|
||||
reauthorizationDidFailDefinitively = true
|
||||
account.postSyncError(error, operation: "Refreshing access token")
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -136,20 +136,24 @@ import os
|
||||
return
|
||||
}
|
||||
|
||||
// Key on the request URL: `URL(string:)` doesn’t always round-trip feed.url.
|
||||
urlToFeedDictionary.removeAll()
|
||||
var urls = Set<URL>()
|
||||
for feed in filteredFeeds {
|
||||
urlToFeedDictionary[feed.url] = feed
|
||||
guard let url = Self.url(for: feed) else {
|
||||
continue
|
||||
}
|
||||
urlToFeedDictionary[url.absoluteString] = feed
|
||||
urls.insert(url)
|
||||
}
|
||||
|
||||
let urls = filteredFeeds.compactMap { Self.url(for: $0) }
|
||||
|
||||
// This refresh replaces any in-flight one, so resume its caller rather than stranding it.
|
||||
if let previousCompletion = self.completion {
|
||||
previousCompletion()
|
||||
}
|
||||
|
||||
self.completion = completion
|
||||
downloadSession.download(Set(urls))
|
||||
downloadSession.download(urls)
|
||||
}
|
||||
|
||||
private var activityOwner: ActivityOwner? {
|
||||
|
||||
@@ -9,14 +9,13 @@ import Testing
|
||||
import RSWeb
|
||||
@testable import Account
|
||||
|
||||
@MainActor struct FeedbinFeedNameTests {
|
||||
@Suite(.isolatedWebserviceResponses) @MainActor struct FeedbinFeedNameTests {
|
||||
|
||||
private static let daringFireballFeedID = "1296379"
|
||||
|
||||
private let accountManager = TestAccountManager()
|
||||
|
||||
@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")
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//
|
||||
// FeedbinStatusSendTests.swift
|
||||
// AccountTests
|
||||
//
|
||||
// Created by Brent Simmons on 9/5/26.
|
||||
//
|
||||
|
||||
import Testing
|
||||
import RSWeb
|
||||
import SyncDatabase
|
||||
@testable import Account
|
||||
|
||||
@Suite(.isolatedWebserviceResponses) @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 {
|
||||
// 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 syncDatabase = try #require(account.delegate as? FeedbinAccountDelegate).syncDatabase
|
||||
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 == [])
|
||||
}
|
||||
|
||||
/// A failing status send used to abort the whole refresh, so an account stopped
|
||||
/// receiving new articles for as long as the send kept failing.
|
||||
@Test func failingStatusSendDoesNotBlockArticleRefresh() async throws {
|
||||
TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json")
|
||||
TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json")
|
||||
|
||||
// Only the send fails. The status refresh GETs this same path and must still succeed,
|
||||
// which is why this registration names a method.
|
||||
TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: "unread_entries.json", httpMethod: HTTPMethod.post)
|
||||
|
||||
let account = TestAccountManager.shared.createAccount(type: .feedbin)
|
||||
defer {
|
||||
TestAccountManager.shared.deleteAccount(account)
|
||||
}
|
||||
|
||||
let syncDatabase = try #require(account.delegate as? FeedbinAccountDelegate).syncDatabase
|
||||
await syncDatabase.insertStatuses([SyncStatus(articleID: "1", key: .read, flag: false)])
|
||||
|
||||
try await account.refreshAll()
|
||||
|
||||
// The send really did fail, so its row is still queued.
|
||||
let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs()
|
||||
#expect(pendingReadArticleIDs == ["1"])
|
||||
|
||||
#expect(account.flattenedFeeds().count == 224)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//
|
||||
// FeedlyReauthorizationTests.swift
|
||||
// AccountTests
|
||||
//
|
||||
// Created by Brent Simmons on 9/16/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
import RSWeb
|
||||
import Secrets
|
||||
@testable import Account
|
||||
|
||||
@Suite(.isolatedWebserviceResponses) @MainActor struct FeedlyReauthorizationTests {
|
||||
|
||||
private static let tokenEndpoint = "/v3/auth/token"
|
||||
|
||||
/// Every 401 in a refresh cycle used to spawn its own token POST, which is the
|
||||
/// abuse pattern that earns a 403 ban from Feedly.
|
||||
@Test func aRejectedRefreshTokenIsOnlyTriedOnce() async throws {
|
||||
TestingURLProtocol.setResponse(.init(statusCode: 400), forURLContaining: Self.tokenEndpoint, httpMethod: HTTPMethod.post)
|
||||
|
||||
let account = TestAccountManager.shared.createAccount(type: .feedly)
|
||||
defer {
|
||||
TestAccountManager.shared.deleteAccount(account)
|
||||
}
|
||||
let delegate = try #require(account.delegate as? FeedlyAccountDelegate)
|
||||
|
||||
// Unique per test — keychain entries are keyed by server and username.
|
||||
let username = UUID().uuidString
|
||||
try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: username, secret: "rejected-token"))
|
||||
|
||||
let firstResult = await delegate.reauthorizeFeedlyAPICaller()
|
||||
#expect(firstResult == false)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 1)
|
||||
|
||||
let secondResult = await delegate.reauthorizeFeedlyAPICaller()
|
||||
#expect(secondResult == false)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 1)
|
||||
}
|
||||
|
||||
/// The account has to recover when the user signs in again, rather than staying
|
||||
/// dead until relaunch.
|
||||
@Test func newCredentialsAllowAnotherAttempt() async throws {
|
||||
TestingURLProtocol.setResponse(.init(statusCode: 400), forURLContaining: Self.tokenEndpoint, httpMethod: HTTPMethod.post)
|
||||
|
||||
let account = TestAccountManager.shared.createAccount(type: .feedly)
|
||||
defer {
|
||||
TestAccountManager.shared.deleteAccount(account)
|
||||
}
|
||||
let delegate = try #require(account.delegate as? FeedlyAccountDelegate)
|
||||
|
||||
// Unique per test — keychain entries are keyed by server and username.
|
||||
let username = UUID().uuidString
|
||||
try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: username, secret: "rejected-token"))
|
||||
|
||||
_ = await delegate.reauthorizeFeedlyAPICaller()
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 1)
|
||||
|
||||
try account.storeCredentials(Credentials(type: .oauthAccessToken, username: username, secret: "fresh-token"))
|
||||
|
||||
_ = await delegate.reauthorizeFeedlyAPICaller()
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// IsolatedWebserviceResponsesTrait.swift
|
||||
// AccountTests
|
||||
//
|
||||
// Created by Brent Simmons on 9/9/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
import RSWeb
|
||||
|
||||
/// Gives each test its own `TestingURLProtocol` response table, so suites that stub
|
||||
/// webservice responses can run in parallel without seeing each other's registrations.
|
||||
///
|
||||
/// Apply it to a suite. It's recursive, so every test in that suite — and in any suite
|
||||
/// nested inside it — gets a fresh table, and the table is discarded when the test ends.
|
||||
struct IsolatedWebserviceResponsesTrait: TestTrait, SuiteTrait, TestScoping {
|
||||
|
||||
var isRecursive: Bool {
|
||||
true
|
||||
}
|
||||
|
||||
func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws {
|
||||
let testID = UUID().uuidString
|
||||
try await TestingURLProtocol.$currentTestID.withValue(testID) {
|
||||
defer {
|
||||
TestingURLProtocol.endTest(withID: testID)
|
||||
}
|
||||
try await function()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Trait where Self == IsolatedWebserviceResponsesTrait {
|
||||
|
||||
/// Gives each test its own `TestingURLProtocol` response table.
|
||||
static var isolatedWebserviceResponses: Self {
|
||||
Self()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// IsolatedWebserviceResponsesTraitTests.swift
|
||||
// AccountTests
|
||||
//
|
||||
// Created by Brent Simmons on 9/9/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
import RSWeb
|
||||
|
||||
@Suite(.isolatedWebserviceResponses) struct IsolatedWebserviceResponsesTraitTests {
|
||||
|
||||
private static let url = URL(string: "https://example.com/subscriptions.json")!
|
||||
|
||||
@Test func theTraitBindsATestID() {
|
||||
#expect(TestingURLProtocol.currentTestID != nil)
|
||||
}
|
||||
|
||||
@Test func responsesRegisteredHereAreInvisibleUnderAnotherTestID() async throws {
|
||||
TestingURLProtocol.setResponse(.init(statusCode: 418), forURLContaining: "subscriptions.json")
|
||||
|
||||
let mine = try await Self.statusCode()
|
||||
#expect(mine == 418)
|
||||
|
||||
let theirs = try await TestingURLProtocol.$currentTestID.withValue("another-test") {
|
||||
try await Self.statusCode()
|
||||
}
|
||||
#expect(theirs == 200)
|
||||
}
|
||||
}
|
||||
|
||||
private extension IsolatedWebserviceResponsesTraitTests {
|
||||
|
||||
static func statusCode() async throws -> Int {
|
||||
let session = URLSession.makeWebserviceSession()
|
||||
let (_, response) = try await session.data(from: url)
|
||||
return try #require(response as? HTTPURLResponse).statusCode
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
import Foundation
|
||||
import RSWeb
|
||||
import Secrets
|
||||
|
||||
@testable import Account
|
||||
|
||||
@@ -15,9 +16,9 @@ import RSWeb
|
||||
|
||||
nonisolated static let shared = TestAccountManager()
|
||||
|
||||
var accountsFolder: URL {
|
||||
return try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
}
|
||||
// Not Caches: macOS puts a `group:everyone deny delete` ACE on it, so test accounts
|
||||
// created there can't be removed afterward.
|
||||
private let accountsFolder = FileManager.default.temporaryDirectory.appendingPathComponent("NetNewsWireTestAccounts")
|
||||
|
||||
func createAccount(type: AccountType, username: String? = nil, password: String? = nil) -> Account {
|
||||
|
||||
@@ -31,22 +32,22 @@ import RSWeb
|
||||
abort()
|
||||
}
|
||||
|
||||
let account = Account(dataFolder: accountFolder.absoluteString, type: type, accountID: accountID)
|
||||
let account = Account(dataFolder: accountFolder.path, type: type, accountID: accountID)
|
||||
|
||||
return account
|
||||
}
|
||||
|
||||
func deleteAccount(_ account: Account) {
|
||||
|
||||
// Credentials live in the keychain, outside the account folder removed below.
|
||||
for credentialsType in CredentialsType.allCases {
|
||||
try? account.removeCredentials(type: credentialsType)
|
||||
}
|
||||
|
||||
account.deleteSettings()
|
||||
|
||||
do {
|
||||
try FileManager.default.removeItem(atPath: account.dataFolder)
|
||||
} catch let error as CocoaError where error.code == .fileNoSuchFile {
|
||||
|
||||
} catch {
|
||||
assertionFailure("Could not delete folder at: \(account.dataFolder) because \(error)")
|
||||
abort()
|
||||
}
|
||||
// Cleanup failing is not a test failure, and aborting here would take every
|
||||
// other test in the process down with it.
|
||||
try? FileManager.default.removeItem(atPath: account.dataFolder)
|
||||
}
|
||||
}
|
||||
@@ -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).")
|
||||
}
|
||||
responses[urlSubstring] = Response(statusCode: statusCode, data: data)
|
||||
setResponse(Response(statusCode: statusCode, data: data), forURLContaining: urlSubstring, httpMethod: httpMethod)
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ nonisolated public final class NetworkMonitor: Sendable {
|
||||
private let queue = DispatchQueue(label: "RSWeb NetworkMonitor")
|
||||
|
||||
private struct State: Sendable {
|
||||
var isConnected = false
|
||||
var isConnected: Bool?
|
||||
var connectionType: NWInterface.InterfaceType?
|
||||
var isExpensive = false
|
||||
var isConstrained = false
|
||||
@@ -24,8 +24,10 @@ nonisolated public final class NetworkMonitor: Sendable {
|
||||
|
||||
private let state = OSAllocatedUnfairLock<State>(initialState: State())
|
||||
|
||||
/// `true` until `NWPathMonitor` delivers its first path, so callers attempt
|
||||
/// network work rather than skip it on an answer we don't have yet.
|
||||
public var isConnected: Bool {
|
||||
state.withLock { $0.isConnected }
|
||||
state.withLock { $0.isConnected ?? true }
|
||||
}
|
||||
|
||||
public var connectionType: NWInterface.InterfaceType? {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import os
|
||||
|
||||
public final class TestingURLProtocol: URLProtocol {
|
||||
|
||||
@@ -20,13 +21,106 @@ public final class TestingURLProtocol: URLProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a URL substring to the response to return for matching requests.
|
||||
/// Populated by tests; consulted per request, so it may change between requests.
|
||||
nonisolated(unsafe) public static var responses = [String: Response]()
|
||||
/// 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?
|
||||
|
||||
/// Clears all registered responses. Call between tests.
|
||||
/// Carries `currentTestID` from the session's configuration to `startLoading`.
|
||||
public static let testIDHeaderField = "X-NetNewsWire-Testing-ID"
|
||||
|
||||
/// What a registered response answers: a URL substring, and optionally one HTTP method.
|
||||
private struct ResponseKey: Hashable {
|
||||
let urlSubstring: String
|
||||
let httpMethod: String?
|
||||
}
|
||||
|
||||
/// A request the protocol answered.
|
||||
private struct AnsweredRequest: Sendable {
|
||||
let urlString: String
|
||||
let httpMethod: String?
|
||||
}
|
||||
|
||||
/// What one test registered, and what it has been asked for since.
|
||||
private struct TestState: Sendable {
|
||||
var responses = [ResponseKey: Response]()
|
||||
var answeredRequests = [AnsweredRequest]()
|
||||
}
|
||||
|
||||
/// Maps a test ID to its state. Requests from a session built outside a
|
||||
/// `currentTestID` scope use `sharedTestID`.
|
||||
private static let testStates = OSAllocatedUnfairLock<[String: TestState]>(initialState: [:])
|
||||
|
||||
private static let sharedTestID = "shared"
|
||||
|
||||
/// Register the response to return for requests whose URL contains `urlSubstring`.
|
||||
/// 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
|
||||
let key = ResponseKey(urlSubstring: urlSubstring, httpMethod: httpMethod)
|
||||
testStates.withLock { $0[testID, default: TestState()].responses[key] = response }
|
||||
}
|
||||
|
||||
/// How many requests this test has been asked for whose URL contains `urlSubstring`.
|
||||
/// Pass `httpMethod` to count only that method. Counts requests whether or not a
|
||||
/// response was registered for them.
|
||||
public static func requestCount(forURLContaining urlSubstring: String, httpMethod: String? = nil) -> Int {
|
||||
let testID = currentTestID ?? sharedTestID
|
||||
return testStates.withLock { testStates in
|
||||
let answeredRequests = testStates[testID]?.answeredRequests ?? []
|
||||
return answeredRequests.count { answeredRequest in
|
||||
guard answeredRequest.urlString.contains(urlSubstring) else {
|
||||
return false
|
||||
}
|
||||
guard let httpMethod else {
|
||||
return true
|
||||
}
|
||||
return answeredRequest.httpMethod == httpMethod
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears everything recorded for the current test. Call between tests.
|
||||
public static func reset() {
|
||||
responses = [:]
|
||||
endTest(withID: currentTestID ?? sharedTestID)
|
||||
}
|
||||
|
||||
/// Discards one test's registrations and request history, for a scope that is ending.
|
||||
public static func endTest(withID testID: String) {
|
||||
testStates.withLock { $0[testID] = nil }
|
||||
}
|
||||
|
||||
private static func recordRequest(_ request: URLRequest) {
|
||||
guard let urlString = request.url?.absoluteString else {
|
||||
return
|
||||
}
|
||||
|
||||
let testID = request.value(forHTTPHeaderField: testIDHeaderField) ?? sharedTestID
|
||||
let answeredRequest = AnsweredRequest(urlString: urlString, httpMethod: request.httpMethod)
|
||||
testStates.withLock { $0[testID, default: TestState()].answeredRequests.append(answeredRequest) }
|
||||
}
|
||||
|
||||
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 testStates.withLock { testStates in
|
||||
guard let responsesForTest = testStates[testID]?.responses 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)
|
||||
}
|
||||
}
|
||||
|
||||
public override static func canInit(with request: URLRequest) -> Bool {
|
||||
@@ -44,8 +138,9 @@ public final class TestingURLProtocol: URLProtocol {
|
||||
return
|
||||
}
|
||||
|
||||
let urlString = url.absoluteString
|
||||
let match = Self.responses.first { urlString.contains($0.key) }?.value
|
||||
Self.recordRequest(request)
|
||||
|
||||
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.endTest(withID: "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.endTest(withID: 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
|
||||
}
|
||||
}
|
||||
@@ -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.endTest(withID: 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//
|
||||
// TestingURLProtocolRequestCountTests.swift
|
||||
// RSWebTests
|
||||
//
|
||||
// Created by Brent Simmons on 9/16/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
import RSCore
|
||||
@testable import RSWeb
|
||||
|
||||
struct TestingURLProtocolRequestCountTests {
|
||||
|
||||
private static let url = URL(string: "https://example.com/v3/auth/token")!
|
||||
private static let urlSubstring = "/v3/auth/token"
|
||||
|
||||
@Test func requestsAreCounted() async throws {
|
||||
try #require(Platform.isRunningUnitTests)
|
||||
|
||||
try await Self.withItsOwnResponses {
|
||||
TestingURLProtocol.setResponse(.init(statusCode: 400), forURLContaining: Self.urlSubstring)
|
||||
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 0)
|
||||
|
||||
try await Self.send(httpMethod: HTTPMethod.post)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 1)
|
||||
|
||||
try await Self.send(httpMethod: HTTPMethod.post)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 2)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func countingCanBeNarrowedToOneMethod() async throws {
|
||||
try #require(Platform.isRunningUnitTests)
|
||||
|
||||
try await Self.withItsOwnResponses {
|
||||
try await Self.send(httpMethod: HTTPMethod.post)
|
||||
try await Self.send(httpMethod: HTTPMethod.get)
|
||||
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.post) == 1)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.get) == 1)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 2)
|
||||
}
|
||||
}
|
||||
|
||||
/// A request with no registered response still counts, so a test can assert that a
|
||||
/// call it never stubbed was made — or wasn't.
|
||||
@Test func unstubbedRequestsAreCountedToo() async throws {
|
||||
try #require(Platform.isRunningUnitTests)
|
||||
|
||||
try await Self.withItsOwnResponses {
|
||||
try await Self.send(httpMethod: HTTPMethod.get)
|
||||
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 1)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: "/v3/never/called") == 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func anotherTestsRequestsAreNotCounted() async throws {
|
||||
try #require(Platform.isRunningUnitTests)
|
||||
|
||||
try await Self.withItsOwnResponses {
|
||||
try await Self.send(httpMethod: HTTPMethod.post)
|
||||
|
||||
let countInAnotherTest = try await TestingURLProtocol.$currentTestID.withValue("another-test") {
|
||||
try await Self.send(httpMethod: HTTPMethod.post)
|
||||
return TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring)
|
||||
}
|
||||
TestingURLProtocol.endTest(withID: "another-test")
|
||||
|
||||
#expect(countInAnotherTest == 1)
|
||||
#expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension TestingURLProtocolRequestCountTests {
|
||||
|
||||
/// Runs `body` against its own response table. RSWebTests has no trait to do this
|
||||
/// (`IsolatedWebserviceResponsesTrait` lives in AccountTests), so it's done by hand.
|
||||
static func withItsOwnResponses(_ body: () async throws -> Void) async throws {
|
||||
let testID = UUID().uuidString
|
||||
try await TestingURLProtocol.$currentTestID.withValue(testID) {
|
||||
defer {
|
||||
TestingURLProtocol.endTest(withID: testID)
|
||||
}
|
||||
try await body()
|
||||
}
|
||||
}
|
||||
|
||||
static func send(httpMethod: String) async throws {
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = httpMethod
|
||||
|
||||
let session = URLSession.makeWebserviceSession()
|
||||
_ = try await session.data(for: request)
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ extension CredentialsError: LocalizedError {
|
||||
}
|
||||
}
|
||||
|
||||
public enum CredentialsType: String, Sendable {
|
||||
public enum CredentialsType: String, CaseIterable, Sendable {
|
||||
case basic = "password"
|
||||
case newsBlurBasic = "newsBlurBasic"
|
||||
case newsBlurSessionID = "newsBlurSessionId"
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
import Foundation
|
||||
import RSCore
|
||||
import os
|
||||
import RSWeb
|
||||
|
||||
struct CacheCleaner {
|
||||
|
||||
@@ -26,28 +25,25 @@ struct CacheCleaner {
|
||||
return
|
||||
}
|
||||
|
||||
// If the image disk cache hasn't been flushed for 3 days and the network is available, delete it
|
||||
// If the image disk cache hasn't been flushed for 3 days, delete it
|
||||
if flushDate.addingTimeInterval(3600 * 24 * 3) < Date() {
|
||||
if NetworkMonitor.shared.isConnected {
|
||||
let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
|
||||
let faviconsFolderURL = tempDir.appendingPathComponent("Favicons")
|
||||
let imagesFolderURL = tempDir.appendingPathComponent("Images")
|
||||
let feedURLToIconURL = tempDir.appendingPathComponent("FeedURLToIconURLCache.plist")
|
||||
let homePageToIconURL = tempDir.appendingPathComponent("HomePageToIconURLCache.plist")
|
||||
let homePagesWithNoIconURL = tempDir.appendingPathComponent("HomePagesWithNoIconURLCache.plist")
|
||||
|
||||
let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
|
||||
let faviconsFolderURL = tempDir.appendingPathComponent("Favicons")
|
||||
let imagesFolderURL = tempDir.appendingPathComponent("Images")
|
||||
let feedURLToIconURL = tempDir.appendingPathComponent("FeedURLToIconURLCache.plist")
|
||||
let homePageToIconURL = tempDir.appendingPathComponent("HomePageToIconURLCache.plist")
|
||||
let homePagesWithNoIconURL = tempDir.appendingPathComponent("HomePagesWithNoIconURLCache.plist")
|
||||
|
||||
for tempItem in [faviconsFolderURL, imagesFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] {
|
||||
do {
|
||||
logger.info("Removing cache file: \(tempItem.absoluteString)")
|
||||
try FileManager.default.removeItem(at: tempItem)
|
||||
} catch {
|
||||
logger.error("Could not delete cache file: \(error.localizedDescription)")
|
||||
}
|
||||
for tempItem in [faviconsFolderURL, imagesFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] {
|
||||
do {
|
||||
logger.info("Removing cache file: \(tempItem.absoluteString)")
|
||||
try FileManager.default.removeItem(at: tempItem)
|
||||
} catch {
|
||||
logger.error("Could not delete cache file: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
AppDefaults.shared.lastImageCacheFlushDate = Date()
|
||||
}
|
||||
|
||||
AppDefaults.shared.lastImageCacheFlushDate = Date()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+25
-13
@@ -87,13 +87,10 @@ import Images
|
||||
self.updateBadge()
|
||||
}
|
||||
|
||||
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, _) in
|
||||
if granted {
|
||||
DispatchQueue.main.async {
|
||||
UIApplication.shared.registerForRemoteNotifications()
|
||||
}
|
||||
}
|
||||
}
|
||||
// Silent CloudKit pushes don’t need notification permission. setBadgeCount does.
|
||||
UIApplication.shared.registerForRemoteNotifications()
|
||||
|
||||
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { _, _ in }
|
||||
|
||||
UNUserNotificationCenter.current().delegate = self
|
||||
UserNotificationManager.shared.start()
|
||||
@@ -423,8 +420,14 @@ private extension AppDelegate {
|
||||
|
||||
let refreshTaskIsCompleted = OSAllocatedUnfairLock(initialState: false)
|
||||
|
||||
enum RefreshOutcome {
|
||||
case completed
|
||||
case noNetwork
|
||||
case expired
|
||||
}
|
||||
|
||||
/// Make sure task.setTaskCompleted is called exactly once.
|
||||
func completeRefreshTask(success: Bool) {
|
||||
func completeRefreshTask(_ outcome: RefreshOutcome) {
|
||||
let shouldComplete = refreshTaskIsCompleted.withLock { isCompleted -> Bool in
|
||||
if isCompleted {
|
||||
return false
|
||||
@@ -435,11 +438,20 @@ private extension AppDelegate {
|
||||
guard shouldComplete else {
|
||||
return
|
||||
}
|
||||
if success {
|
||||
|
||||
let success: Bool
|
||||
switch outcome {
|
||||
case .completed:
|
||||
Self.logger.info("Background refresh completed.")
|
||||
} else {
|
||||
success = true
|
||||
case .noNetwork:
|
||||
Self.logger.info("Background refresh skipped — no network path.")
|
||||
success = false
|
||||
case .expired:
|
||||
Self.logger.info("Background refresh terminated for running too long.")
|
||||
success = false
|
||||
}
|
||||
|
||||
task.setTaskCompleted(success: success)
|
||||
}
|
||||
|
||||
@@ -447,17 +459,17 @@ private extension AppDelegate {
|
||||
if AccountManager.shared.isSuspended {
|
||||
AccountManager.shared.resumeAll()
|
||||
}
|
||||
await AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log)
|
||||
let didRefresh = await AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log)
|
||||
if !Task.isCancelled {
|
||||
await WidgetDataEncoder.shared?.encodeAndWait()
|
||||
}
|
||||
self.suspendApplication()
|
||||
completeRefreshTask(success: true)
|
||||
completeRefreshTask(didRefresh ? .completed : .noNetwork)
|
||||
}
|
||||
|
||||
task.expirationHandler = {
|
||||
refreshTask.cancel()
|
||||
completeRefreshTask(success: false)
|
||||
completeRefreshTask(.expired)
|
||||
Task { @MainActor in
|
||||
self.suspendApplication()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user