← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Tests/Unit/PromptSchedulerTests.swift (10141B)

1import Foundation
2import Testing
3import UserNotifications
4
5@testable import Reportage
6
7/// Records what's scheduled, in place of `UNUserNotificationCenter`.
8final class FakeNotifications: NotificationScheduling, @unchecked Sendable {
9    private let lock = NSLock()
10    private var requests: [String: UNNotificationRequest] = [:]
11    private(set) var addCount = 0
12
13    var identifiers: Set<String> { lock.withLock { Set(requests.keys) } }
14
15    func request(_ identifier: String) -> UNNotificationRequest? {
16        lock.withLock { requests[identifier] }
17    }
18
19    func pendingIdentifiers() async -> [String] {
20        lock.withLock { Array(requests.keys) }
21    }
22
23    func add(_ request: UNNotificationRequest) async throws {
24        lock.withLock {
25            requests[request.identifier] = request
26            addCount += 1
27        }
28    }
29
30    func removePending(_ identifiers: [String]) {
31        lock.withLock {
32            for identifier in identifiers { requests[identifier] = nil }
33        }
34    }
35}
36
37@Suite("PromptScheduler")
38struct PromptSchedulerTests {
39
40    private static var calendar: Calendar {
41        var calendar = Calendar(identifier: .gregorian)
42        calendar.timeZone = TimeZone(identifier: "Asia/Tokyo")!
43        return calendar
44    }
45
46    private static let now = calendar.date(
47        from: DateComponents(year: 2026, month: 10, day: 14, hour: 8))!
48
49    private static var settings: PromptSettings {
50        var settings = PromptSettings()
51        settings.isEnabled = true
52        return settings
53    }
54
55    private func schedule(
56        _ center: FakeNotifications, settings: PromptSettings = settings, now: Date = now
57    ) async {
58        await PromptScheduler(center: center)
59            .reschedule(settings: settings, secret: 7, now: now, calendar: Self.calendar)
60    }
61
62    private static func plan(settings: PromptSettings = settings, now: Date = now) -> Set<String> {
63        Set(
64            PromptSchedule.horizon(from: now, settings: settings, secret: 7, calendar: calendar)
65                .map(\.identifier))
66    }
67
68    @Test("Scheduling fills the horizon with prompts and a reminder")
69    func fills() async throws {
70        let center = FakeNotifications()
71        await schedule(center)
72
73        #expect(center.identifiers == Self.plan())
74        let reminder = try #require(center.identifiers.first { $0.hasPrefix("reminder.") })
75        #expect(center.request(reminder)?.content.categoryIdentifier == PromptNotification.reminderCategory)
76        let prompt = try #require(center.identifiers.first { $0.hasPrefix("prompt.") })
77        #expect(center.request(prompt)?.content.categoryIdentifier == PromptNotification.promptCategory)
78        #expect(center.request(prompt)?.trigger is UNCalendarNotificationTrigger)
79    }
80
81    @Test("Rescheduling leaves pending prompts alone")
82    func idempotent() async {
83        let center = FakeNotifications()
84        await schedule(center)
85        let added = center.addCount
86        await schedule(center)
87        #expect(center.addCount == added)
88    }
89
90    @Test("A day later, fired prompts go and the next day's come, and the old reminder becomes a prompt")
91    func rolls() async {
92        let center = FakeNotifications()
93        await schedule(center)
94        let later = Self.now.addingTimeInterval(24 * 60 * 60)
95        await schedule(center, now: later)
96        #expect(center.identifiers == Self.plan(now: later))
97    }
98
99    @Test("Changing the settings replaces the prompts, but keeps snoozed ones")
100    func settingsChange() async {
101        let center = FakeNotifications()
102        await schedule(center)
103        try? await center.add(PromptNotification.snoozeRequest(promptedAt: Self.now, delay: 900))
104        var settings = Self.settings
105        settings.perDay = 2
106        await schedule(center, settings: settings)
107
108        let snoozed = center.identifiers.filter { $0.hasPrefix("snoozed.") }
109        #expect(snoozed.count == 1)
110        #expect(center.identifiers.subtracting(snoozed) == Self.plan(settings: settings))
111    }
112
113    @Test("Turning prompts off removes them all, snoozed ones too, but not other notifications")
114    func off() async throws {
115        let center = FakeNotifications()
116        await schedule(center)
117        try await center.add(PromptNotification.snoozeRequest(promptedAt: Self.now, delay: 900))
118        try await center.add(
119            UNNotificationRequest(identifier: "other", content: UNNotificationContent(), trigger: nil))
120        var settings = Self.settings
121        settings.isEnabled = false
122        await schedule(center, settings: settings)
123        #expect(center.identifiers == ["other"])
124    }
125}
126
127@Suite("PromptResponder")
128struct PromptResponderTests {
129
130    private let persistence = makeTestPersistence()
131    private let center = FakeNotifications()
132
133    private var responder: PromptResponder {
134        PromptResponder(
135            store: ReportStore(persistence: persistence), center: center,
136            capture: { Context(device: DeviceContext(batteryLevel: 0.5)) })
137    }
138
139    private static let firedAt = Date(timeIntervalSinceReferenceDate: 800_000_000)
140    private static let deliveredAt = firedAt.addingTimeInterval(900)
141    private static let now = deliveredAt.addingTimeInterval(60)
142
143    private static func response(_ action: String, snoozed: Bool = false) -> PromptResponse {
144        PromptResponse(
145            category: PromptNotification.promptCategory, action: action,
146            deliveredAt: snoozed ? deliveredAt : firedAt,
147            promptedAt: snoozed ? firedAt : nil)
148    }
149
150    @Test("Instant Report saves an instant random report prompted when the prompt first fired")
151    func instantReport() async throws {
152        let survey = try await responder.respond(
153            to: Self.response(PromptNotification.instantReportAction, snoozed: true),
154            settings: PromptSettings(), now: Self.now)
155        #expect(survey == nil)
156
157        let store = ReportStore(persistence: persistence)
158        #expect(try await store.passiveCount() == 1)
159        let context = persistence.newBackgroundContext()
160        let report = try await context.perform {
161            try context.fetch(ReportEntity.fetchRequest()).first?.report()
162        }
163        #expect(report?.kind == .random)
164        #expect(report?.trigger == .notification)
165        #expect(report?.state == .passive)
166        #expect(report?.date == Self.now)
167        #expect(report?.promptedAt == Self.firedAt)
168        #expect(report?.context.device?.batteryLevel == 0.5)
169    }
170
171    @Test("Snooze repeats the prompt later, keeping when it first fired")
172    func snooze() async throws {
173        var settings = PromptSettings()
174        settings.snooze = 20
175        _ = try await responder.respond(
176            to: Self.response(PromptNotification.snoozeAction), settings: settings, now: Self.now)
177
178        let id = try #require(center.identifiers.first)
179        #expect(PromptNotification.kind(ofIdentifier: id) == .snoozed)
180        let request = try #require(center.request(id))
181        #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == TimeInterval(20 * 60))
182        #expect(request.content.categoryIdentifier == PromptNotification.promptCategory)
183
184        // Snoozing the snoozed prompt keeps the original time.
185        let delivered = PromptResponse(
186            category: PromptNotification.promptCategory, action: UNNotificationDefaultActionIdentifier,
187            deliveredAt: Self.deliveredAt,
188            promptedAt: (request.content.userInfo[PromptNotification.promptedAtKey] as? Double)
189                .map(Date.init(timeIntervalSinceReferenceDate:)))
190        #expect(delivered.firedAt == Self.firedAt)
191    }
192
193    @Test("Tapping a prompt opens a random survey for when it was tapped")
194    func tap() async throws {
195        let survey = try #require(
196            try await responder.respond(
197                to: Self.response(UNNotificationDefaultActionIdentifier, snoozed: true),
198                settings: PromptSettings(), now: Self.now))
199        #expect(survey.kind == .random)
200        #expect(survey.date == Self.now)
201        #expect(survey.trigger == .notification)
202        #expect(survey.promptedAt == Self.firedAt)
203        #expect(survey.reportID == nil)
204    }
205
206    @Test("Tapping the reminder or dismissing a prompt does nothing")
207    func ignored() async throws {
208        let reminder = PromptResponse(
209            category: PromptNotification.reminderCategory, action: UNNotificationDefaultActionIdentifier,
210            deliveredAt: Self.firedAt)
211        #expect(try await responder.respond(to: reminder, settings: PromptSettings()) == nil)
212        #expect(
213            try await responder.respond(
214                to: Self.response(UNNotificationDismissActionIdentifier), settings: PromptSettings())
215                == nil)
216        #expect(center.identifiers.isEmpty)
217        #expect(try await ReportStore(persistence: persistence).passiveCount() == 0)
218    }
219}
220
221@Suite("PromptRefreshQueue")
222struct PromptRefreshQueueTests {
223
224    /// Records when each run starts and ends.
225    private actor Log {
226        var events: [String] = []
227        func record(_ event: String) { events.append(event) }
228    }
229
230    @Test("Runs never overlap, and each waits for the one before")
231    func serial() async {
232        let queue = PromptRefreshQueue()
233        let log = Log()
234        // Started in order, the first taking longest, so overlapping runs
235        // would interleave or finish out of order.
236        await withTaskGroup(of: Void.self) { group in
237            for (index, delay) in [30, 10, 0].enumerated() {
238                group.addTask {
239                    await queue.run {
240                        await log.record("start \(index)")
241                        try? await Task.sleep(for: .milliseconds(delay))
242                        await log.record("end \(index)")
243                    }
244                }
245                // Lets each run reach the queue before the next is started.
246                try? await Task.sleep(for: .milliseconds(5))
247            }
248        }
249        #expect(await log.events == ["start 0", "end 0", "start 1", "end 1", "start 2", "end 2"])
250    }
251}