From 11a40ce9da7f3c4088bbbbbb1d9c7d7084da30c9 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 13 Nov 2026 10:42:31 +0100 Subject: [PATCH] test: fix flaky unit and ui tests --- .github/workflows/unit-tests.yml | 5 +++ Bitkit/Services/BackupService.swift | 12 +++++- Bitkit/Utilities/AppReset.swift | 6 ++- Bitkit/Utilities/Deadline.swift | 11 +++-- BitkitTests/BackupServiceTests.swift | 5 +-- .../PaykitPaymentRequestServiceTests.swift | 26 +++++++++++- BitkitTests/PaykitSdkIdentityCheckTests.swift | 13 +++--- BitkitTests/ProfileDestinationViewTests.swift | 40 +++++++++++++++---- BitkitTests/ServerConnectionResetTests.swift | 37 +++++++++++++---- BitkitUITests/BitkitUITests.swift | 32 --------------- BitkitUITests/BitkitUITestsLaunchTests.swift | 24 ----------- BitkitUITests/UsdtWalletUITests.swift | 28 ++++++++++--- 12 files changed, 148 insertions(+), 91 deletions(-) delete mode 100644 BitkitUITests/BitkitUITests.swift delete mode 100644 BitkitUITests/BitkitUITestsLaunchTests.swift diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 26038fe9ce..e44892197f 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -45,6 +45,8 @@ jobs: echo "✅ Simulator started at $(date)" - name: Run unit tests + # Leaves time for the upload below when a slow runner's build ate most of the job's hour + timeout-minutes: 55 run: | echo "⏱️ Starting unit tests at $(date)" set -o pipefail && xcodebuild test \ @@ -56,6 +58,9 @@ jobs: -skipPackageUpdates \ -enableCodeCoverage NO \ -parallel-testing-enabled NO \ + -test-timeouts-enabled YES \ + -default-test-execution-time-allowance 300 \ + -maximum-test-execution-time-allowance 300 \ -skip-testing:BitkitTests/UtxoSelectionTests \ -skip-testing:BitkitTests/AddressTypeIntegrationTests \ -skip-testing:BitkitTests/RNMigrationCleanupTests \ diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 536de26ed4..f4eade4472 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1071,8 +1071,18 @@ class BackupService { private func scheduleBackup(category: BackupCategory, initialOutcome: BackupOutcome = .failed, foregroundGeneration: UInt64? = nil) async { try? await ServiceQueue.background(.backup) { [self] in + // A request made before a wipe or restore began can arrive after it: drop it, and clear the running flag that + // `markBackupRequired` set for it, which would otherwise keep the category from being scheduled again + guard !shouldSkipBackup(category: category) else { + if backupJobs[category] == nil, runningBackupTasks[category] == nil { + updateBackupStatus(category: category) { status in + BackupItemStatus(synced: status.synced, required: status.required, running: false) + } + } + return + } if let foregroundGeneration { - guard isObserving, !shouldSkipBackup(category: category), + guard isObserving, stateQueue.sync(execute: { foregroundObservationGeneration == foregroundGeneration }) else { return } } diff --git a/Bitkit/Utilities/AppReset.swift b/Bitkit/Utilities/AppReset.swift index 76be1efa63..3ff34ddd56 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -156,7 +156,11 @@ final class AppReset: WipeStepExecutor { /// A hung remote cleanup must not hold the wipe; what it leaves behind is recoverable from the seed. static func runRemoteCleanup(timeout: Duration = .seconds(15), _ cleanup: @escaping () async -> Void) async { - guard await withDeadline(timeout, cleanup) == nil else { return } + await runRemoteCleanup(until: { try await Task.sleep(for: timeout) }, cleanup) + } + + static func runRemoteCleanup(until deadline: @escaping () async throws -> Void, _ cleanup: @escaping () async -> Void) async { + guard await withDeadline(until: deadline, cleanup) == nil else { return } Logger.warn("Remote cleanup timed out, continuing the wipe", context: "AppReset") } diff --git a/Bitkit/Utilities/Deadline.swift b/Bitkit/Utilities/Deadline.swift index 5f7e3e19ef..f1931bff2a 100644 --- a/Bitkit/Utilities/Deadline.swift +++ b/Bitkit/Utilities/Deadline.swift @@ -3,15 +3,20 @@ import Foundation /// Returns nil once `timeout` passes, without waiting for an operation that ignores cancellation. The operation is cancelled /// either way. func withDeadline(_ timeout: Duration, _ operation: @escaping () async -> T) async -> T? { + await withDeadline(until: { try await Task.sleep(for: timeout) }, operation) +} + +/// Returns nil once `deadline` returns, like `withDeadline(_:_:)` with a deadline other than a clock's. +func withDeadline(until deadline: @escaping () async throws -> Void, _ operation: @escaping () async -> T) async -> T? { let (results, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingOldest(1)) let work = Task { await continuation.yield(operation()) } - let deadline = Task { - try await Task.sleep(for: timeout) + let deadlineTask = Task { + try await deadline() continuation.yield(nil) } defer { work.cancel() - deadline.cancel() + deadlineTask.cancel() continuation.finish() } diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index 5a2a7a36c8..1102dab8e8 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -222,10 +222,9 @@ final class BackupServiceTests: XCTestCase { } func testTemporaryFailureRemainsPendingAcrossServiceRestart() async throws { - let suite = "BackupServiceTests.\(UUID().uuidString)" - let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } for category in [BackupCategory.wallet, .usdt] { + // Its own suite per category: a stopped service's jobs can still rewrite the statuses of the suite it used + let defaults = try makeIsolatedDefaults("\(#function).\(category)") let unavailable = BackupService(defaults: defaults, backupData: { _ in throw PaykitError.SharedStateBusy(code: "shared_state_busy", context: "pending reconciliation") }, waitForBackupDelay: { try await Task.sleep(nanoseconds: 60_000_000_000) }) diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index ed48c2f7b3..b5454dfca1 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -3108,7 +3108,7 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { to: target ) } - try await waitUntil { await sdk.uploadIsPaused() } + try await waitUntil(before: proposal) { await sdk.uploadIsPaused() } switch change { case "expired": clock.advance(by: 60) case "removed": await manager.refreshEligibleTargets(savedPublicKeys: []) @@ -11540,6 +11540,7 @@ private final class PaymentRequestTestClock: @unchecked Sendable { private enum PaymentRequestTestError: Error { case timedOut + case endedFirst } private actor PaymentProofProtectionGate { @@ -11630,6 +11631,29 @@ private final class PaymentRequestIntakeError: PrivateOperationError, @unchecked } } +/// Polls with no time limit, as on a slow runner `condition` can take seconds to hold, and fails at once when `operation` +/// ends without it holding. +@MainActor +private func waitUntil(before operation: Task, condition: @MainActor () async -> Bool) async throws { + let ended = OperationEndFlag() + Task { @MainActor in + _ = await operation.result + ended.isSet = true + } + while await !condition() { + guard !ended.isSet else { + guard await condition() else { throw PaymentRequestTestError.endedFirst } + return + } + try await Task.sleep(for: .milliseconds(10)) + } +} + +@MainActor +private final class OperationEndFlag { + var isSet = false +} + @MainActor private func waitUntil( timeout: Duration = .seconds(2), diff --git a/BitkitTests/PaykitSdkIdentityCheckTests.swift b/BitkitTests/PaykitSdkIdentityCheckTests.swift index 585c24904f..ba5c642597 100644 --- a/BitkitTests/PaykitSdkIdentityCheckTests.swift +++ b/BitkitTests/PaykitSdkIdentityCheckTests.swift @@ -975,12 +975,15 @@ final class PaykitSdkIdentityCheckTests: XCTestCase { try Keychain.upsert(key: .pubkySecretKey, data: Data(oldSecret.utf8)) let readEntered = expectation(description: "the old cleanup is reading SDK state") - let cleanupEnded = expectation(description: "the abandoned cleanup returns") + // The wipe stops waiting once the cleanup is held in its read, however long the cleanup takes to get there + let readEnteredGate = AsyncGate() + let cleanupEnded = AsyncGate() let readGate = AsyncGate() defer { readGate.open() } let oldSdk = AbandonedCleanupSdk(noPointer: .init()) let suspendRead = { readEntered.fulfill() + readEnteredGate.open() // Like the UniFFI call, it ignores Swift cancellation await readGate.wait() } @@ -1002,7 +1005,7 @@ final class PaykitSdkIdentityCheckTests: XCTestCase { let wipe = Task { try await service.withWalletWipe { - await AppReset.runRemoteCleanup(timeout: .milliseconds(100)) { + await AppReset.runRemoteCleanup(until: { await readEnteredGate.wait() }) { switch heldRead { case .registry, .revision: _ = try? await service.syncPublicEndpoints([]) @@ -1011,15 +1014,15 @@ final class PaykitSdkIdentityCheckTests: XCTestCase { case .peers, .linkRecovery: _ = try? await service.clearPrivatePaymentLists(to: oldSdk.recoveringPeers, isSessionCurrent: { !Task.isCancelled }) } - cleanupEnded.fulfill() + cleanupEnded.open() } // The wipe clears these once it has stopped waiting for the cleanup try Keychain.delete(key: .pubkySecretKey) try Keychain.delete(key: oldGenerationKey) } } - await fulfillment(of: [readEntered], timeout: 2) try await wipe.value + await fulfillment(of: [readEntered], timeout: 0) XCTAssertNil(try Keychain.load(key: oldGenerationKey)) // The next wallet's first operation creates its own SDK and identity before the old response arrives @@ -1029,7 +1032,7 @@ final class PaykitSdkIdentityCheckTests: XCTestCase { XCTAssertTrue(replacementSdk.mutations.isEmpty) readGate.open() - await fulfillment(of: [cleanupEnded], timeout: 2) + await cleanupEnded.wait() XCTAssertNil(try Keychain.load(key: oldGenerationKey), "Completed wipe must not recreate the old identity's keychain state") let alreadyStartedMutations = heldRead == .linkRecovery ? ["recoverLink"] : [] diff --git a/BitkitTests/ProfileDestinationViewTests.swift b/BitkitTests/ProfileDestinationViewTests.swift index 319d615185..9501cc699b 100644 --- a/BitkitTests/ProfileDestinationViewTests.swift +++ b/BitkitTests/ProfileDestinationViewTests.swift @@ -282,12 +282,12 @@ final class ProfileDestinationViewTests: XCTestCase { defer { disconnectGate.finish() } let disconnect = Task { try await manager.signOut { - disconnectGate.started.fulfill() + disconnectGate.markStarted() for await _ in disconnectGate.stream {} throw PubkyServiceError.sessionNotActive } } - await fulfillment(of: [disconnectGate.started], timeout: 3) + await disconnectGate.assertReached(by: disconnect) try await Task.sleep(for: .milliseconds(100)) XCTAssertEqual(manager.profileForDisplay?.name, profile.name) disconnectGate.finish() @@ -311,7 +311,7 @@ final class ProfileDestinationViewTests: XCTestCase { let retryGate = await response.holdNextRequest() defer { retryGate.finish() } let retry = Task { await manager.loadProfile() } - await fulfillment(of: [retryGate.started], timeout: 3) + await retryGate.assertReached(by: retry) XCTAssertTrue(manager.isLoadingProfile) XCTAssertEqual(manager.profileForDisplay?.name, profile.name) retryGate.finish() @@ -437,7 +437,7 @@ private final class ContactsRecoveryProfileManager: PubkyProfileManager { } override func hasExistingIdentityForNavigation(hasStoredIdentity: @escaping @Sendable () throws -> Bool) async -> Bool { - lookup.started.fulfill() + lookup.markStarted() for await _ in lookup.stream {} return identityExists } @@ -449,7 +449,7 @@ private final class ContactsRecoveryProfileManager: PubkyProfileManager { didAttemptRecovery = true let gate = restoration await super.restoreSessionIfNeeded(hasStoredIdentity: { true }) { - gate.started.fulfill() + gate.markStarted() for await _ in gate.stream {} return .restorationFailed } @@ -486,10 +486,34 @@ private struct ProfileOperationGate { let started: XCTestExpectation let stream: AsyncStream private let continuation: AsyncStream.Continuation + private let reachedEvents: AsyncStream + private let reachedContinuation: AsyncStream.Continuation init(name: String) { started = XCTestExpectation(description: name) (stream, continuation) = AsyncStream.makeStream() + (reachedEvents, reachedContinuation) = AsyncStream.makeStream() + } + + func markStarted() { + started.fulfill() + reachedContinuation.yield(true) + } + + /// Waits with no time limit, as on a slow runner the operation can take seconds to reach the gate, and fails at once when + /// `operation` ends without reaching it. + func assertReached(by operation: Task, file: StaticString = #filePath, line: UInt = #line) async { + let events = reachedContinuation + Task { + _ = await operation.result + events.yield(false) + } + var reached = false + for await event in reachedEvents { + reached = event + break + } + XCTAssertTrue(reached, "\(started.expectationDescription) ended before reaching its gate", file: file, line: line) } func finish() { @@ -518,7 +542,7 @@ private actor ProfileResponse { func resolve() async throws -> PubkyProfile { if let gate { self.gate = nil - gate.started.fulfill() + gate.markStarted() for await _ in gate.stream {} } guard let profile else { throw URLError(.notConnectedToInternet) } @@ -537,7 +561,7 @@ private final class SuspendedProfileManager: PubkyProfileManager { ) async { let gate = restoration await super.restoreSessionIfNeeded(hasStoredIdentity: { true }) { - gate.started.fulfill() + gate.markStarted() for await _ in gate.stream {} throw PubkyServiceError.authFailed("offline") } @@ -547,7 +571,7 @@ private final class SuspendedProfileManager: PubkyProfileManager { isLoadingProfile = true defer { isLoadingProfile = false } let gate = profileFetch - gate.started.fulfill() + gate.markStarted() for await _ in gate.stream {} } } diff --git a/BitkitTests/ServerConnectionResetTests.swift b/BitkitTests/ServerConnectionResetTests.swift index f188270623..3b31713f83 100644 --- a/BitkitTests/ServerConnectionResetTests.swift +++ b/BitkitTests/ServerConnectionResetTests.swift @@ -33,7 +33,7 @@ final class ServerConnectionResetTests: XCTestCase { restartCount += 1 } } - await fulfillment(of: [endpoint.started], timeout: 3) + await endpoint.assertReached(by: connection) clearServerPreferencesAndReset() settings.rgsIsLoading = true @@ -56,7 +56,7 @@ final class ServerConnectionResetTests: XCTestCase { throw TestError.restartFailed } } - await fulfillment(of: [restart.started], timeout: 3) + await restart.assertReached(by: connection) clearServerPreferencesAndReset() settings.rgsIsLoading = true restart.resume(()) @@ -89,7 +89,7 @@ final class ServerConnectionResetTests: XCTestCase { waitCount += 1 }, isNodeRunning: { true }) } - await fulfillment(of: [restart.started], timeout: 3) + await restart.assertReached(by: connection) clearServerPreferencesAndReset() settings.electrumHost = "new.example.com" settings.electrumIsLoading = true @@ -112,7 +112,7 @@ final class ServerConnectionResetTests: XCTestCase { await wait.wait() }, isNodeRunning: { true }) } - await fulfillment(of: [wait.started], timeout: 3) + await wait.assertReached(by: connection) clearServerPreferencesAndReset() wait.resume(()) @@ -140,7 +140,8 @@ final class ServerConnectionResetTests: XCTestCase { await electrumRestart.wait() }, waitForConnection: {}, isNodeRunning: { true }) } - await fulfillment(of: [restart.started, electrumRestart.started], timeout: 3) + await restart.assertReached(by: connection) + await electrumRestart.assertReached(by: electrumConnection) let invalidated = expectation(description: "Wipe invalidates the pending connection") let observation = settings.$rgsIsLoading.dropFirst().filter { !$0 }.first().sink { _ in invalidated.fulfill() } @@ -247,7 +248,7 @@ final class ServerConnectionResetTests: XCTestCase { XCTFail("Cancelled request must not restart the node") }) } - await fulfillment(of: [endpoint.started], timeout: 3) + await endpoint.assertReached(by: connection) connection.cancel() endpoint.resume(true) @@ -273,15 +274,20 @@ final class ServerConnectionResetTests: XCTestCase { } } +/// Holds a connection at one of its suspension points. Waiting for it to get there has no time limit: on a slow runner it +/// can take seconds, and a connection that returns without getting there fails the test at once. @MainActor private final class ConnectionGate { - let started = XCTestExpectation(description: "Connection reached suspended operation") private var continuation: CheckedContinuation? + private var hasStarted = false + private var reachedWaiter: CheckedContinuation? func wait() async -> Value { await withCheckedContinuation { continuation = $0 - started.fulfill() + hasStarted = true + reachedWaiter?.resume(returning: true) + reachedWaiter = nil } } @@ -289,4 +295,19 @@ private final class ConnectionGate { continuation?.resume(returning: value) continuation = nil } + + func assertReached(by connection: Task, file: StaticString = #filePath, line: UInt = #line) async { + let reached = await reached(by: connection) + XCTAssertTrue(reached, "The connection returned before reaching the gate", file: file, line: line) + } + + private func reached(by connection: Task) async -> Bool { + guard !hasStarted else { return true } + Task { + _ = await connection.value + reachedWaiter?.resume(returning: hasStarted) + reachedWaiter = nil + } + return await withCheckedContinuation { reachedWaiter = $0 } + } } diff --git a/BitkitUITests/BitkitUITests.swift b/BitkitUITests/BitkitUITests.swift deleted file mode 100644 index d7786fb2e1..0000000000 --- a/BitkitUITests/BitkitUITests.swift +++ /dev/null @@ -1,32 +0,0 @@ -import XCTest - -final class BitkitUITests: XCTestCase { - override func setUpWithError() throws { - // Put setup code here. This method is called before the invocation of each test method in the class. - - // In UI tests it is usually best to stop immediately when a failure occurs. - continueAfterFailure = false - - // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp - // method is a good place to do this. - } - - override func tearDownWithError() throws { - // Put teardown code here. This method is called after the invocation of each test method in the class. - } - - func testExample() { - // UI tests must launch the application that they test. - let app = XCUIApplication() - app.launch() - - // Use XCTAssert and related functions to verify your tests produce the correct results. - } - - func testLaunchPerformance() { - // This measures how long it takes to launch your application. - measure(metrics: [XCTApplicationLaunchMetric()]) { - XCUIApplication().launch() - } - } -} diff --git a/BitkitUITests/BitkitUITestsLaunchTests.swift b/BitkitUITests/BitkitUITestsLaunchTests.swift deleted file mode 100644 index 8f59e9dd10..0000000000 --- a/BitkitUITests/BitkitUITestsLaunchTests.swift +++ /dev/null @@ -1,24 +0,0 @@ -import XCTest - -final class BitkitUITestsLaunchTests: XCTestCase { - override class var runsForEachTargetApplicationUIConfiguration: Bool { - true - } - - override func setUpWithError() throws { - continueAfterFailure = false - } - - func testLaunch() { - let app = XCUIApplication() - app.launch() - - // Insert steps here to perform after app launch but before taking a screenshot, - // such as logging into a test account or navigating somewhere in the app - - let attachment = XCTAttachment(screenshot: app.screenshot()) - attachment.name = "Launch Screen" - attachment.lifetime = .keepAlways - add(attachment) - } -} diff --git a/BitkitUITests/UsdtWalletUITests.swift b/BitkitUITests/UsdtWalletUITests.swift index 40824b1067..275ca66c93 100644 --- a/BitkitUITests/UsdtWalletUITests.swift +++ b/BitkitUITests/UsdtWalletUITests.swift @@ -116,8 +116,7 @@ final class UsdtWalletUITests: XCTestCase { } XCTAssertTrue(app.buttons["UsdtWallet"].waitForExistence(timeout: 90)) capture(app, "USDT home") - app.buttons["UsdtWallet"].tap() - XCTAssertTrue(app.buttons["UsdtReceive"].waitForExistence(timeout: 5)) + openUsdtWallet(app) app.buttons["UsdtReceive"].tap() XCTAssertTrue(app.buttons["UsdtReceiveDetails"].waitForExistence(timeout: 30)) capture(app, "USDT receive") @@ -188,6 +187,20 @@ final class UsdtWalletUITests: XCTestCase { capture(app, "USDT saved activity offline after restart") } + /// Until the wallet's push ends, Home's own Receive is under the wallet's, so a tap can open Bitcoin Receive instead. + @MainActor + private func openUsdtWallet(_ app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { + app.buttons["UsdtWallet"].tap() + let homeReceive = app.buttons.matching(NSPredicate(format: "identifier == %@", "Receive")).firstMatch + XCTAssertTrue(wait(for: homeReceive, toMatch: "exists == false OR hittable == false"), file: file, line: line) + XCTAssertTrue(wait(for: app.buttons["UsdtReceive"], toMatch: "hittable == true"), file: file, line: line) + } + + private func wait(for element: XCUIElement, toMatch predicate: String, timeout: TimeInterval = 5) -> Bool { + let expectation = XCTNSPredicateExpectation(predicate: NSPredicate(format: predicate), object: element) + return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed + } + @MainActor private func capture(_ app: XCUIApplication, _ name: String) { let attachment = XCTAttachment(screenshot: app.screenshot()) @@ -228,8 +241,7 @@ final class UsdtWalletUITests: XCTestCase { app.buttons["UsdtIntroEnable"].tap() } XCTAssertTrue(app.buttons["UsdtWallet"].waitForExistence(timeout: 90), app.debugDescription) - app.buttons["UsdtWallet"].tap() - XCTAssertTrue(app.buttons["UsdtReceive"].waitForExistence(timeout: 5)) + openUsdtWallet(app) app.buttons["UsdtReceive"].tap() XCTAssertTrue(app.buttons["UsdtReceiveDetails"].waitForExistence(timeout: 30)) let qr = app.descendants(matching: .any).matching(identifier: "QRCode").firstMatch @@ -284,7 +296,13 @@ final class UsdtWalletUITests: XCTestCase { let cameraAlert = XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts .containing(NSPredicate(format: "label CONTAINS[c] %@", "camera")).firstMatch XCTAssertTrue(cameraAlert.waitForExistence(timeout: 5)) - cameraAlert.buttons["Allow"].tap() + let allow = cameraAlert.buttons["Allow"] + XCTAssertTrue(wait(for: allow, toMatch: "hittable == true")) + allow.tap() + // A tap while the alert is still animating in can be dropped, leaving the alert up + if !cameraAlert.waitForNonExistence(timeout: 2), allow.exists { + allow.tap() + } XCTAssertTrue(cameraAlert.waitForNonExistence(timeout: 5)) XCTAssertTrue(app.buttons["UsdtManual"].waitForExistence(timeout: 5)) app.buttons["UsdtManual"].tap()