forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppleNotesReaderServiceTests.swift
More file actions
284 lines (243 loc) · 10.7 KB
/
Copy pathAppleNotesReaderServiceTests.swift
File metadata and controls
284 lines (243 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import GRDB
import XCTest
@testable import Omi_Computer
final class AppleNotesReaderServiceTests: XCTestCase {
func testClassifiesSqliteAuthorizationDeniedAsPermissionError() {
let error = NSError(
domain: "GRDB",
code: 23,
userInfo: [NSLocalizedDescriptionKey: "SQLite error 23: authorization denied"]
)
guard
case .authorizationDenied(let path) = AppleNotesReaderService.classifyReadError(
error, path: "/notes/NoteStore.sqlite")
else {
return XCTFail("Expected authorizationDenied classification")
}
XCTAssertEqual(path, "/notes/NoteStore.sqlite")
}
func testIsLikelyAttachmentDoesNotDropOrdinaryNotesContainingExecSubstring() {
// Regression: a raw `contains("exec")` substring match wrongly classified ordinary
// notes as attachment/metadata artifacts and silently dropped them from the import.
for title in ["Q3 execution plan", "Executive summary", "executed the migration", "executive decisions"] {
XCTAssertFalse(
AppleNotesReaderService.isLikelyAttachment(title: title, summary: "notes and details"),
"note titled \"\(title)\" must not be filtered as an attachment"
)
}
}
func testIsLikelyAttachmentStillFiltersArtifactTokens() {
// The metadata/artifact tokens the filter targets must still be caught.
XCTAssertTrue(AppleNotesReaderService.isLikelyAttachment(title: "kMDItemFSName", summary: ""))
XCTAssertTrue(AppleNotesReaderService.isLikelyAttachment(title: "SOLITE", summary: ""))
XCTAssertTrue(AppleNotesReaderService.isLikelyAttachment(title: "exec", summary: ""))
XCTAssertTrue(AppleNotesReaderService.isLikelyAttachment(title: "", summary: ""))
}
func testResolveSelectedFolderAcceptsAndInfersNotesContainer() throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let home = root.appendingPathComponent("home", isDirectory: true)
let groupContainers = home.appendingPathComponent("Library/Group Containers", isDirectory: true)
let notesContainer = groupContainers.appendingPathComponent("group.com.apple.notes", isDirectory: true)
try FileManager.default.createDirectory(at: notesContainer, withIntermediateDirectories: true)
XCTAssertEqual(
try AppleNotesReaderService.resolveSelectedFolder(groupContainers, homeDirectory: home).path,
notesContainer.path
)
XCTAssertEqual(
try AppleNotesReaderService.resolveSelectedFolder(notesContainer, homeDirectory: home).path,
notesContainer.path
)
}
func testReadRecentNotesResolvesLegacyGroupContainersSelection() async throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let groupContainers = root.appendingPathComponent("Library/Group Containers", isDirectory: true)
let notesContainer = try makeNotesContainerFixture(in: groupContainers, withSchema: true)
let store = notesContainer.appendingPathComponent("NoteStore.sqlite")
let dbQueue = try DatabaseQueue(path: store.path)
try await dbQueue.write { db in
try db.execute(
sql: """
INSERT INTO ZICCLOUDSYNCINGOBJECT
(Z_PK, ZTITLE, ZSUMMARY, ZMODIFICATIONDATE, ZNOTE, ZMARKEDFORDELETION)
VALUES (?, ?, ?, ?, ?, ?)
""",
arguments: [1, "Legacy folder import", "Parent folder still works", 42.0, 1, 0]
)
}
let notes = try await AppleNotesReaderService.shared.readRecentNotes(
maxResults: 10,
selectedFolderPath: groupContainers.path
)
XCTAssertEqual(notes.count, 1)
XCTAssertEqual(notes.first?.title, "Legacy folder import")
}
func testResolveSelectedFolderRejectsUnrelatedFolder() throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let unrelated = root.appendingPathComponent("Documents", isDirectory: true)
try FileManager.default.createDirectory(at: unrelated, withIntermediateDirectories: true)
XCTAssertThrowsError(try AppleNotesReaderService.resolveSelectedFolder(unrelated, homeDirectory: root)) { error in
guard case .invalidSelectedFolder(let path) = error as? AppleNotesReaderError else {
return XCTFail("Expected invalidSelectedFolder, got \(error)")
}
XCTAssertEqual(path, unrelated.path)
}
}
func testReadProbeRejectsInvalidFolderBeforeEnteringReaderActor() throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let invalidPath = root.appendingPathComponent("not-apple-notes", isDirectory: true).path
XCTAssertThrowsError(
try AppleNotesReadProbe.resolveRequestedFolder(
path: invalidPath,
homeDirectory: root
)
) { error in
guard case .invalidSelectedFolder(let path) = error as? AppleNotesReaderError else {
return XCTFail("Expected invalidSelectedFolder, got \(error)")
}
XCTAssertEqual(path, invalidPath)
}
}
func testReadRecentNotesFromSelectedFolderFixture() async throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let notesContainer = try makeNotesContainerFixture(in: root, withSchema: true)
let store = notesContainer.appendingPathComponent("NoteStore.sqlite")
let dbQueue = try DatabaseQueue(path: store.path)
try await dbQueue.write { db in
try db.execute(
sql: """
INSERT INTO ZICCLOUDSYNCINGOBJECT
(Z_PK, ZTITLE, ZSUMMARY, ZMODIFICATIONDATE, ZNOTE, ZMARKEDFORDELETION)
VALUES (?, ?, ?, ?, ?, ?)
""",
arguments: [1, "Launch checklist", "Ship Notes connector", 42.0, 1, 0]
)
}
let notes = try await AppleNotesReaderService.shared.readRecentNotes(
maxResults: 10,
selectedFolderPath: notesContainer.path
)
XCTAssertEqual(notes.count, 1)
XCTAssertEqual(notes.first?.title, "Launch checklist")
XCTAssertEqual(notes.first?.summary, "Ship Notes connector")
}
func testReadRecentNotesClampsNegativeLimit() async throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let notesContainer = try makeNotesContainerFixture(in: root, withSchema: true)
let notes = try await AppleNotesReaderService.shared.readRecentNotes(
maxResults: -1,
selectedFolderPath: notesContainer.path
)
XCTAssertTrue(notes.isEmpty)
}
func testConnectionStatusTreatsZeroNotesAsReadable() async throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let notesContainer = try makeNotesContainerFixture(in: root, withSchema: true)
let status = await AppleNotesReaderService.shared.connectionStatus(
maxResults: 10,
selectedFolderPath: notesContainer.path
)
guard case .connected(let noteCount, _) = status else {
return XCTFail("Expected connected status, got \(status)")
}
XCTAssertEqual(noteCount, 0)
XCTAssertTrue(status.isConnected)
}
func testValidateSelectedFolderClassifiesSchemaFailure() async throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let notesContainer = try makeNotesContainerFixture(in: root, withSchema: false)
_ = try DatabaseQueue(path: notesContainer.appendingPathComponent("NoteStore.sqlite").path)
do {
_ = try await AppleNotesReaderService.shared.validateSelectedFolder(path: notesContainer.path, remember: false)
XCTFail("Expected schema validation to fail")
} catch let error as AppleNotesReaderError {
XCTAssertEqual(error.reasonCode, "schema_unavailable")
}
}
func testReadOutcomeClassifiesPathFailuresAsNeedsAccess() {
let outcome = AppleNotesReaderService.classifyReadOutcome(
noteCount: nil,
error: .invalidSelectedFolder(path: "/tmp/wrong")
)
XCTAssertEqual(
outcome,
.needsAccess(
message: "Choose the Apple Notes folder named group.com.apple.notes.",
reasonCode: "invalid_selected_folder"
)
)
}
func testReadOutcomeClassifiesSchemaAndReadFailuresAsErrors() {
XCTAssertEqual(
AppleNotesReaderService.classifyReadOutcome(
noteCount: nil,
error: .schemaUnavailable(path: "/notes/NoteStore.sqlite")
),
.error(
message: "Apple Notes data store could not be read because its database format was not recognized.",
reasonCode: "schema_unavailable"
)
)
XCTAssertEqual(
AppleNotesReaderService.classifyReadOutcome(
noteCount: nil,
error: .storeReadFailed(path: "/notes/NoteStore.sqlite", reason: "disk I/O error")
),
.error(
message: "Apple Notes data store could not be read: disk I/O error",
reasonCode: "store_read_failed"
)
)
}
func testConnectionStatusSurfacesSchemaFailureAsError() async throws {
let root = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let notesContainer = try makeNotesContainerFixture(in: root, withSchema: false)
_ = try DatabaseQueue(path: notesContainer.appendingPathComponent("NoteStore.sqlite").path)
let status = await AppleNotesReaderService.shared.connectionStatus(
maxResults: 10,
selectedFolderPath: notesContainer.path
)
guard case .error(let message, let reasonCode) = status else {
return XCTFail("Expected error status, got \(status)")
}
XCTAssertEqual(reasonCode, "schema_unavailable")
XCTAssertTrue(message.contains("database format was not recognized"))
}
private func makeNotesContainerFixture(in root: URL, withSchema: Bool) throws -> URL {
let notesContainer = root.appendingPathComponent("group.com.apple.notes", isDirectory: true)
try FileManager.default.createDirectory(at: notesContainer, withIntermediateDirectories: true)
let store = notesContainer.appendingPathComponent("NoteStore.sqlite")
let dbQueue = try DatabaseQueue(path: store.path)
if withSchema {
try dbQueue.write { db in
try db.execute(
sql: """
CREATE TABLE ZICCLOUDSYNCINGOBJECT (
Z_PK INTEGER PRIMARY KEY,
ZTITLE TEXT,
ZSUMMARY TEXT,
ZMODIFICATIONDATE REAL,
ZNOTE INTEGER,
ZMARKEDFORDELETION INTEGER
)
"""
)
}
}
return notesContainer
}
private func makeTemporaryDirectory() throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("AppleNotesReaderServiceTests-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
}