diff --git a/Normal/App/AppContainer.swift b/Normal/App/AppContainer.swift index ef30153..75f6ec2 100644 --- a/Normal/App/AppContainer.swift +++ b/Normal/App/AppContainer.swift @@ -8,7 +8,6 @@ struct AppContainer: View { @State private var nfcService = NFCService.shared @State private var qrService = QRService.shared @State private var locationService = LocationService.shared - @State private var keyManager = KeyManager() @State private var scheduleService: ScheduleService @State private var onboardingService = OnboardingService() @State private var appReviewService: AppReviewService @@ -31,7 +30,6 @@ struct AppContainer: View { .environment(nfcService) .environment(qrService) .environment(locationService) - .environment(keyManager) .environment(timedUnblockService) .environment(scheduleService) .environment(onboardingService) diff --git a/Normal/App/NormalApp.swift b/Normal/App/NormalApp.swift index ded6d75..c7f142b 100644 --- a/Normal/App/NormalApp.swift +++ b/Normal/App/NormalApp.swift @@ -49,6 +49,15 @@ struct NormalApp: App { context.insert(group) context.insert(Key(name: "Group Key", type: .qr, rawValue: "GROUP-VALUE", groupID: group.id)) } + if UITestSupport.seedLocationKey { + context.insert(Key( + name: "Test Place", + latitude: 37.33182, + longitude: -122.03118, + radiusMeters: 400, + radiusKind: .unblock + )) + } if UITestSupport.seedSchedule { context.insert(BlockSchedule( name: "Test Schedule", diff --git a/Normal/App/UITestSupport.swift b/Normal/App/UITestSupport.swift index 7dc5d07..12a4678 100644 --- a/Normal/App/UITestSupport.swift +++ b/Normal/App/UITestSupport.swift @@ -22,6 +22,8 @@ enum UITestSupport { static let seedGroupKey = arguments.contains("-uiTestSeedGroupKey") + static let seedLocationKey = arguments.contains("-uiTestSeedLocationKey") + static let seedGroupID = UUID(uuidString: "6E0A1C9B-2D4F-4B7A-9C3E-5F8D1A2B3C4D")! static let skipBypassConfirm = arguments.contains("-uiTestSkipBypassConfirm") diff --git a/Normal/Modifiers/WidgetActionResponder.swift b/Normal/Modifiers/WidgetActionResponder.swift index 2a711c3..21bb691 100644 --- a/Normal/Modifiers/WidgetActionResponder.swift +++ b/Normal/Modifiers/WidgetActionResponder.swift @@ -13,12 +13,17 @@ private struct WidgetActionResponder: ViewModifier { @Binding var selectedTab: AppTab @State private var authAction: (@MainActor () -> Void)? - @State private var actionGroup: AppGroup? - @State private var keyType: KeyType? - @State private var allowBypass = false - @State private var requestID: UUID? + @State private var active: ActiveRequest? + @State private var heldRequest: GroupActionRequest? @State private var durationTarget: UnblockTarget? + private struct ActiveRequest { + let token: UUID + let group: AppGroup + let keyType: KeyType? + let allowBypass: Bool + } + private var unblockDurations: [TimedUnblockDuration] { allSettings.first?.unblockDurations ?? TimedUnblockDuration.presets } @@ -27,12 +32,12 @@ private struct WidgetActionResponder: ViewModifier { content .protectedAction( $authAction, - allowBypass: allowBypass, - defaultKeyType: keyType, - keyGroupID: actionGroup?.id, - requestID: requestID + allowBypass: active?.allowBypass ?? false, + defaultKeyType: active?.keyType, + keyGroupID: active?.group.id, + requestID: active?.token ) - .sheet(item: $durationTarget) { target in + .sheet(item: $durationTarget, onDismiss: replayHeldRequest) { target in UnblockDurationSheet(target: target) } .onOpenURL { coordinator.handle(url: $0) } @@ -59,30 +64,31 @@ private struct WidgetActionResponder: ViewModifier { } private func resolve(_ request: GroupActionRequest?) { - guard let request, - durationTarget == nil, - allSettings.first?.hasCompletedOnboarding == true, - let group = groups.first(where: { $0.id == request.groupID }) - else { - coordinator.clearPendingGroupAction() + guard let request else { return } + coordinator.clearPendingGroupAction() + guard durationTarget == nil else { + heldRequest = request return } + guard allSettings.first?.hasCompletedOnboarding == true, + let group = groups.first(where: { $0.id == request.groupID }) + else { return } selectedTab = .groups - actionGroup = group - requestID = request.token switch request.action { - case let .unlock(duration, requestedKeyType): - keyType = requestedKeyType - allowBypass = false + case let .unlock(duration, keyType): + active = ActiveRequest(token: request.token, group: group, keyType: keyType, allowBypass: false) authAction = { unlock(group, duration: duration) } case .block: - keyType = nil - allowBypass = true + active = ActiveRequest(token: request.token, group: group, keyType: nil, allowBypass: true) authAction = { block(group) } } + } - coordinator.clearPendingGroupAction() + private func replayHeldRequest() { + guard let held = heldRequest else { return } + heldRequest = nil + resolve(held) } private func unlock(_ group: AppGroup, duration request: UnlockDurationRequest) { diff --git a/Normal/Services/Keys/KeyCheckFlow.swift b/Normal/Services/Keys/KeyCheckFlow.swift new file mode 100644 index 0000000..f702a3d --- /dev/null +++ b/Normal/Services/Keys/KeyCheckFlow.swift @@ -0,0 +1,204 @@ +import Foundation +import Observation + +protocol QRScanning: KeyScanning { + var isScanning: Bool { get } + func cancel() +} + +extension QRService: QRScanning {} + +@Observable +final class KeyCheckFlow { + struct Request { + let id = UUID() + let keys: [Key] + let availableKeyTypes: [KeyType] + let allowBypass: Bool + let defaultKeyType: KeyType? + } + + enum Stage: Equatable { + case idle + case noKeys + case choosing + case confirmingBypass + case scanningQR + case scanningNFC + case openingLocation + case checkingLocation + + var showsKeySheet: Bool { + switch self { + case .choosing, .confirmingBypass, .scanningQR: true + default: false + } + } + } + + enum SheetScreen: Equatable { + case picker + case bypassConfirm + case qrScanner + } + + private(set) var stage: Stage = .idle + private(set) var request: Request? + private(set) var sheetScreen: SheetScreen = .picker + private(set) var finishedRequestID: UUID? + + private let nfc: any KeyScanning + private let qr: any QRScanning + @ObservationIgnored private var qrScanRequestID: UUID? + @ObservationIgnored private var action: (@MainActor () -> Void)? + + init(nfc: any KeyScanning, qr: any QRScanning) { + self.nfc = nfc + self.qr = qr + } + + func start(_ request: Request, action: (@MainActor () -> Void)?) { + stopQRScan() + self.request = request + self.action = action + switch KeySelectLogic.decide( + availableKeyTypes: request.availableKeyTypes, + allowBypass: request.allowBypass, + defaultKeyType: request.defaultKeyType + ) { + case .showNoKeysAlert: + stage = .noKeys + case let .autoSelect(keyType): + begin(keyType) + case .showSheet: + sheetScreen = .picker + stage = .choosing + } + } + + func choose(_ keyType: KeyType) { + guard stage == .choosing else { return } + begin(keyType) + } + + func requestBypass(skippingConfirmation: Bool) { + guard stage == .choosing, request?.allowBypass == true else { return } + if skippingConfirmation { + complete() + } else { + sheetScreen = .bypassConfirm + stage = .confirmingBypass + } + } + + func confirmBypass() { + guard stage == .confirmingBypass, request?.allowBypass == true else { return } + complete() + } + + func returnFromBypassConfirm() { + guard stage == .confirmingBypass else { return } + sheetScreen = .picker + stage = .choosing + } + + func scannerAppeared() { + guard stage == .scanningQR, qrScanRequestID == nil, let request else { return } + qrScanRequestID = request.id + check(QRKeyMethod(qrService: qr, keys: request.keys), for: request) + } + + func locationVerified(requestID: UUID) { + guard stage == .checkingLocation, request?.id == requestID else { return } + complete() + } + + func keySheetClosed() { + guard stage.showsKeySheet else { return } + cancel() + } + + func keySheetDismissed() { + switch stage { + case .openingLocation: + stage = .checkingLocation + case let current where current.showsKeySheet: + break + default: + if qr.isScanning { + qr.cancel() + } + qrScanRequestID = nil + } + } + + func locationSheetClosed() { + guard stage == .checkingLocation else { return } + cancel() + } + + func cancel() { + stopQRScan() + finish() + } + + func hostCleared() { + guard stage != .idle else { return } + stopQRScan() + stage = .idle + request = nil + action = nil + } + + private func begin(_ keyType: KeyType) { + guard let request else { return } + switch keyType { + case .nfc: + stage = .scanningNFC + check(NFCKeyMethod(nfcService: nfc, keys: request.keys), for: request) + case .qr: + sheetScreen = .qrScanner + stage = .scanningQR + case .location: + stage = stage.showsKeySheet ? .openingLocation : .checkingLocation + } + } + + private func check(_ method: some KeyMethod, for request: Request) { + let requestID = request.id + Task { + let result = await method.checkKey() + scanFinished(result, requestID: requestID) + } + } + + private func scanFinished(_ result: KeyResult, requestID: UUID) { + if qrScanRequestID == requestID { + qrScanRequestID = nil + } + guard request?.id == requestID else { return } + if result == .success { + complete() + } else { + finish() + } + } + + private func complete() { + action?() + finish() + } + + private func finish() { + finishedRequestID = request?.id + stage = .idle + request = nil + action = nil + } + + private func stopQRScan() { + guard qrScanRequestID != nil else { return } + qrScanRequestID = nil + qr.cancel() + } +} diff --git a/Normal/Services/Keys/KeyManager.swift b/Normal/Services/Keys/KeyManager.swift deleted file mode 100644 index 9a7cace..0000000 --- a/Normal/Services/Keys/KeyManager.swift +++ /dev/null @@ -1,20 +0,0 @@ -import Foundation -import Observation - -@MainActor -@Observable -final class KeyManager { - @discardableResult - func performWithKeyCheck( - using method: KeyMethod, - action: @MainActor () -> Void - ) async -> Bool { - switch await method.checkKey() { - case .success: - action() - return true - case .failure, .cancelled: - return false - } - } -} diff --git a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift index d35b5b0..59ca25a 100644 --- a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift +++ b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift @@ -2,8 +2,6 @@ import SwiftData import SwiftUI struct KeySelectModifier: ViewModifier { - @Environment(KeyManager.self) private var keyManager - @Environment(NFCService.self) private var nfcService @Environment(QRService.self) private var qrService @Environment(LocationService.self) private var locationService @Query private var keys: [Key] @@ -15,24 +13,14 @@ struct KeySelectModifier: ViewModifier { var keyGroupID: UUID? var requestID: UUID? - @State private var flowID = UUID() - @State private var keySelectToken: PresentationToken? - @State private var locationCheck: LocationCheck? - @State private var pendingLocationCheck: LocationCheck? - @State private var presentedLocationFlowID: UUID? - @State private var locationAction: (@MainActor () -> Void)? - @State private var qrScanFlowID: UUID? - @State private var showQRScanner = false - @State private var showNoKeysAlert = false - @State private var showBypassConfirm = false + @State private var flow = KeyCheckFlow(nfc: NFCService.shared, qr: QRService.shared) - private struct PresentationToken: Identifiable { - let id = UUID() + private struct SheetID: Identifiable { + let id: UUID } private struct LocationCheck: Identifiable { - let id = UUID() - let flowID: UUID + let id: UUID let keys: [Key] } @@ -45,38 +33,33 @@ struct KeySelectModifier: ViewModifier { allSettings.unwrapped } - private var scopedKeys: [Key] { - Key.scoped(keys, toGroup: keyGroupID) - } - - private var availableKeyTypes: [KeyType] { - KeyType.selectable(registered: scopedKeys.map(\.type)) - } - func body(content: Content) -> some View { content .onChange(of: Trigger(hasAction: action != nil, requestID: requestID)) { _, trigger in if trigger.hasAction { - startFlow() + start() + } else { + flow.hostCleared() } } - .alert("No Keys Available", isPresented: $showNoKeysAlert) { - Button("OK", role: .cancel) { action = nil } + .onChange(of: flow.finishedRequestID) { _, _ in action = nil } + .alert("No Keys Available", isPresented: noKeysAlert) { + Button("OK", role: .cancel) { flow.cancel() } } message: { Text( - scopedKeys.isEmpty + flow.request?.keys.isEmpty ?? true ? "Add a key in the Keys tab before blocking apps." : "None of your registered keys are supported on this device. Add a QR code or barcode key to use on iPad." ) } - .sheet(item: $keySelectToken, onDismiss: onSheetDismiss) { _ in + .sheet(item: keySheet, onDismiss: flow.keySheetDismissed) { _ in keySelectSheet } - .sheet(item: $locationCheck, onDismiss: finishLocation) { check in + .sheet(item: locationSheet) { check in LocationUnlockSheet( keys: check.keys, provider: locationService, - onVerified: { verifyLocation(check) } + onVerified: { flow.locationVerified(requestID: check.id) } ) } } @@ -84,163 +67,81 @@ struct KeySelectModifier: ViewModifier { private var keySelectSheet: some View { NavigationStack { KeySelectView( - availableKeyTypes: availableKeyTypes, - allowBypass: allowBypass, - onSelect: handleSelection, - onBypass: requestBypass + availableKeyTypes: flow.request?.availableKeyTypes ?? [], + allowBypass: flow.request?.allowBypass ?? false, + onSelect: flow.choose, + onBypass: { flow.requestBypass(skippingConfirmation: settings.skipBlockWithoutKeyConfirmation) } ) - .navigationDestination(isPresented: $showBypassConfirm) { + .navigationDestination(isPresented: screen(.bypassConfirm, onBack: flow.returnFromBypassConfirm)) { BypassConfirmView { skipFuture in if skipFuture { settings.skipBlockWithoutKeyConfirmation = true } - bypassNow() + flow.confirmBypass() } } - .navigationDestination(isPresented: $showQRScanner) { + .navigationDestination(isPresented: screen(.qrScanner, onBack: {})) { QRScannerView(qrService: qrService) .navigationBarBackButtonHidden() .toolbar { ToolbarItem(placement: .cancellationAction) { - Button("Cancel") { - qrService.cancel() - keySelectToken = nil - } + Button("Cancel", action: flow.cancel) } } + .onAppear(perform: flow.scannerAppeared) } .toolbar { ToolbarItem(placement: .cancellationAction) { - Button("Cancel") { keySelectToken = nil } + Button("Cancel", action: flow.cancel) } } } - .presentationDetents(sheetDetents) - .presentationDragIndicator(showBypassConfirm ? .visible : .hidden) + .presentationDetents(flow.sheetScreen == .qrScanner ? [.large] : [.medium]) + .presentationDragIndicator(flow.sheetScreen == .bypassConfirm ? .visible : .hidden) } - private var sheetDetents: Set { - if showQRScanner { - return [.large] - } - return [.medium] - } - - private func startFlow() { - pendingLocationCheck = nil - locationCheck = nil - locationAction = nil - if qrScanFlowID != nil { - qrService.cancel() - } - flowID = UUID() - applyDecision() - } - - private func applyDecision() { - let decision = KeySelectLogic.decide( - availableKeyTypes: availableKeyTypes, - allowBypass: allowBypass, - defaultKeyType: defaultKeyType + private var noKeysAlert: Binding { + Binding( + get: { flow.stage == .noKeys }, + set: { if !$0 { flow.cancel() } } ) - switch decision { - case .showNoKeysAlert: - showNoKeysAlert = true - case let .autoSelect(keyType): - handleSelection(keyType) - case .showSheet: - showQRScanner = false - showBypassConfirm = false - keySelectToken = PresentationToken() - } - } - - private func requestBypass() { - if settings.skipBlockWithoutKeyConfirmation { - bypassNow() - } else { - showBypassConfirm = true - } - } - - private func handleSelection(_ choice: KeyType) { - switch choice { - case .nfc: - let pending = action - keySelectToken = nil - Task { await authenticate(with: .nfc, action: pending) } - case .qr: - guard qrScanFlowID != flowID else { return } - qrScanFlowID = flowID - let pending = action - showQRScanner = true - Task { await authenticate(with: .qr, action: pending) } - case .location: - locationAction = action - let check = LocationCheck(flowID: flowID, keys: scopedKeys) - if keySelectToken != nil { - pendingLocationCheck = check - keySelectToken = nil - } else { - present(check) - } - } - } - - private func present(_ check: LocationCheck) { - presentedLocationFlowID = check.flowID - locationCheck = check } - private func verifyLocation(_ check: LocationCheck) { - guard check.flowID == flowID else { return } - locationAction?() - } - - /// Leaves `showBypassConfirm` alone: flipping it here would swap the key - /// picker back in while the sheet is still animating away. - private func bypassNow() { - guard allowBypass else { return } - action?() - action = nil - keySelectToken = nil + private var keySheet: Binding { + Binding( + get: { flow.stage.showsKeySheet ? flow.request.map { SheetID(id: $0.id) } : nil }, + set: { if $0 == nil { flow.keySheetClosed() } } + ) } - private func authenticate(with choice: KeyType, action pending: (@MainActor () -> Void)?) async { - guard let pending else { return } - let flow = flowID - let method: KeyMethod = switch choice { - case .nfc: NFCKeyMethod(nfcService: nfcService, keys: scopedKeys) - case .qr: QRKeyMethod(qrService: qrService, keys: scopedKeys) - case .location: preconditionFailure("location uses its own popup") - } - _ = await keyManager.performWithKeyCheck(using: method) { pending() } - if qrScanFlowID == flow { - qrScanFlowID = nil - } - guard flow == flowID else { return } - keySelectToken = nil - action = nil + private var locationSheet: Binding { + Binding( + get: { + guard flow.stage == .checkingLocation, let request = flow.request else { return nil } + return LocationCheck(id: request.id, keys: request.keys) + }, + set: { if $0 == nil { flow.locationSheetClosed() } } + ) } - private func onSheetDismiss() { - guard keySelectToken == nil else { return } - if qrService.isScanning { - qrService.cancel() - } - - if let pending = pendingLocationCheck { - pendingLocationCheck = nil - present(pending) - return - } - action = nil + private func screen(_ screen: KeyCheckFlow.SheetScreen, onBack: @escaping () -> Void) -> Binding { + Binding( + get: { flow.sheetScreen == screen }, + set: { if !$0 { onBack() } } + ) } - private func finishLocation() { - guard locationCheck == nil, presentedLocationFlowID == flowID else { return } - locationAction = nil - action = nil + private func start() { + let scopedKeys = Key.scoped(keys, toGroup: keyGroupID) + flow.start( + KeyCheckFlow.Request( + keys: scopedKeys, + availableKeyTypes: KeyType.selectable(registered: scopedKeys.map(\.type)), + allowBypass: allowBypass, + defaultKeyType: defaultKeyType + ), + action: action + ) } } diff --git a/NormalTests/Services/KeyCheckFlowTests.swift b/NormalTests/Services/KeyCheckFlowTests.swift new file mode 100644 index 0000000..c6123fd --- /dev/null +++ b/NormalTests/Services/KeyCheckFlowTests.swift @@ -0,0 +1,309 @@ +import Foundation +@testable import Normal +import Testing + +@MainActor +struct KeyCheckFlowTests { + private let nfc = ControlledScanner() + private let qr = ControlledScanner() + private let flow: KeyCheckFlow + private let counter = Counter() + + private final class Counter { + var runs = 0 + } + + init() { + flow = KeyCheckFlow(nfc: nfc, qr: qr) + } + + private func key(_ type: KeyType, _ value: String) -> Key { + Key(name: value, type: type, rawValue: value) + } + + private func request( + _ keys: [Key], + available: [KeyType], + allowBypass: Bool = false, + defaultKeyType: KeyType? = nil + ) -> KeyCheckFlow.Request { + KeyCheckFlow.Request( + keys: keys, + availableKeyTypes: available, + allowBypass: allowBypass, + defaultKeyType: defaultKeyType + ) + } + + private func start(_ request: KeyCheckFlow.Request) { + let counter = counter + flow.start(request, action: { counter.runs += 1 }) + } + + private func waitUntil(_ condition: () -> Bool) async { + for _ in 0 ..< 10000 where !condition() { + await Task.yield() + } + #expect(condition()) + } + + private var qrAndNFC: KeyCheckFlow.Request { + request([key(.qr, "code"), key(.nfc, "tag")], available: [.nfc, .qr]) + } + + @Test func noKeysShowsTheAlertUntilCancelled() { + let request = request([], available: []) + start(request) + #expect(flow.stage == .noKeys) + + flow.cancel() + + #expect(flow.stage == .idle) + #expect(flow.finishedRequestID == request.id) + #expect(counter.runs == 0) + } + + @Test func severalKeyTypesShowThePicker() { + start(qrAndNFC) + #expect(flow.stage == .choosing) + #expect(flow.sheetScreen == .picker) + } + + @Test func defaultNFCKeyScansAndRunsTheAction() async { + start(request([key(.nfc, "tag"), key(.qr, "code")], available: [.nfc, .qr], defaultKeyType: .nfc)) + #expect(flow.stage == .scanningNFC) + + await waitUntil { nfc.isScanning } + nfc.present("tag") + await waitUntil { flow.stage == .idle } + + #expect(counter.runs == 1) + } + + @Test func rejectedTagEndsWithoutTheAction() async { + start(request([key(.nfc, "tag")], available: [.nfc])) + await waitUntil { nfc.isScanning } + + nfc.reject() + await waitUntil { flow.stage == .idle } + + #expect(counter.runs == 0) + } + + @Test func qrScanStartsOnceTheScannerAppears() async { + start(qrAndNFC) + flow.choose(.qr) + #expect(flow.stage == .scanningQR) + #expect(flow.sheetScreen == .qrScanner) + for _ in 0 ..< 100 { + await Task.yield() + } + #expect(qr.scanCount == 0) + + flow.scannerAppeared() + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + #expect(qr.scanCount == 1) + } + + @Test func repeatedChoiceIsIgnored() async { + start(qrAndNFC) + flow.choose(.qr) + flow.choose(.qr) + flow.choose(.nfc) + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + #expect(flow.stage == .scanningQR) + #expect(qr.scanCount == 1) + #expect(nfc.scanCount == 0) + } + + @Test func validCodeRunsTheActionOnce() async { + start(qrAndNFC) + flow.choose(.qr) + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + qr.present("code") + await waitUntil { flow.stage == .idle } + + #expect(counter.runs == 1) + } + + @Test func onlyTheRequestsOwnKeysPass() async { + start(request([key(.qr, "group-code")], available: [.qr])) + flow.choose(.qr) + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + qr.present("other-code") + #expect(qr.isScanning) + qr.present("group-code") + await waitUntil { flow.stage == .idle } + + #expect(counter.runs == 1) + } + + @Test func newerRequestCancelsTheRunningScan() async { + start(qrAndNFC) + flow.choose(.qr) + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + let newer = qrAndNFC + start(newer) + + #expect(!qr.isScanning) + #expect(flow.stage == .choosing) + #expect(flow.request?.id == newer.id) + #expect(counter.runs == 0) + } + + @Test func resultForAReplacedRequestIsIgnored() async { + start(request([key(.nfc, "tag")], available: [.nfc])) + await waitUntil { nfc.isScanning } + let newer = qrAndNFC + start(newer) + + nfc.present("tag") + for _ in 0 ..< 100 { + await Task.yield() + } + + #expect(counter.runs == 0) + #expect(flow.stage == .choosing) + #expect(flow.request?.id == newer.id) + } + + @Test func bypassNeedsPermission() { + start(qrAndNFC) + flow.requestBypass(skippingConfirmation: true) + #expect(flow.stage == .choosing) + #expect(counter.runs == 0) + } + + @Test func bypassWithoutConfirmationRunsTheAction() { + start(request([key(.qr, "code")], available: [.qr], allowBypass: true)) + flow.requestBypass(skippingConfirmation: true) + #expect(counter.runs == 1) + #expect(flow.stage == .idle) + } + + @Test func bypassConfirmationRunsTheAction() { + start(request([key(.qr, "code")], available: [.qr], allowBypass: true)) + flow.requestBypass(skippingConfirmation: false) + #expect(flow.stage == .confirmingBypass) + #expect(flow.sheetScreen == .bypassConfirm) + + flow.confirmBypass() + + #expect(counter.runs == 1) + #expect(flow.stage == .idle) + } + + @Test func goingBackFromTheConfirmationShowsThePicker() { + start(request([key(.qr, "code")], available: [.qr], allowBypass: true)) + flow.requestBypass(skippingConfirmation: false) + flow.returnFromBypassConfirm() + #expect(flow.stage == .choosing) + #expect(flow.sheetScreen == .picker) + } + + @Test func confirmationCannotRunANewerRequest() { + start(request([key(.qr, "code")], available: [.qr], allowBypass: true)) + flow.requestBypass(skippingConfirmation: false) + start(qrAndNFC) + + flow.confirmBypass() + + #expect(counter.runs == 0) + #expect(flow.stage == .choosing) + } + + @Test func locationOpensAfterThePickerCloses() { + start(request([key(.qr, "code")], available: [.qr, .location])) + flow.choose(.location) + #expect(flow.stage == .openingLocation) + + flow.keySheetDismissed() + + #expect(flow.stage == .checkingLocation) + } + + @Test func locationVerificationOnlyCountsForTheCurrentRequest() throws { + let request = request([], available: [.location], defaultKeyType: .location) + start(request) + #expect(flow.stage == .checkingLocation) + + flow.locationVerified(requestID: UUID()) + #expect(counter.runs == 0) + + flow.locationVerified(requestID: request.id) + #expect(counter.runs == 1) + #expect(flow.stage == .idle) + } + + @Test func closingTheLocationSheetCancels() { + let request = request([], available: [.location], defaultKeyType: .location) + start(request) + + flow.locationSheetClosed() + + #expect(flow.stage == .idle) + #expect(flow.finishedRequestID == request.id) + #expect(counter.runs == 0) + } + + @Test func closingTheSheetCancelsTheScan() async { + start(qrAndNFC) + flow.choose(.qr) + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + flow.keySheetClosed() + + #expect(!qr.isScanning) + #expect(flow.stage == .idle) + #expect(counter.runs == 0) + } + + @Test func dismissingAReplacedSheetKeepsTheNewerScan() async { + start(qrAndNFC) + flow.choose(.qr) + start(qrAndNFC) + flow.choose(.qr) + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + flow.keySheetDismissed() + + #expect(qr.isScanning) + #expect(flow.stage == .scanningQR) + } + + @Test func dismissingTheSheetClearsAnOrphanedScan() async { + let orphan = Task { try await qr.scan(validate: nil) } + await waitUntil { qr.isScanning } + + flow.keySheetDismissed() + + #expect(!qr.isScanning) + _ = try? await orphan.value + } + + @Test func clearingTheHostStopsWithoutFinishing() async { + start(qrAndNFC) + flow.choose(.qr) + flow.scannerAppeared() + await waitUntil { qr.isScanning } + + flow.hostCleared() + + #expect(!qr.isScanning) + #expect(flow.stage == .idle) + #expect(flow.finishedRequestID == nil) + #expect(counter.runs == 0) + } +} diff --git a/NormalTests/Services/KeyManagerTests.swift b/NormalTests/Services/KeyManagerTests.swift deleted file mode 100644 index 147ad95..0000000 --- a/NormalTests/Services/KeyManagerTests.swift +++ /dev/null @@ -1,35 +0,0 @@ -@testable import Normal -import Testing - -@MainActor -struct KeyManagerTests { - @Test func successInvokesAction() async { - let manager = KeyManager() - var didRun = false - let result = await manager.performWithKeyCheck(using: FakeKeyMethod(result: .success)) { - didRun = true - } - #expect(result) - #expect(didRun) - } - - @Test func failureDoesNotInvokeAction() async { - let manager = KeyManager() - var didRun = false - let result = await manager.performWithKeyCheck(using: FakeKeyMethod(result: .failure)) { - didRun = true - } - #expect(!result) - #expect(!didRun) - } - - @Test func cancellationDoesNotInvokeAction() async { - let manager = KeyManager() - var didRun = false - let result = await manager.performWithKeyCheck(using: FakeKeyMethod(result: .cancelled)) { - didRun = true - } - #expect(!result) - #expect(!didRun) - } -} diff --git a/NormalTests/TestSupport/ControlledScanner.swift b/NormalTests/TestSupport/ControlledScanner.swift new file mode 100644 index 0000000..90ce7db --- /dev/null +++ b/NormalTests/TestSupport/ControlledScanner.swift @@ -0,0 +1,38 @@ +import Foundation +@testable import Normal + +final class ControlledScanner: QRScanning { + private(set) var isScanning = false + private(set) var scanCount = 0 + private var continuation: CheckedContinuation? + private var validator: ((String) -> Bool)? + + func scan(validate: ((String) -> Bool)?) async throws -> String { + guard !isScanning else { throw ScanError.alreadyScanning } + scanCount += 1 + isScanning = true + validator = validate + return try await withCheckedThrowingContinuation { continuation = $0 } + } + + func present(_ value: String) { + guard let validator, validator(value) else { return } + finish(.success(value)) + } + + func reject() { + finish(.failure(ScanError.invalidKey)) + } + + func cancel() { + finish(.failure(ScanError.userCanceled)) + } + + private func finish(_ result: Result) { + let pending = continuation + continuation = nil + validator = nil + isScanning = false + pending?.resume(with: result) + } +} diff --git a/NormalTests/TestSupport/FakeKeyMethod.swift b/NormalTests/TestSupport/FakeKeyMethod.swift deleted file mode 100644 index 2128317..0000000 --- a/NormalTests/TestSupport/FakeKeyMethod.swift +++ /dev/null @@ -1,8 +0,0 @@ -@testable import Normal - -struct FakeKeyMethod: KeyMethod { - let result: KeyResult - func checkKey() async -> KeyResult { - result - } -} diff --git a/NormalUITests/BlockingUITests.swift b/NormalUITests/BlockingUITests.swift index 61f0d8e..67110e9 100644 --- a/NormalUITests/BlockingUITests.swift +++ b/NormalUITests/BlockingUITests.swift @@ -60,6 +60,23 @@ final class BlockingUITests: XCTestCase { XCTAssertTrue(app.buttons["home.blockAll"].waitForExistence(timeout: timeout)) } + func testLocationKeyIsCheckedAfterThePickerCloses() { + let app = launch(["-uiTestSeedLocationKey"]) + blockViaBypass(app) + + app.buttons["home.unblockAll"].tap() + let locationRow = app.buttons["keySelect.row.LOCATION"] + require(locationRow, "The picker should offer the location key") + locationRow.tap() + + let permanent = app.buttons["timedUnblock.permanent"] + require(permanent, "A verified location should continue to the duration sheet") + permanent.tap() + app.buttons["timedUnblock.confirm"].tap() + + require(app.staticTexts["No Active Blocks"], "Apps should be unblocked") + } + func testBlockingDisablesKeysTab() { let app = launch() blockViaBypass(app)