Repository Public
1// SP Notes iOS2// File: Tests/WidgetTasksTests.swift3// Description: Tasks on the system surfaces: the due-date rule (a bare day is noon UTC), the links, what the widget lists, and4// the completion of a task by a SECOND read-write connection (the widget extension) next to the app's connection:5// the app sees it, the outbox holds it, a 1.0 database is never touched.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Testing11import SPNotesCore12@testable import SPNotes1314struct TaskDueTests {15 private func calendar(_ zone: String) -> Calendar {16 var calendar = Calendar(identifier: .gregorian)17 calendar.timeZone = TimeZone(identifier: zone)!18 return calendar19 }20 private func date(_ text: String) -> Date { APIDate.parse(text)! }2122 @Test func aBareDayIsThatCalendarDayEverywhere() {23 let due = date("2026-11-20T12:00:00.000Z")24 #expect(TaskDueRule.isBareDay(due))25 for zone in ["America/Toronto", "Asia/Tokyo", "Pacific/Auckland", "Pacific/Honolulu"] {26 let calendar = calendar(zone)27 let day = calendar.dateComponents([.year, .month, .day, .hour], from: TaskDueRule.localDay(due, calendar: calendar))28 #expect(day.year == 2026 && day.month == 11 && day.day == 20 && day.hour == 0, "\(zone)")29 let fire = calendar.dateComponents([.day, .hour, .minute], from: TaskDueRule.notificationDate(due, calendar: calendar))30 #expect(fire.day == 20 && fire.hour == 9 && fire.minute == 0, "\(zone)")31 }32 }3334 @Test func aTimedDueDateIsAnInstant() {35 let toronto = calendar("America/Toronto")36 let due = date("2026-11-20T19:30:00.000Z") // 14:30 in Toronto37 #expect(!TaskDueRule.isBareDay(due))38 #expect(TaskDueRule.notificationDate(due, calendar: toronto) == due)39 #expect(toronto.component(.day, from: TaskDueRule.localDay(due, calendar: toronto)) == 20)40 #expect(TaskDueRule.isOverdue(due, now: date("2026-11-20T19:31:00.000Z"), calendar: toronto))41 #expect(!TaskDueRule.isOverdue(due, now: date("2026-11-20T19:00:00.000Z"), calendar: toronto))42 }4344 @Test func overdueAndDueToday() {45 let toronto = calendar("America/Toronto")46 let bare = date("2026-11-20T12:00:00.000Z")47 // The evening of the 20th in Toronto (01:00 UTC on the 21st): still today, not late.48 let evening = date("2026-11-21T01:00:00.000Z")49 #expect(TaskDueRule.isDueByToday(bare, now: evening, calendar: toronto) && !TaskDueRule.isOverdue(bare, now: evening, calendar: toronto))50 let nextDay = date("2026-11-21T14:00:00.000Z")51 #expect(TaskDueRule.isOverdue(bare, now: nextDay, calendar: toronto))52 let dayBefore = date("2026-11-19T23:00:00.000Z")53 #expect(!TaskDueRule.isDueByToday(bare, now: dayBefore, calendar: toronto))54 }5556 @Test func bareDayRoundTripsAndPostpones() {57 let toronto = calendar("America/Toronto")58 let now = date("2026-11-20T03:30:00.000Z") // 22:30 on the 19th in Toronto59 #expect(TaskDueRule.dayString(of: now, calendar: toronto) == "2026-11-19")60 #expect(TaskDueRule.bareDay(of: now, calendar: toronto) == date("2026-11-19T12:00:00.000Z"))61 // « Reporter à demain » from the evening of the 19th: the 20th.62 #expect(TaskDueRule.postponedToTomorrow(date("2026-11-18T12:00:00.000Z"), now: now, calendar: toronto) == date("2026-11-20T12:00:00.000Z"))63 #expect(TaskDueRule.postponedToTomorrow(nil, now: now, calendar: toronto) == date("2026-11-20T12:00:00.000Z"))64 // A timed one keeps its time of day (14:30 Toronto).65 #expect(TaskDueRule.postponedToTomorrow(date("2026-11-17T19:30:00.000Z"), now: now, calendar: toronto) == date("2026-11-20T19:30:00.000Z"))66 }6768 @Test func links() {69 let id = "0b7f6c0e-3f0a-4d5e-9b0a-111111111111"70 #expect(SystemLinks.capture().absoluteString == "spnotes://capture")71 #expect(SystemLinks.capture(kind: "Dictation").absoluteString == "spnotes://capture?kind=dictation")72 #expect(SystemLinks.capture(kind: "a&b=c").absoluteString == "spnotes://capture")73 #expect(SystemLinks.note(id, blockId: "blk-12_ab")?.absoluteString == "spnotes://note/\(id)?block=blk-12_ab")74 #expect(SystemLinks.note(id, blockId: "x y&z")?.absoluteString == "spnotes://note/\(id)")75 #expect(SystemLinks.note("../etc") == nil)76 #expect(SystemLinks.task(pageId: id, blockId: nil).absoluteString == "spnotes://note/\(id)")77 #expect(SystemLinks.task(pageId: nil, blockId: "b").absoluteString == "spnotes://tasks")78 // The note link is understood by today's parser (the block is read once the 2.0 routes are merged).79 #expect(DeepLink(url: SystemLinks.note(id, blockId: "blk1")!) != nil)80 }81}8283struct WidgetTasksTests {84 private func makeDatabase() throws -> (url: URL, store: NotesStore, tasks: TasksRepository) {85 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-wtasks-\(UUID().uuidString)", isDirectory: true)86 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)87 let url = directory.appendingPathComponent("notes.sqlite")88 let store = try NotesStore.open(url: url).get()89 return (url, store, TasksRepository(context: RepositoryContext(store: store, api: SystemTestSupport.offlineAPI(), engine: nil)))90 }9192 @Test func theWidgetListsWhatIsDueTodayOrLate() async throws {93 let (url, store, tasks) = try makeDatabase()94 let group = ScratchSuite()95 defer { group.remove() }96 let provider = WidgetDataProvider(databaseURL: url, lock: group.lock)97 #expect(await provider.tasksContent(limit: 3) == .tasks([], more: 0, open: 0))9899 let now = Date()100 let page = try await store.createPage(NewPage(title: "Projet", plainText: "", wordCount: 0, preview: ""))101 let late = try await tasks.create(title: "En retard", dueAt: now.addingTimeInterval(-3 * 86_400), priority: .high, pageId: page.id, blockId: "blk-1")102 let today = try await tasks.create(title: "Aujourd’hui", dueDay: TaskDueRule.dayString(of: now))103 _ = try await tasks.create(title: "Plus tard", dueAt: now.addingTimeInterval(5 * 86_400))104 _ = try await tasks.create(title: "Sans date")105 let finished = try await tasks.create(title: "Finie", dueAt: now.addingTimeInterval(-86_400))106 try await tasks.setDone(id: finished.id, true)107 let removed = try await tasks.create(title: "Supprimée", dueAt: now.addingTimeInterval(-86_400))108 try await tasks.delete(id: removed.id)109110 guard case .tasks(let shown, let more, let open) = await provider.tasksContent(limit: 3, now: now) else { Issue.record("not a list"); return }111 #expect(shown.map(\.id) == [late.id, today.id])112 #expect(more == 0 && open == 4)113 #expect(shown[0].isOverdue && shown[0].isHighPriority && shown[0].noteTitle == "Projet")114 #expect(shown[0].url.absoluteString == "spnotes://note/\(page.id)?block=blk-1")115 #expect(!shown[1].isOverdue && shown[1].url == SystemLinks.tasks)116117 guard case .tasks(let one, let rest, _) = await provider.tasksContent(limit: 1, now: now) else { Issue.record("not a list"); return }118 #expect(one.map(\.id) == [late.id] && rest == 1)119 #expect(await provider.openTasks().count == 4)120 await store.close()121 }122123 @Test func aMissingDatabaseIsAnOrdinaryState() async {124 let url = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-none-\(UUID().uuidString).sqlite")125 let group = ScratchSuite()126 defer { group.remove() }127 #expect(await WidgetDataProvider(databaseURL: url, lock: group.lock).tasksContent(limit: 3) == .unavailable)128 #expect(await SharedTaskActions.setDone(taskId: "x", databaseURL: url, lock: group.lock) == .unavailable)129 #expect(!FileManager.default.fileExists(atPath: url.path)) // an extension never creates the database130 }131132 /// The widget extension's write: a second read-write connection next to the app's.133 @Test func aSecondConnectionCompletesATaskAndTheAppSeesIt() async throws {134 let (url, appStore, appTasks) = try makeDatabase()135 let group = ScratchSuite()136 defer { group.remove() }137 let task = try await appTasks.create(title: "Cocher depuis l’écran d’accueil", dueDay: TaskDueRule.dayString(of: Date()))138 let other = try await appTasks.create(title: "Reste ouverte", dueDay: TaskDueRule.dayString(of: Date()))139 #expect(try await appStore.entityOps().count == 2)140141 // What the app shows follows its change stream; an external write is relayed by `noteExternalChange()` at activation.142 let changes = await appStore.changes()143 let sawReset = Task { () -> Bool in144 for await change in changes { if case .reset = change { return true } }145 return false146 }147148 // The app keeps writing while the "widget" completes the task: both connections write the same file.149 async let appWrite = appTasks.create(title: "Créée par l’app pendant ce temps")150 let outcome = await SharedTaskActions.setDone(taskId: task.id, databaseURL: url, lock: group.lock)151 _ = try await appWrite152 #expect(outcome == .done)153154 // The app's connection reads the committed change at once…155 let seen = try #require(try await appTasks.task(id: task.id))156 #expect(seen.isDone && seen.completedAt != nil)157 #expect(try await appTasks.task(id: other.id)?.isDone == false)158 #expect(try await appTasks.isPending(id: task.id))159 // …and its outbox holds the update, after the creation, for the next synchronisation.160 let ops = try await appTasks.pendingOperations().filter { $0.taskId == task.id }161 #expect(ops.map(\.verb) == ["create", "update"])162 #expect(try await appTasks.list(.open).map(\.title).sorted() == ["Créée par l’app pendant ce temps", "Reste ouverte"])163 #expect(try await appStore.integrityCheck().isEmpty)164165 await appStore.noteExternalChange()166 #expect(await sawReset.value)167168 // The widget no longer lists it; completing twice changes nothing; an unknown task is reported.169 #expect(await WidgetDataProvider(databaseURL: url, lock: group.lock).tasksContent(limit: 5).tasks.map(\.id) == [other.id])170 #expect(await SharedTaskActions.setDone(taskId: task.id, databaseURL: url, lock: group.lock) == .done)171 #expect(try await appTasks.pendingOperations().filter { $0.taskId == task.id }.count == 2)172 #expect(await SharedTaskActions.setDone(taskId: "00000000-0000-4000-8000-00000000dead", databaseURL: url, lock: group.lock) == .notFound)173 await appStore.close()174 }175176 @Test func a10DatabaseIsNeverOpenedForWritingByTheWidget() async throws {177 let container = try V1Container()178 defer { container.cleanUp() }179 let group = ScratchSuite()180 defer { group.remove() }181 #expect(container.userVersion == 1)182 #expect(!SharedTaskActions.isWritable(databaseURL: container.database))183 #expect(await SharedTaskActions.setDone(taskId: "00000000-0000-4000-8000-0000000000a1", databaseURL: container.database, lock: group.lock) == .unavailable)184 #expect(await WidgetDataProvider(databaseURL: container.database, lock: group.lock).tasksContent(limit: 3) == .unavailable)185 // Not migrated, no backup made: the app does that at its next launch.186 #expect(container.userVersion == 1)187 #expect(StoreBackup.existingBackups(of: container.database).isEmpty)188 }189190 @MainActor @Test func inTheAppTheWriteGoesThroughTheAppRepositories() async throws {191 // The host app installed its hook at launch (`AppRuntime.install`): no database URL = the app path.192 let app = try AppRuntime.model()193 let task = try await app.repositories.tasks.create(title: "Depuis un raccourci \(UUID().uuidString.prefix(6))")194 #expect(await SharedTaskActions.setDone(taskId: task.id, enforceLock: false) == .done)195 #expect(try await app.repositories.tasks.task(id: task.id)?.isDone == true)196 #expect(await SharedTaskActions.setDone(taskId: "00000000-0000-4000-8000-00000000dead", enforceLock: false) == .notFound)197 try await app.repositories.tasks.delete(id: task.id)198 }199}200