SPB Git

Repository Public

WidgetLockTests.swift 9.1 KB 170 lines swift

1// SP Notes iOS2// File: Tests/WidgetLockTests.swift3// Description: The app lock seen by the widgets: the 1.0 setting is mirrored into the shared defaults at launch and at every4//              change, and every widget-facing content function answers the redacted state while it is on — whatever the5//              database holds — as do the note picker of the configurable widget and the task-completing intent.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AppIntents10import Foundation11import Testing12import SPNotesCore13@testable import SPNotes1415/// A throw-away defaults suite standing for the App Group (or for the app's standard defaults).16struct ScratchSuite {17    let name = "spnotes-tests-\(UUID().uuidString)"18    var defaults: UserDefaults { UserDefaults(suiteName: name)! }19    var lock: WidgetLock { WidgetLock(suiteName: name) }20    func remove() { UserDefaults().removePersistentDomain(forName: name) }21}2223@MainActor24struct WidgetLockMirrorTests {25    @Test func a10SettingIsMirroredAtTheFirst20Launch() {26        let standard = ScratchSuite(), group = ScratchSuite()27        defer { standard.remove(); group.remove() }28        // 1.0 wrote the setting in the app's own defaults only.29        standard.defaults.set(true, forKey: "lock.enabled")30        #expect(group.lock.isEnabled == false)3132        let lock = AppLock(defaults: standard.defaults, mirror: group.lock)33        #expect(lock.isEnabled && lock.isLocked)34        #expect(group.lock.isEnabled)35        #expect(lock.mirrorChangedAtLaunch)36        #expect(standard.defaults.bool(forKey: "lock.enabled"))   // the 1.0 key stays the source of truth3738        // The next launch finds the mirror in step.39        #expect(AppLock(defaults: standard.defaults, mirror: group.lock).mirrorChangedAtLaunch == false)40    }4142    @Test func aUserWithoutLockSeesNoChange() {43        let standard = ScratchSuite(), group = ScratchSuite()44        defer { standard.remove(); group.remove() }45        let lock = AppLock(defaults: standard.defaults, mirror: group.lock)46        #expect(!lock.isEnabled && !lock.mirrorChangedAtLaunch && !group.lock.isEnabled)47    }4849    @Test func everyChangeIsMirroredAndAnnounced() {50        let standard = ScratchSuite(), group = ScratchSuite()51        defer { standard.remove(); group.remove() }52        let lock = AppLock(defaults: standard.defaults, mirror: group.lock)53        var announced: [Bool] = []54        lock.onEnabledChange = { announced.append($0) }55        lock.isEnabled = true56        #expect(group.lock.isEnabled && standard.defaults.bool(forKey: "lock.enabled"))57        lock.isEnabled = true   // no change: no reload58        lock.isEnabled = false59        #expect(!group.lock.isEnabled && !standard.defaults.bool(forKey: "lock.enabled"))60        #expect(announced == [true, false])61    }6263    @Test func aMirrorOutOfStepIsRepaired() {64        let standard = ScratchSuite(), group = ScratchSuite()65        defer { standard.remove(); group.remove() }66        group.defaults.set(true, forKey: "lock.enabled")   // e.g. restored from a backup of another state67        let lock = AppLock(defaults: standard.defaults, mirror: group.lock)68        #expect(!group.lock.isEnabled && lock.mirrorChangedAtLaunch)69    }7071    @Test func theModelReloadsTheWidgetsWhenTheSettingChanges() throws {72        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-lock-\(UUID().uuidString)", isDirectory: true)73        var reloads = 074        let app = try AppModel(configuration: AppConfiguration(api: .production(appVersion: "tests"), dataDirectory: directory, inMemoryStore: true),75                               widgets: WidgetRefresher(delay: .seconds(60)) { reloads += 1 })76        app.installSystemIntegration()77        let before = reloads78        // The setting itself is not touched (it is the host app's real one): the announcement is what the model listens to.79        app.lock.onEnabledChange?(true)80        #expect(reloads == before + 1)81        app.lock.onEnabledChange?(false)82        #expect(reloads == before + 2)83    }8485    @Test func aMissingSuiteReadsUnlocked() {86        #expect(WidgetLock(suiteName: nil).isEnabled == false)87        #expect(WidgetLock(suiteName: nil).set(true) == false)88    }89}9091struct WidgetLockContentTests {92    private func makeDatabase() async throws -> (url: URL, store: NotesStore, noteId: String, taskId: String) {93        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-wlock-\(UUID().uuidString)", isDirectory: true)94        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)95        let url = directory.appendingPathComponent("notes.sqlite")96        let store = try NotesStore.open(url: url).get()97        let page = try await store.createPage(NewPage(title: "Dossier médical", pinned: true, plainText: "Résultats confidentiels", wordCount: 2, preview: "Résultats confidentiels"))98        let tasks = TasksRepository(context: RepositoryContext(store: store, api: SystemTestSupport.offlineAPI(), engine: nil))99        let task = try await tasks.create(title: "Appeler la clinique", dueAt: Date().addingTimeInterval(-3_600), pageId: page.id)100        return (url, store, page.id, task.id)101    }102103    @Test func everyContentFunctionIsRedactedWhileTheLockIsOn() async throws {104        let group = ScratchSuite()105        defer { group.remove() }106        let (url, store, noteId, taskId) = try await makeDatabase()107        var provider = WidgetDataProvider(databaseURL: url, lock: group.lock)108109        // Unlocked: the content is there.110        #expect(await provider.content(.recent, limit: 3).notes.map(\.title) == ["Dossier médical"])111        #expect(await provider.content(.pinned, limit: 3).notes.count == 1)112        #expect(await provider.single(noteId: noteId, textLength: 100) == .note(try #require(await provider.note(id: noteId, textLength: 100))))113        #expect(await provider.single(noteId: nil, textLength: 100) == .unconfigured)114        #expect(await provider.single(noteId: "00000000-0000-4000-8000-00000000dead", textLength: 100) == .missing)115        #expect(await provider.tasksContent(limit: 3).tasks.map(\.id) == [taskId])116117        group.lock.set(true)118        provider = WidgetDataProvider(databaseURL: url, lock: group.lock)119        #expect(await provider.content(.recent, limit: 3) == .locked)120        #expect(await provider.content(.pinned, limit: 3) == .locked)121        #expect(await provider.single(noteId: noteId, textLength: 100) == .locked)122        #expect(await provider.single(noteId: nil, textLength: 100) == .locked)123        #expect(await provider.tasksContent(limit: 3) == .locked)124        #expect(WidgetContent.locked.notes.isEmpty && WidgetTasksContent.locked.tasks.isEmpty)125126        // No completing from a locked widget: the task stays open and nothing is queued.127        let opsBefore = try await store.entityOps().count128        #expect(await SharedTaskActions.setDone(taskId: taskId, databaseURL: url, lock: group.lock, enforceLock: true) == .locked)129        #expect(try await store.entityOps().count == opsBefore)130131        group.lock.set(false)132        #expect(await provider.content(.recent, limit: 3).notes.count == 1)133        await store.close()134    }135136    @Test func theWidgetNotePickerListsNoTitleWhileLocked() async throws {137        let group = ScratchSuite()138        defer { group.remove() }139        let (url, store, noteId, _) = try await makeDatabase()140        let data = WidgetDataProvider(databaseURL: url, lock: group.lock)141        let inWidget = NoteEntityQuery(data: data, policy: NotePickerPolicy(lock: group.lock, appliesLock: true))142        let inApp = NoteEntityQuery(data: data, policy: NotePickerPolicy(lock: group.lock, appliesLock: false))143144        #expect(try await inWidget.suggestedEntities().sections.flatMap(\.items).map(\.value.title) == ["Dossier médical"])145        #expect(try await inWidget.entities(matching: "medical").sections.flatMap(\.items).count == 1)146147        group.lock.set(true)148        let suggested = try await inWidget.suggestedEntities()149        #expect(suggested.sections.flatMap(\.items).isEmpty)150        #expect(suggested.promptLabel != nil)   // the explanation151        #expect(try await inWidget.entities(matching: "medical").sections.flatMap(\.items).isEmpty)152        // The configured note keeps its identity (the widget keeps its configuration) but shows nothing.153        let resolved = try await inWidget.entities(for: [noteId])154        #expect(resolved.map(\.id) == [noteId])155        #expect(resolved.allSatisfy { $0.title == NotePickerPolicy.lockedTitle && $0.preview.isEmpty })156157        // The app's own intents (Shortcuts runs them in the app, behind the device's own lock) keep working.158        #expect(try await inApp.suggestedEntities().sections.flatMap(\.items).map(\.value.title) == ["Dossier médical"])159        await store.close()160    }161}162163/// Shared helpers of the system tests.164enum SystemTestSupport {165    /// A client that is never called (the offline paths of the repositories need one to exist).166    static func offlineAPI() -> NotesAPI {167        NotesAPI(client: HTTPClient(configuration: .production(appVersion: "tests"), tokenStore: InMemoryTokenStore(token: nil)))168    }169}170
Files main
Menu

Theme