From d208cc3dc5bc02c57120f3bc02c13575ce4f51c8 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Mon, 28 Sep 2026 07:31:11 -0400 Subject: [PATCH 1/4] test(calendar): isolate providers and selection state Inject the existing calendar provider, an owned Defaults selection key and initial date without changing production singleton startup. Exercise 18 synthetic-provider cases without personal events, OS grants or real reminder mutations. Fix deferred authorization status writes and selection broadening before list load or with stale IDs. Preserve the existing empty-selection fallback and route every event refresh through the same selection checks. Refs #75, #18 --- docs/regression-coverage.md | 53 ++- .../Providers/CalendarServiceProviding.swift | 6 + notchPocket/managers/CalendarManager.swift | 79 ++-- .../CalendarManagerIsolationTests.swift | 347 ++++++++++++++++++ 4 files changed, 453 insertions(+), 32 deletions(-) create mode 100644 notchPocketTests/CalendarManagerIsolationTests.swift diff --git a/docs/regression-coverage.md b/docs/regression-coverage.md index 0fe07b018f..f1c3f484e4 100644 --- a/docs/regression-coverage.md +++ b/docs/regression-coverage.md @@ -104,7 +104,7 @@ regression preservation, not a new player support commitment. | Notification capture/filter/queue/expiry/cycling, draft preservation; [manager](../notchPocket/managers/SystemNotificationManager.swift), [helper watcher](../notchPocketXPCHelper/NotificationWatcher.swift) | Bundle-ID normalization/cache tests; notification expanded-view pixel test is local rendering, not banner delivery. | Synthetic notification source/clock and state scenarios before controlled live banners; fresh XPC reconnect/queue cases. | Accessibility; controlled sender/account consent. Attribution follow-up [#12](https://github.com/jdylanmc/notch/issues/12). | | Notification reply/action/open, verification-code copy and debug window; [notification UI](../notchPocket/components/Notch/NotificationLiveActivity.swift), [debug UI](../notchPocket/components/NotificationDebugWindow.swift) | OTP DEBUG self-check is not a canonical XCTest gate. No end-to-end send evidence. | Mock send/clipboard/open sinks; verify drafts survive failures, failed sends never count as delivered, and diagnostics avoid private text. | Real message sending/clipboard changes are separately approved effects. Never dump personal notification trees. | | Contact avatars and optional smart replies; [avatars](../notchPocket/managers/ContactAvatarManager.swift), [smart replies](../notchPocket/managers/SmartReplyManager.swift) | No dedicated availability/generation or contact-provider tests. | Inject contacts/model availability and synthetic content; test unavailable/failed output and fallback rendering. | Contacts grant; macOS 26+ and Apple Intelligence availability for live generation. | -| Calendar/day/week/reminders, filters, selection, completion and meeting links; [view](../notchPocket/components/Calendar/NotchPocketCalendar.swift), [service](../notchPocket/Providers/CalendarServiceProviding.swift) | [Meeting link detection](../notchPocketTests/MeetingLinkDetectorTests.swift); Graph core tests below are not EventKit integration. | Inject EventKit service/clock into manager; synthetic events/reminders, date boundaries and approved mutation sinks. | Calendar/reminder grants and account access; real completion/join actions separately approved. | +| Calendar/day/week/reminders, filters, selection, completion and meeting links; [view](../notchPocket/components/Calendar/NotchPocketCalendar.swift), [service](../notchPocket/Providers/CalendarServiceProviding.swift) | [Manager/provider isolation](../notchPocketTests/CalendarManagerIsolationTests.swift) tests synthetic authorization, list partitioning, scoped date queries, selection and completion; [meeting link detection](../notchPocketTests/MeetingLinkDetectorTests.swift). Graph core tests below are not EventKit integration. | Provider injection exists for an explicit manager, not the live singleton/UI. EventStore change observation/debounce, rendered filtering and whole-profile lifecycle still need scenarios. | Calendar/reminder grants and account access; real completion/join actions separately approved. | | Battery status/popover/charging alerts; [model](../notchPocket/models/BatteryStatusViewModel.swift), [activity manager](../notchPocket/managers/BatteryActivityManager.swift) | No dedicated battery-provider tests. | Inject power readings/time; test transition/debounce/visibility and popover hover guard. | Real battery/adapter state and physical power changes. | | Volume/brightness/backlight indicators and media keys; [on-screen display settings](../notchPocket/components/Settings/Views/OSDSettingsView.swift), [interceptor](../notchPocket/observers/MediaKeyInterceptor.swift) | Presentation bus tests, not actual hardware adjustment or key interception. | Provider-level synthetic controls and bounded native scenarios preserving prior volume/brightness. | Accessibility and explicit device-setting changes. BetterDisplay/Lunar require their apps; do not change their settings for a test implicitly. | | Camera mirror, device/frame/flip and expanded preview; [WebcamManager](../notchPocket/managers/WebcamManager.swift), [view](../notchPocket/components/Webcam/WebcamView.swift) | No dedicated authorization/device/session suite. | Fake availability/session provider; view interaction and permission-denial tests without capturing a real camera. | Camera grant and hardware for live preview; no recording. | @@ -221,6 +221,57 @@ scripts/test.sh \ -only-testing:notchPocketTests/ShelfSummaryWidgetPolicyTests ``` +### Calendar component fixtures + +`CalendarManager(service:selectionKey:initialDate:)` requires all three +dependencies explicitly and does no automatic reload or global EventKit +observation. Tests invoke its operations deliberately. The production `shared` +initializer still constructs the real service with the existing selection key, +registers its observer, and starts the existing initial reload. + +[CalendarManagerIsolationTests](../notchPocketTests/CalendarManagerIsolationTests.swift) +use a synthetic implementation of the existing service protocol and fresh +UUID-named preferences suites. Authorization status and reminder completion +now cross that same protocol rather than escaping into EventKit from the +manager. These fixtures never instantiate the real provider, request OS +permissions, fetch personal events or complete a real reminder. The ordinary +XCTest app host remains unchanged; this is not whole-process isolation. + +Eighteen cases cover inert construction, event/reminder list partitioning, +selection persistence/isolation and the existing all-calendars fallback, date +query parameters, returned events, granted/denied/restricted/write-only/error +authorization, already-granted access, and completion-before-refresh ordering. +With immediate synthetic providers, main-queue-drain regressions reproduced an +ordering failure in the old code: a queued `.notDetermined` assignment overwrote +the newer grant or denial. This is provider-contract evidence, not an observed +live EventKit failure. The already-main-actor manager now publishes the initial +status synchronously, before awaiting the request. Request failures retain the +existing `.notDetermined` outcome and are logged rather than silently swallowed. + +The fixture also reproduced selection broadening before the initial calendar +list loaded and when stale IDs happened to match the available-calendar count. +Date queries and first selection changes now resolve the initial list before +computing selected IDs; a nonempty explicit selection +with no available IDs returns no events instead of passing the provider's +empty-ID wildcard. Converting selection to `.all` uses actual set membership, +not counts. The existing empty-selection fallback is preserved. Synthetic query +responses honor ID filtering, so an accidental all-calendar query changes the +observed result as well as the captured request. + +```bash +scripts/test.sh \ + -only-testing:notchPocketTests/CalendarManagerIsolationTests \ + -only-testing:notchPocketTests/MeetingLinkDetectorTests \ + -only-testing:notchPocketTests/CalendarCoreIdentityTests +``` + +The real EventKit provider, reminder mutation implementation, date normalization, +global observer and production initial reload remain in place. The selection and +authorization ordering corrections above are intentional, regression-backed +behavior fixes. Real permission dialogs, EventKit synchronization/debounce, +overlapping asynchronous query completion, end-to-end meeting launches and UI +restoration remain unverified. + ## Next bounded isolation/control increments 1. Supply an explicit test-session owner that routes Dashboard, Defaults, diff --git a/notchPocket/Providers/CalendarServiceProviding.swift b/notchPocket/Providers/CalendarServiceProviding.swift index 58b43ee514..04742730f4 100644 --- a/notchPocket/Providers/CalendarServiceProviding.swift +++ b/notchPocket/Providers/CalendarServiceProviding.swift @@ -11,13 +11,19 @@ import Foundation @preconcurrency import EventKit protocol CalendarServiceProviding { + func authorizationStatus(for type: EKEntityType) -> EKAuthorizationStatus func requestAccess(to type: EKEntityType) async throws -> Bool func calendars() async -> [CalendarModel] func events(from start: Date, to end: Date, calendars: [String]) async -> [EventModel] + func setReminderCompleted(reminderID: String, completed: Bool) async } class CalendarService: CalendarServiceProviding { private let store = EKEventStore() + + func authorizationStatus(for type: EKEntityType) -> EKAuthorizationStatus { + EKEventStore.authorizationStatus(for: type) + } @MainActor func requestAccess(to type: EKEntityType) async throws -> Bool { diff --git a/notchPocket/managers/CalendarManager.swift b/notchPocket/managers/CalendarManager.swift index 871d3a6ff6..1503d692f8 100644 --- a/notchPocket/managers/CalendarManager.swift +++ b/notchPocket/managers/CalendarManager.swift @@ -24,21 +24,29 @@ final class CalendarManager: ObservableObject { @Published var calendarAuthorizationStatus: EKAuthorizationStatus = .notDetermined @Published var reminderAuthorizationStatus: EKAuthorizationStatus = .notDetermined private var selectedCalendars: [CalendarModel] = [] - private let calendarService = CalendarService() + private let calendarService: any CalendarServiceProviding + private let selectionKey: Defaults.Key + private var didLoadCalendarLists = false private var eventStoreChangedObserver: NSObjectProtocol? /// EventKit can fire EKEventStoreChanged in bursts during syncs; reloads /// coalesce so the UI refreshes once per burst instead of per notification. private var reloadTask: Task? - private init() { - self.currentWeekStartDate = CalendarManager.startOfDay(Date()) + private convenience init() { + self.init(service: CalendarService(), selectionKey: .calendarSelectionState, initialDate: Date()) setupEventStoreChangedObserver() Task { await reloadCalendarAndReminderLists() } } + init(service: any CalendarServiceProviding, selectionKey: Defaults.Key, initialDate: Date) { + self.calendarService = service + self.selectionKey = selectionKey + self.currentWeekStartDate = CalendarManager.startOfDay(initialDate) + } + deinit { if let observer = eventStoreChangedObserver { NotificationCenter.default.removeObserver(observer) @@ -67,39 +75,36 @@ final class CalendarManager: ObservableObject { self.eventCalendars = all.filter { !$0.isReminder } self.reminderLists = all.filter { $0.isReminder } self.allCalendars = all // for legacy compatibility, can be removed if not needed + didLoadCalendarLists = true updateSelectedCalendars() } func checkCalendarAuthorization() async { - let status = EKEventStore.authorizationStatus(for: .event) - DispatchQueue.main.async { - Log.calendar.debug("📅 Current calendar authorization status: \(String(describing: status))") - self.calendarAuthorizationStatus = status - } + let status = calendarService.authorizationStatus(for: .event) + Log.calendar.debug("📅 Current calendar authorization status: \(String(describing: status))") + calendarAuthorizationStatus = status switch status { case .notDetermined: - guard let granted = try? await calendarService.requestAccess(to: .event) else { + let granted: Bool + do { + granted = try await calendarService.requestAccess(to: .event) + } catch { + Log.calendar.error("Calendar access request failed: \(error.localizedDescription)") self.calendarAuthorizationStatus = .notDetermined return } self.calendarAuthorizationStatus = granted ? .fullAccess : .denied if granted { await reloadCalendarAndReminderLists() - events = await calendarService.events( - from: currentWeekStartDate, - to: Calendar.current.date(byAdding: .day, value: 1, to: currentWeekStartDate)!, - calendars: selectedCalendars.map { $0.id }) + await updateEvents() } case .restricted, .denied: NSLog("Calendar access denied or restricted") case .fullAccess: NSLog("Full access") await reloadCalendarAndReminderLists() - events = await calendarService.events( - from: currentWeekStartDate, - to: Calendar.current.date(byAdding: .day, value: 1, to: currentWeekStartDate)!, - calendars: selectedCalendars.map { $0.id }) + await updateEvents() case .writeOnly: NSLog("Write only") @unknown default: @@ -108,15 +113,17 @@ final class CalendarManager: ObservableObject { } func checkReminderAuthorization() async { - let status = EKEventStore.authorizationStatus(for: .reminder) - DispatchQueue.main.async { - Log.calendar.debug("📅 Current reminder authorization status: \(String(describing: status))") - self.reminderAuthorizationStatus = status - } + let status = calendarService.authorizationStatus(for: .reminder) + Log.calendar.debug("📅 Current reminder authorization status: \(String(describing: status))") + reminderAuthorizationStatus = status switch status { case .notDetermined: - guard let granted = try? await calendarService.requestAccess(to: .reminder) else { + let granted: Bool + do { + granted = try await calendarService.requestAccess(to: .reminder) + } catch { + Log.calendar.error("Reminder access request failed: \(error.localizedDescription)") self.reminderAuthorizationStatus = .notDetermined return } @@ -139,7 +146,7 @@ final class CalendarManager: ObservableObject { func updateSelectedCalendars() { // Populate selectedCalendarIDs based on Defaults calendar selection state - switch Defaults[.calendarSelectionState] { + switch Defaults[selectionKey] { case .all: selectedCalendarIDs = Set(allCalendars.map { $0.id }) case .selected(let identifiers): @@ -155,7 +162,8 @@ final class CalendarManager: ObservableObject { } func setCalendarSelected(_ calendar: CalendarModel, isSelected: Bool) async { - var selectionState = Defaults[.calendarSelectionState] + await loadCalendarsIfNeeded() + var selectionState = Defaults[selectionKey] switch selectionState { case .all: @@ -173,10 +181,10 @@ final class CalendarManager: ObservableObject { selectionState = identifiers.isEmpty - ? .all : identifiers.count == allCalendars.count ? .all : .selected(identifiers) // if empty, select all + ? .all : identifiers == Set(allCalendars.map(\.id)) ? .all : .selected(identifiers) } - Defaults[.calendarSelectionState] = selectionState + Defaults[selectionKey] = selectionState updateSelectedCalendars() await updateEvents() } @@ -190,8 +198,20 @@ final class CalendarManager: ObservableObject { await updateEvents() } + private func loadCalendarsIfNeeded() async { + if !didLoadCalendarLists { + await reloadCalendarAndReminderLists() + } + } + private func updateEvents() async { + await loadCalendarsIfNeeded() + updateSelectedCalendars() let calendarIDs = selectedCalendars.map { $0.id } + if case .selected(let identifiers) = Defaults[selectionKey], !identifiers.isEmpty, calendarIDs.isEmpty { + events = [] + return + } let eventsResult = await calendarService.events( from: currentWeekStartDate, to: Calendar.current.date(byAdding: .day, value: 1, to: currentWeekStartDate)!, @@ -203,9 +223,6 @@ final class CalendarManager: ObservableObject { func setReminderCompleted(reminderID: String, completed: Bool) async { await calendarService.setReminderCompleted(reminderID: reminderID, completed: completed) // Refresh events after updating - events = await calendarService.events( - from: currentWeekStartDate, - to: Calendar.current.date(byAdding: .day, value: 1, to: currentWeekStartDate)!, - calendars: selectedCalendars.map { $0.id }) + await updateEvents() } } diff --git a/notchPocketTests/CalendarManagerIsolationTests.swift b/notchPocketTests/CalendarManagerIsolationTests.swift new file mode 100644 index 0000000000..b3c14b7f7f --- /dev/null +++ b/notchPocketTests/CalendarManagerIsolationTests.swift @@ -0,0 +1,347 @@ +import Defaults +import EventKit +import Foundation +import XCTest + +@testable import notchPocket + +@MainActor +final class CalendarManagerIsolationTests: XCTestCase { + private enum FixtureError: Error { + case occupiedDomain + case accessFailed + } + + private struct Query: Equatable { + let start: Date + let end: Date + let calendarIDs: [String] + } + + private final class Service: CalendarServiceProviding { + var eventStatus: EKAuthorizationStatus = .notDetermined + var reminderStatus: EKAuthorizationStatus = .notDetermined + var accessResult: Result = .success(true) + var calendarValues: [CalendarModel] = [] + var eventValues: [EventModel] = [] + var requests: [EKEntityType] = [] + var calendarReads = 0 + var queries: [Query] = [] + var completions: [(String, Bool)] = [] + var operations: [String] = [] + + func authorizationStatus(for type: EKEntityType) -> EKAuthorizationStatus { + type == .event ? eventStatus : reminderStatus + } + + @MainActor + func requestAccess(to type: EKEntityType) async throws -> Bool { + requests.append(type) + return try accessResult.get() + } + + func calendars() async -> [CalendarModel] { + calendarReads += 1 + return calendarValues + } + + func events(from start: Date, to end: Date, calendars: [String]) async -> [EventModel] { + queries.append(Query(start: start, end: end, calendarIDs: calendars)) + operations.append("events") + return eventValues.filter { calendars.isEmpty || calendars.contains($0.calendar.id) } + } + + func setReminderCompleted(reminderID: String, completed: Bool) async { + completions.append((reminderID, completed)) + operations.append("complete") + } + } + + private struct Fixture { + let service: Service + let manager: CalendarManager + let key: Defaults.Key + } + + private let date = Date(timeIntervalSince1970: 1_789_220_700) + + private func calendar(_ id: String, reminder: Bool = false) -> CalendarModel { + CalendarModel(id: id, account: "Synthetic account", title: id, color: .blue, + isSubscribed: false, isReminder: reminder) + } + + private func fixture() throws -> Fixture { + let name = "com.jdylanmc.notchpocket.tests.calendar.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: name)) + guard defaults.persistentDomain(forName: name) == nil else { throw FixtureError.occupiedDomain } + addTeardownBlock { + let owned = try XCTUnwrap(UserDefaults(suiteName: name)) + owned.removePersistentDomain(forName: name) + XCTAssertTrue(owned.persistentDomain(forName: name)?.isEmpty ?? true) + } + let key = Defaults.Key("calendarSelectionState", default: .all, suite: defaults) + XCTAssertTrue(key.suite === defaults) + XCTAssertFalse(key.suite === UserDefaults.standard) + let service = Service() + service.calendarValues = [calendar("a"), calendar("b"), calendar("reminders", reminder: true)] + let manager = CalendarManager(service: service, selectionKey: key, initialDate: date) + return Fixture(service: service, manager: manager, key: key) + } + + private func event(in calendar: CalendarModel) -> EventModel { + EventModel(id: "fixture-event-\(calendar.id)", start: date, end: date.addingTimeInterval(3_600), + title: "Synthetic event", location: nil, notes: nil, url: nil, isAllDay: false, + type: .event(.accepted), calendar: calendar, participants: [], timeZone: nil, + hasRecurrenceRules: false, priority: nil, meetingLink: nil) + } + + private func drainMainQueue() async { + await withCheckedContinuation { continuation in + DispatchQueue.main.async { continuation.resume() } + } + } + + func testInjectedConstructionDoesNotStartProviderWork() throws { + XCTAssertTrue(Defaults.Keys.calendarSelectionState.suite === UserDefaults.standard) + let fixture = try fixture() + XCTAssertEqual(fixture.service.calendarReads, 0) + XCTAssertTrue(fixture.service.requests.isEmpty) + XCTAssertTrue(fixture.service.queries.isEmpty) + XCTAssertTrue(fixture.manager.allCalendars.isEmpty) + XCTAssertEqual(fixture.manager.currentWeekStartDate, Calendar.current.startOfDay(for: date)) + } + + func testReloadPartitionsCalendarsAndRemindersWithAllSelection() async throws { + let fixture = try fixture() + + await fixture.manager.reloadCalendarAndReminderLists() + + XCTAssertEqual(fixture.service.calendarReads, 1) + XCTAssertEqual(fixture.manager.eventCalendars.map(\.id), ["a", "b"]) + XCTAssertEqual(fixture.manager.reminderLists.map(\.id), ["reminders"]) + XCTAssertEqual(fixture.manager.selectedCalendarIDs, ["a", "b", "reminders"]) + XCTAssertTrue(fixture.service.queries.isEmpty) + } + + func testStoredSelectionScopesQueriesToItsOwnedPreferenceSuite() async throws { + let fixture = try fixture() + Defaults[fixture.key] = .selected(["b"]) + await fixture.manager.reloadCalendarAndReminderLists() + let value = event(in: fixture.service.calendarValues[1]) + fixture.service.eventValues = [event(in: fixture.service.calendarValues[0]), value] + + await fixture.manager.updateCurrentDate(date) + + let query = try XCTUnwrap(fixture.service.queries.last) + let start = Calendar.current.startOfDay(for: date) + XCTAssertEqual(query.start, start) + XCTAssertEqual(query.end, try XCTUnwrap(Calendar.current.date(byAdding: .day, value: 1, to: start))) + XCTAssertEqual(query.calendarIDs, ["b"]) + XCTAssertEqual(fixture.manager.events, [value]) + XCTAssertFalse(fixture.manager.getCalendarSelected(fixture.service.calendarValues[0])) + } + + func testSelectionWritesDoNotAffectAnotherFixtureSuite() async throws { + let first = try fixture() + let second = try fixture() + Defaults[second.key] = .selected(["a"]) + await first.manager.reloadCalendarAndReminderLists() + + await first.manager.setCalendarSelected(first.service.calendarValues[0], isSelected: false) + + guard case .selected(let firstIDs) = Defaults[first.key], + case .selected(let secondIDs) = Defaults[second.key] else { + return XCTFail("Expected independent stored selections") + } + XCTAssertEqual(firstIDs, ["b", "reminders"]) + XCTAssertEqual(secondIDs, ["a"]) + XCTAssertEqual(first.service.queries.last?.calendarIDs, ["b", "reminders"]) + } + + func testRemovingTheLastExplicitSelectionPreservesExistingAllFallback() async throws { + let fixture = try fixture() + Defaults[fixture.key] = .selected(["a"]) + await fixture.manager.reloadCalendarAndReminderLists() + + await fixture.manager.setCalendarSelected(fixture.service.calendarValues[0], isSelected: false) + + guard case .all = Defaults[fixture.key] else { return XCTFail("Expected the existing all-calendars fallback") } + XCTAssertEqual(fixture.manager.selectedCalendarIDs, ["a", "b", "reminders"]) + XCTAssertEqual(fixture.service.queries.last?.calendarIDs, ["a", "b", "reminders"]) + } + + func testImmediateCalendarGrantKeepsFinalStatusAfterQueuedWork() async throws { + let fixture = try fixture() + fixture.service.eventValues = [event(in: fixture.service.calendarValues[0])] + + await fixture.manager.checkCalendarAuthorization() + await drainMainQueue() + + XCTAssertEqual(fixture.service.requests, [.event]) + XCTAssertEqual(fixture.manager.calendarAuthorizationStatus, .fullAccess) + XCTAssertEqual(fixture.service.calendarReads, 1) + XCTAssertEqual(fixture.manager.events, fixture.service.eventValues) + } + + func testDeniedRestrictedAndWriteOnlyCalendarNeverRequestOrReadData() async throws { + for status in [EKAuthorizationStatus.denied, .restricted, .writeOnly] { + let fixture = try fixture() + fixture.service.eventStatus = status + + await fixture.manager.checkCalendarAuthorization() + await drainMainQueue() + + XCTAssertEqual(fixture.manager.calendarAuthorizationStatus, status) + XCTAssertTrue(fixture.service.requests.isEmpty) + XCTAssertEqual(fixture.service.calendarReads, 0) + XCTAssertTrue(fixture.service.queries.isEmpty) + } + } + + func testCalendarRequestDenialOrErrorDoesNotBecomeAccessOrFetch() async throws { + for result: Result in [.success(false), .failure(.accessFailed)] { + let fixture = try fixture() + fixture.service.accessResult = result + + await fixture.manager.checkCalendarAuthorization() + await drainMainQueue() + + switch result { + case .success: XCTAssertEqual(fixture.manager.calendarAuthorizationStatus, .denied) + case .failure: XCTAssertEqual(fixture.manager.calendarAuthorizationStatus, .notDetermined) + } + XCTAssertEqual(fixture.service.requests, [.event]) + XCTAssertEqual(fixture.service.calendarReads, 0) + XCTAssertTrue(fixture.service.queries.isEmpty) + } + } + + func testExistingCalendarAccessFetchesWithoutRequestingAgain() async throws { + let fixture = try fixture() + fixture.service.eventStatus = .fullAccess + + await fixture.manager.checkCalendarAuthorization() + + XCTAssertTrue(fixture.service.requests.isEmpty) + XCTAssertEqual(fixture.service.calendarReads, 1) + XCTAssertEqual(fixture.service.queries.count, 1) + } + + func testImmediateReminderGrantRetainsStatusWithoutFetchingEvents() async throws { + let fixture = try fixture() + + await fixture.manager.checkReminderAuthorization() + await drainMainQueue() + + XCTAssertEqual(fixture.service.requests, [.reminder]) + XCTAssertEqual(fixture.manager.reminderAuthorizationStatus, .fullAccess) + XCTAssertEqual(fixture.service.calendarReads, 1) + XCTAssertTrue(fixture.service.queries.isEmpty) + } + + func testDeniedReminderAccessDoesNotRequestOrReload() async throws { + let fixture = try fixture() + fixture.service.reminderStatus = .denied + + await fixture.manager.checkReminderAuthorization() + await drainMainQueue() + + XCTAssertEqual(fixture.manager.reminderAuthorizationStatus, .denied) + XCTAssertTrue(fixture.service.requests.isEmpty) + XCTAssertEqual(fixture.service.calendarReads, 0) + } + + func testReminderRequestDenialOrErrorDoesNotBecomeAccessOrReload() async throws { + for result: Result in [.success(false), .failure(.accessFailed)] { + let fixture = try fixture() + fixture.service.accessResult = result + + await fixture.manager.checkReminderAuthorization() + await drainMainQueue() + + switch result { + case .success: XCTAssertEqual(fixture.manager.reminderAuthorizationStatus, .denied) + case .failure: XCTAssertEqual(fixture.manager.reminderAuthorizationStatus, .notDetermined) + } + XCTAssertEqual(fixture.service.requests, [.reminder]) + XCTAssertEqual(fixture.service.calendarReads, 0) + XCTAssertTrue(fixture.service.queries.isEmpty) + } + } + + func testExistingReminderAccessReloadsWithoutRequestingOrFetchingEvents() async throws { + let fixture = try fixture() + fixture.service.reminderStatus = .fullAccess + + await fixture.manager.checkReminderAuthorization() + + XCTAssertTrue(fixture.service.requests.isEmpty) + XCTAssertEqual(fixture.service.calendarReads, 1) + XCTAssertTrue(fixture.service.queries.isEmpty) + XCTAssertEqual(fixture.manager.reminderLists.map(\.id), ["reminders"]) + } + + func testReminderCompletionReachesOnlyTheInjectedServiceThenRefreshes() async throws { + let fixture = try fixture() + await fixture.manager.reloadCalendarAndReminderLists() + fixture.service.eventValues = [event(in: fixture.service.calendarValues[0])] + + await fixture.manager.setReminderCompleted(reminderID: "fixture-reminder", completed: true) + + XCTAssertEqual(fixture.service.completions.count, 1) + XCTAssertEqual(fixture.service.completions.first?.0, "fixture-reminder") + XCTAssertEqual(fixture.service.completions.first?.1, true) + XCTAssertEqual(fixture.service.operations, ["complete", "events"]) + XCTAssertEqual(fixture.manager.events, fixture.service.eventValues) + } + + func testFirstDateQueryResolvesStoredSelectionBeforeFetchingEvents() async throws { + let fixture = try fixture() + Defaults[fixture.key] = .selected(["b"]) + let expected = event(in: fixture.service.calendarValues[1]) + fixture.service.eventValues = [event(in: fixture.service.calendarValues[0]), expected] + + await fixture.manager.updateCurrentDate(date) + + XCTAssertEqual(fixture.service.calendarReads, 1) + XCTAssertEqual(fixture.service.queries.last?.calendarIDs, ["b"]) + XCTAssertEqual(fixture.manager.events, [expected]) + } + + func testFirstSelectionChangeLoadsListsBeforeComputingDeselection() async throws { + let fixture = try fixture() + + await fixture.manager.setCalendarSelected(fixture.service.calendarValues[0], isSelected: false) + + XCTAssertEqual(fixture.service.calendarReads, 1) + XCTAssertEqual(fixture.manager.selectedCalendarIDs, ["b", "reminders"]) + XCTAssertEqual(fixture.service.queries.last?.calendarIDs, ["b", "reminders"]) + } + + func testUnavailableExplicitSelectionDoesNotBroadenToEveryCalendar() async throws { + let fixture = try fixture() + Defaults[fixture.key] = .selected(["removed-calendar"]) + fixture.service.eventValues = [event(in: fixture.service.calendarValues[0])] + + await fixture.manager.updateCurrentDate(date) + + XCTAssertEqual(fixture.manager.selectedCalendarIDs, ["removed-calendar"]) + XCTAssertTrue(fixture.service.queries.isEmpty) + XCTAssertTrue(fixture.manager.events.isEmpty) + } + + func testStaleSelectionIDsDoNotEnableUnselectedListsByMatchingCount() async throws { + let fixture = try fixture() + Defaults[fixture.key] = .selected(["a", "removed-calendar"]) + await fixture.manager.reloadCalendarAndReminderLists() + + await fixture.manager.setCalendarSelected(fixture.service.calendarValues[1], isSelected: true) + + guard case .selected(let identifiers) = Defaults[fixture.key] else { + return XCTFail("Unknown IDs must not silently convert an explicit selection into all calendars") + } + XCTAssertEqual(identifiers, ["a", "b", "removed-calendar"]) + XCTAssertEqual(fixture.service.queries.last?.calendarIDs, ["a", "b"]) + XCTAssertFalse(fixture.manager.getCalendarSelected(fixture.service.calendarValues[2])) + } +} From 4fff039f5a62249c7ac84466c5cb0c124b2c9a06 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Mon, 28 Sep 2026 17:34:29 -0400 Subject: [PATCH 2/4] docs(calendar): record isolated regression coverage Document the Calendar provider fixtures and selection fixes in Unreleased.\nKeep Settings pane and whole-app isolation limits explicit.\n\nRefs #75, #18, PR #97 --- CHANGELOG.md | 24 ++++++++++++++++++++++++ docs/regression-coverage.md | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..bccf4aa7cb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +Notable changes follow [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +Product tags and distribution are documented in the [release guide](docs/releases.md). + +## [Unreleased] + +### Added + +- Calendar component fixtures with an injected provider and disposable selection + preferences, covering authorization, queries and reminder completion without + personal Calendar data or real reminder mutations. This is not whole-app isolation. + +### Fixed + +- Calendar authorization status no longer loses immediate access results to a + queued older status. Initial queries resolve stored selections first; stale or + unavailable selected IDs no longer silently broaden queries to all calendars. + The existing empty-selection fallback is preserved. + +Scoped to [PR #97](https://github.com/jdylanmc/notch/pull/97), part of +[#75](https://github.com/jdylanmc/notch/issues/75); neither #75 nor #18 is closed. + +[Unreleased]: https://github.com/jdylanmc/notch/compare/notch-pocket-v0.1.0...pocket diff --git a/docs/regression-coverage.md b/docs/regression-coverage.md index f1c3f484e4..5119949401 100644 --- a/docs/regression-coverage.md +++ b/docs/regression-coverage.md @@ -126,7 +126,7 @@ routine human clicks. Preference writes need a whole-app fixture profile first. | [Appearance](../notchPocket/components/Settings/Views/AppearanceSettingsView.swift) | Tab visibility, settings icon, waveform, tinting/lighting, slider color and idle face. | Tab policy only; fixture setting/pixel and audio-availability assertions missing. | | [Media](../notchPocket/components/Settings/Views/MediaSettingsView.swift) | Source, live activity, sneak peek, idle timing, lyrics and fallback retry. | Availability-model tests; no pane/controller/provider end-to-end suite. | | [Notifications](../notchPocket/components/Settings/Views/NotificationSettingsView.swift) | Enable watching, all-apps/allow-list selection, smart replies and availability. | No settings journey test; real enable can start live capture and must not run in a personal profile. | -| [Calendar](../notchPocket/components/Settings/Views/CalendarSettingsView.swift) | Visibility, completed/all-day filters, full titles, next event, week start, meeting tap, calendar/reminder lists and denied access. | Meeting-link parsing only; inject service/permission results and prevent real reminder mutations. | +| [Calendar](../notchPocket/components/Settings/Views/CalendarSettingsView.swift) | Visibility, completed/all-day filters, full titles, next event, week start, meeting tap, calendar/reminder lists and denied access. | Meeting-link parsing and explicit-manager provider fixtures cover authorization, lists and selection without real reminder mutations. Pane rendering, preference propagation and live permission/UI restoration remain unverified; the pane still uses the production singleton. | | [On-screen display](../notchPocket/components/Settings/Views/OSDSettingsView.swift) | Replacement, inline display, source providers, authorization, color/shadow/percentage and Option-key behavior. | Event bus only; fake controls before live device changes, including provider restoration. | | [Battery](../notchPocket/components/Settings/Views/BatterySettingsView.swift) | Indicator, status notifications, percentage, icons and charging wattage. | No dedicated pane tests; synthetic battery readings needed. | | [Shelf](../notchPocket/components/Settings/Views/ShelfSettingsView.swift) | Enable/default tab, expanded drag target, copy-on-drag, auto-removal, ordering and quick-share provider. | Shelf policy/tab tests do not prove these settings; isolate files, preferences and external sharing. | From a4e83096841df6cfdfb52e641ae4fe2a0560a6f4 Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Sun, 4 Oct 2026 02:05:58 -0400 Subject: [PATCH 3/4] Align Calendar fixture notes with the open coverage backlog --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bccf4aa7cb..04ee7c13a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,10 @@ Product tags and distribution are documented in the [release guide](docs/release unavailable selected IDs no longer silently broaden queries to all calendars. The existing empty-selection fallback is preserved. -Scoped to [PR #97](https://github.com/jdylanmc/notch/pull/97), part of -[#75](https://github.com/jdylanmc/notch/issues/75); neither #75 nor #18 is closed. +Scoped to [PR #97](https://github.com/jdylanmc/notch/pull/97), extending the +coverage and fixture work in [#7](https://github.com/jdylanmc/notch/issues/7) and +[#18](https://github.com/jdylanmc/notch/issues/18). The original +[#75](https://github.com/jdylanmc/notch/issues/75) regression foundation is +already delivered; this change does not close the remaining coverage issues. [Unreleased]: https://github.com/jdylanmc/notch/compare/notch-pocket-v0.1.0...pocket From 1e649ae8b3c48631908b8e7fe56d9a5c66df234b Mon Sep 17 00:00:00 2001 From: Dylan McCurry Date: Sun, 4 Oct 2026 03:07:19 -0400 Subject: [PATCH 4/4] Qualify Calendar authorization evidence in release notes --- CHANGELOG.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04ee7c13a7..01a28dec6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,13 @@ Product tags and distribution are documented in the [release guide](docs/release ### Fixed -- Calendar authorization status no longer loses immediate access results to a - queued older status. Initial queries resolve stored selections first; stale or - unavailable selected IDs no longer silently broaden queries to all calendars. - The existing empty-selection fallback is preserved. +- Calendar manager authorization state is published before awaiting provider + access, preventing immediate provider results from being overwritten by a + queued older status. This ordering fix is demonstrated with synthetic + providers, not a reproduced live EventKit failure. +- Initial queries resolve stored selections first; stale or unavailable + selected IDs no longer silently broaden queries to all calendars. The + existing empty-selection fallback is preserved. Scoped to [PR #97](https://github.com/jdylanmc/notch/pull/97), extending the coverage and fixture work in [#7](https://github.com/jdylanmc/notch/issues/7) and