From c7e6b46feb9a2fece010bd6dbb59858bb5de0c93 Mon Sep 17 00:00:00 2001 From: Piotr Stachyra Date: Thu, 19 Nov 2026 14:24:54 +0100 Subject: [PATCH] test: stabilize contact and Paykit unit tests --- Bitkit/Services/PubkyService.swift | 4 +- Bitkit/Views/Contacts/AddContactView.swift | 2 + BitkitTests/AddContactViewTests.swift | 54 ++++++++++++------- BitkitTests/PaykitSdkOperationLockTests.swift | 13 ++--- 4 files changed, 46 insertions(+), 27 deletions(-) diff --git a/Bitkit/Services/PubkyService.swift b/Bitkit/Services/PubkyService.swift index e07ccf5657..8eb7216729 100644 --- a/Bitkit/Services/PubkyService.swift +++ b/Bitkit/Services/PubkyService.swift @@ -495,7 +495,7 @@ actor PaykitSdkService { private let sessionProvider = PaykitSdkSessionProvider() private let paymentAdapter = PaykitSdkPaymentAdapter() - private let operationLock = PaykitSdkOperationLock() + private let operationLock: PaykitSdkOperationLock private let publicReadSlots = PaykitPublicReadSlots() private let pubkyClientConfig = PaykitSdkService.makePubkyClientConfig(localTestnetHost: Env.pubkyLocalTestnetHost) private let sdkFactory: (() throws -> PaykitSdk)? @@ -515,9 +515,11 @@ actor PaykitSdkService { private var runtimeGeneration: UInt64 = 0 init( + operationLock: PaykitSdkOperationLock = PaykitSdkOperationLock(), sdkFactory: (() throws -> PaykitSdk)? = nil, bootstrapFactory: @escaping BootstrapFactory = PubkySessionBootstrap.withPubkyClientConfig(clientId:pubkyClient:) ) { + self.operationLock = operationLock self.sdkFactory = sdkFactory self.bootstrapFactory = bootstrapFactory } diff --git a/Bitkit/Views/Contacts/AddContactView.swift b/Bitkit/Views/Contacts/AddContactView.swift index 2e3fc0d32e..c426e3fc2d 100644 --- a/Bitkit/Views/Contacts/AddContactView.swift +++ b/Bitkit/Views/Contacts/AddContactView.swift @@ -13,6 +13,7 @@ struct AddContactView: View { let publicKey: String var loadPaymentEndpoint: (String) async throws -> Bool = PublicPaykitService.hasPayablePublicEndpoint + var onPaymentEndpointLookupCompleted: (() -> Void)? @State private var fetchedProfile: PubkyProfile? @State private var isLoading = true @@ -62,6 +63,7 @@ struct AddContactView: View { let hasEndpoint = await (try? loadPaymentEndpoint(profileKey)) == true guard !Task.isCancelled, fetchedProfile?.publicKey == profileKey else { return } hasPayableEndpoint = hasEndpoint + onPaymentEndpointLookupCompleted?() } } diff --git a/BitkitTests/AddContactViewTests.swift b/BitkitTests/AddContactViewTests.swift index 03e207f9d4..33deaca4ed 100644 --- a/BitkitTests/AddContactViewTests.swift +++ b/BitkitTests/AddContactViewTests.swift @@ -15,7 +15,7 @@ final class AddContactViewTests: XCTestCase { let started = expectation(description: "Endpoint lookup starts") let finished = expectation(description: "Endpoint lookup returns") var continuation: CheckedContinuation? - let window = host { _ in + let window = try host { _ in started.fulfill() let result = await withCheckedContinuation { continuation = $0 } finished.fulfill() @@ -38,14 +38,12 @@ final class AddContactViewTests: XCTestCase { } func testEndpointFailureKeepsContactPreviewVisible() async throws { - let attempted = expectation(description: "Endpoint lookup fails") - let window = host { _ in - attempted.fulfill() + let completed = expectation(description: "Contact preview handles the failed endpoint lookup") + let window = try host(onPaymentEndpointLookupCompleted: { completed.fulfill() }) { _ in throw TestError.offline } defer { close(window) } - await fulfillment(of: [attempted], timeout: 3) - try await Task.sleep(for: .milliseconds(100)) + await fulfillment(of: [completed], timeout: 10) let labels = try renderedLabels(window, name: "Contact after failed endpoint lookup") XCTAssertTrue(labels.contains("alice"), "Missing profile: \(labels)") XCTAssertTrue(labels.contains(t("common__save").lowercased()), "Missing Save: \(labels)") @@ -57,7 +55,7 @@ final class AddContactViewTests: XCTestCase { let finished = expectation(description: "Non-cancellable lookup returns") var continuation: CheckedContinuation? var wasCancelled = false - let window = host { _ in + let window = try host { _ in started.fulfill() let result = await withCheckedContinuation { continuation = $0 } wasCancelled = Task.isCancelled @@ -75,24 +73,40 @@ final class AddContactViewTests: XCTestCase { XCTAssertFalse(labels.contains(t("common__pay").lowercased())) } - private func host(endpoint: @escaping (String) async throws -> Bool) -> UIWindow { + private func host( + onPaymentEndpointLookupCompleted: (() -> Void)? = nil, + endpoint: @escaping (String) async throws -> Bool + ) throws -> UIWindow { let profile = PubkyProfileManager() profile.publicKey = "pubky" + String(repeating: "y", count: 52) - let view = AddContactView(publicKey: PreviewContactsManager.publicKey, loadPaymentEndpoint: endpoint) - .environmentObject(AppViewModel()) - .environmentObject(CurrencyViewModel(currencyService: OfflineCurrencyService())) - .environmentObject(NavigationViewModel()) - .environmentObject(PreviewContactsManager() as ContactsManager) - .environmentObject(profile) - .environmentObject(SettingsViewModel.shared) - .environmentObject(SheetViewModel()) - .environmentObject(WalletViewModel()) - .environment(HwWalletManager()) - .preferredColorScheme(.dark) - let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) + let view = AddContactView( + publicKey: PreviewContactsManager.publicKey, + loadPaymentEndpoint: endpoint, + onPaymentEndpointLookupCompleted: onPaymentEndpointLookupCompleted + ) + .environmentObject(AppViewModel()) + .environmentObject(CurrencyViewModel(currencyService: OfflineCurrencyService())) + .environmentObject(NavigationViewModel()) + .environmentObject(PreviewContactsManager() as ContactsManager) + .environmentObject(profile) + .environmentObject(SettingsViewModel.shared) + .environmentObject(SheetViewModel()) + .environmentObject(WalletViewModel()) + .environment(HwWalletManager()) + .preferredColorScheme(.dark) + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .first { $0.activationState == .foregroundActive }) + let previousKeyWindow = scene.keyWindow + addTeardownBlock { + await MainActor.run { previousKeyWindow?.makeKey() } + } + let window = UIWindow(windowScene: scene) + window.frame = CGRect(x: 0, y: 0, width: 390, height: 844) window.overrideUserInterfaceStyle = .dark window.rootViewController = UIHostingController(rootView: view) window.makeKeyAndVisible() + window.rootViewController?.view.layoutIfNeeded() return window } diff --git a/BitkitTests/PaykitSdkOperationLockTests.swift b/BitkitTests/PaykitSdkOperationLockTests.swift index e045d0610c..980d3e20e2 100644 --- a/BitkitTests/PaykitSdkOperationLockTests.swift +++ b/BitkitTests/PaykitSdkOperationLockTests.swift @@ -395,14 +395,15 @@ final class PaykitSdkOperationLockTests: XCTestCase { XCTAssertEqual(nativeOperation, operation == "orderedProof" ? "proof" : operation) await recorder.record("payment") } - let service = PaykitSdkService(sdkFactory: { sdk }) + let lock = PaykitSdkOperationLock() + let service = PaykitSdkService(operationLock: lock, sdkFactory: { sdk }) let active = Task { _ = try await service.contactRecords() } await fulfillment(of: [started], timeout: 2) let intake = Task { _ = try await service.receivePrivateMessagesFromLinkedPeers(priority: .background) } - try await Task.sleep(for: .milliseconds(50)) + await waitForWaiters(lock, count: 1) let barrier = orderedBarrier ? Task { _ = try await service.contactRecords() } : nil - if barrier != nil { - try await Task.sleep(for: .milliseconds(50)) + if orderedBarrier { + await waitForWaiters(lock, count: 2) } let payment = Task { do { @@ -426,7 +427,7 @@ final class PaykitSdkOperationLockTests: XCTestCase { XCTFail("Expected the SDK test operation to throw") } catch PaymentMutationReached.reached {} } - try await Task.sleep(for: .milliseconds(50)) + await waitForWaiters(lock, count: orderedBarrier ? 3 : 2) release.finish() try await active.value try await intake.value @@ -435,7 +436,7 @@ final class PaykitSdkOperationLockTests: XCTestCase { let events = await recorder.events let expected = orderedBarrier ? ["active", "intake", "ordered", "payment"] : operation == "orderedProof" ? ["active", "intake", "payment"] : ["active", "payment", "intake"] - XCTAssertEqual(events, expected) + XCTAssertEqual(events, expected, "Operation: \(operation), ordered barrier: \(orderedBarrier)") } } }