Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/AppTests/FeaturesTests.swift3// Description: Hosted tests of the SPNotesFeatures wiring: which screens a window lists for a local library, a 2.x server and a 3.0 server; the window as FeatureRouter; database and canvas pages opening natively; the block detail provider for every 3.0 node; a drawing edited and a recording adopted offline through the app's attachment loader; the keychain migration on real keychain items of the Debug build; offscreen pictures of the block sheets.4import XCTest5import SwiftUI6import SPNotesDocument7import SPNotesStore8import SPNotesAPI9import SPNotesSync10import SPNotesEditor11import SPNotesFeatures12import SPNotesTestSupport13@testable import SPNotes1415final class FeaturesWiringTests: XCTestCase {16 @MainActor func testTheSidebarListsOnlyWhatTheServerSupports() async throws {17 // no account: the three local screens, nothing that needs a server18 let local = await Bench(server: false); defer { local.cleanup() }19 XCTAssertEqual(Destination.features.filter { local.env.features.isAvailable($0, env: local.env) }, [.inbox, .tasks, .search])20 // a 2.x server: the routes that exist since 2.x, none of the 3.0 screens21 let (old, fake2) = await fakeBench(apiLevel: 2); defer { old.cleanup(); fake2.shutdown() }22 _ = await old.env.syncMonitor.run()23 let on2 = Set(Destination.features.filter { old.env.features.isAvailable($0, env: old.env) })24 if old.env.serverMeta != nil { XCTAssertEqual(on2, [.inbox, .tasks, .search, .databases, .research, .ask]) } else { XCTAssertEqual(on2, [.inbox, .tasks, .search], "a server that never answered /api/meta is treated as unknown") }25 // a 3.0 server: every screen whose feature it announces26 let (b, fake) = await fakeBench(); defer { b.cleanup(); fake.shutdown() }27 _ = await b.env.syncMonitor.run()28 let meta = try must(b.env.serverMeta); XCTAssertEqual(meta.api, 3)29 let w = WindowModel(env: b.env)30 for d in Destination.features {31 let need = FeaturesHost.requirement(d)32 let expected = need == nil || need == "" || meta.has(need!)33 XCTAssertEqual(b.env.features.isAvailable(d, env: b.env), expected, "\(d)")34 XCTAssertEqual(b.env.features.screen(for: d, env: b.env, window: w) != nil, expected, "\(d) has a screen exactly when it is listed")35 XCTAssertEqual(AppCommandCatalog.commands(env: b.env, window: w).contains { $0.id == "go." + d.rawValue }, expected, "\(d) in the command center")36 }37 XCTAssertTrue(b.env.features.isAvailable(.today, env: b.env)); XCTAssertTrue(b.env.features.isAvailable(.canvas, env: b.env))38 // the assistant switched off in the settings hides « Demander »39 b.env.preferences.aiEnabled = false; XCTAssertFalse(b.env.features.isAvailable(.ask, env: b.env)); b.env.preferences.aiEnabled = true40 }4142 @MainActor func testTheWindowRoutesTheScreensAndOpensDatabaseAndCanvasPagesNatively() async throws {43 let (b, fake) = await fakeBench(); defer { b.cleanup(); fake.shutdown() }44 let canvasId = fake.webCreateCanvas(title: "Plan de thèse")45 let note = fake.webCreatePage(title: "Note ordinaire")46 _ = await b.env.syncMonitor.run()47 let w = WindowModel(env: b.env); let router: any FeatureRouter = w48 router.openCanvas(pageId: canvasId); XCTAssertEqual(w.destination, .canvas); XCTAssertEqual(w.canvasPageId, canvasId)49 XCTAssertNotNil(b.env.features.screen(for: .canvas, env: b.env, window: w))50 router.openDatabase(id: "db-1"); XCTAssertEqual(w.destination, .databases); XCTAssertEqual(w.databaseId, "db-1")51 router.openPage(id: note, blockId: "abc"); XCTAssertEqual(w.destination, .notes); XCTAssertEqual(w.pendingBlock, "abc")52 router.presentError(RepositoryError.offline); XCTAssertTrue(b.env.toasts.current?.isError ?? false)53 // a canvas page selected in the list shows the canvas, not the text editor; a plain note keeps its editor54 let canvasSession = try must(await b.env.session(for: canvasId)); XCTAssertEqual(canvasSession.page.type, "canvas")55 XCTAssertNotNil(NativePage.view(for: canvasSession, env: b.env, window: w))56 let noteSession = try must(await b.env.session(for: note)); XCTAssertNil(NativePage.view(for: noteSession, env: b.env, window: w))57 // « Demander » receives the note in front and its selection58 w.open(note); try await Task.sleep(for: .milliseconds(300))59 let s = try must(w.session); b.type(s, "Une phrase à interroger."); s.editor.textView.setSelectedRange(NSRange(location: 4, length: 6))60 let context = FeaturesHost.askContext(w); XCTAssertEqual(context.pageId, note); XCTAssertEqual(context.selection, "phrase"); XCTAssertNotNil(context.selectionBlockId)61 // the zoom state belongs to the note62 XCTAssertEqual(s.zoom.level, .full); s.zoom.level = .outline; XCTAssertEqual(noteSession.zoom.level, .outline, "one state per open note")63 }6465 @MainActor func testEveryNewBlockHasItsDetailViewAndFilesWorkOffline() async throws {66 let b = await Bench(server: false); defer { b.cleanup() }67 let id = try must(await b.env.library.newNote(title: "Blocs")); let s = await b.session(id); let v = s.editor.textView; let w = WindowModel(env: b.env)68 v.insertMermaid(); v.insertChart(); v.insertRunCode(code: "1+1"); v.insertQueryView(); v.insertBibliography(); v.insertDrawing(); v.insertBlockRef(pageId: id, blockId: nil); v.insertCanvasLink(pageId: id)69 v.insertPDF(attachmentId: "11111111-2222-4333-8444-555555555555", name: "a.pdf"); v.insertAudio(attachmentId: "22222222-3333-4444-8555-666666666666", duration: 3, title: "Mémo")70 var applied: [PMNode] = []71 let context = BlockDetailContext(env: b.env, session: s, editable: true, router: w, apply: { applied.append($0) }, remove: {}, dismiss: {})72 for line in s.editor.document().lines { if let node = line.atomNode { XCTAssertNotNil(b.env.blockDetails.detail(for: node, context: context), "\(node.type) has a detail view") } }73 XCTAssertNil(b.env.blockDetails.detail(for: PMNode(type: "table"), context: context), "legacy blocks keep this app's own editors")74 XCTAssertNil(b.env.blockDetails.detail(for: PMNode(type: "hologram"), context: context), "an unknown block has no editor")75 // a drawing edited with the mouse editor, with no network: ink and preview are stored on this Mac, `pk` is cleared76 let drawing = try must(s.editor.document().lines.compactMap { $0.atomNode }.compactMap(DrawingBlock.init(node:)).first)77 let ink = InkDocument(width: 640, height: 360, strokes: [InkStroke(tool: .pen, color: .black, width: 3, points: [InkPoint(x: 20, y: 30), InkPoint(x: 300, y: 200), InkPoint(x: 600, y: 80)])])78 let loader = b.env.attachmentLoader(pageId: id); XCTAssertTrue(loader.canUpload)79 let updated = try await InkDrawingExport.store(ink, into: drawing, pageId: id, loader: loader)80 let inkId = try must(updated.ink), previewId = try must(updated.preview); XCTAssertNil(updated.pk); XCTAssertEqual(updated.width, 640)81 let stored = try await b.env.store.attachments(pageId: id); XCTAssertEqual(Set(stored.map(\.id)), [inkId, previewId]); XCTAssertTrue(stored.allSatisfy { $0.state == .pendingUpload }, "waiting for the synchronisation")82 let inkData = try await loader.data(id: inkId); let back = try InkDocument(data: inkData); XCTAssertEqual(back.strokes.count, 1); XCTAssertEqual(back.strokes[0].points.count, 3)83 let png = try await loader.data(id: previewId); XCTAssertNotNil(NSImage(data: png), "the preview is a real picture")84 // written into the note through the editor: one undo step, and the card now shows the picture85 let range = try must(v.rangeOfBlock(id: try must(drawing.id))); v.replaceAtom(at: NSRange(location: range.location, length: 1), with: updated.node())86 XCTAssertEqual(AtomCardModel.make(updated.node(), resources: s.editor).body, .image(src: "/api/files/\(previewId)"))87 XCTAssertTrue(s.editor.document().attachmentReferences().contains(inkId)); XCTAssertTrue(s.editor.document().schemaViolations().isEmpty)88 // a fresh recording is adopted the same way (the library hands the file over instead of uploading it)89 let wav = b.dir.appendingPathComponent("memo.m4a"); try Data(repeating: 0, count: 2048).write(to: wav)90 let adopted = try await NoteAudioFiles(env: b.env, pageId: id).adopt(recording: wav, pageId: id); let audioId = try must(adopted)91 let url = try await NoteAudioFiles(env: b.env, pageId: id).localFileURL(attachmentId: audioId); XCTAssertTrue(FileManager.default.fileExists(atPath: url.path))92 // the citation picker hands back a node this app inserts93 _ = FeaturesBlockDetails.citationPicker(existing: nil, context: context)94 _ = applied95 }9697 @MainActor func testTheKeychainMigrationOnRealItemsOfThisBuild() throws {98 // two real generic-password items of the legacy keychain (the Debug build has no access group: the data-protection99 // keychain itself can only be exercised by a signed build)100 let tag = "ai.spboucher.spnotes.tests." + UUID().uuidString101 let old = KeychainTokenStore(service: tag + ".old", account: "http://localhost:9", useDataProtectionKeychain: false)102 let new = KeychainTokenStore(service: tag + ".new", account: "http://localhost:9", useDataProtectionKeychain: false)103 defer { try? old.clear(); try? new.clear() }104 do { try old.save("token-of-1.0.2-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") } catch { throw XCTSkip("the keychain is not available to this test host: \(error)") }105 XCTAssertEqual(old.load(), "token-of-1.0.2-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")106 let store = MigratingTokenStore(primary: new, legacy: old)107 XCTAssertEqual(store.load(), "token-of-1.0.2-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "the 1.x session is found")108 XCTAssertEqual(new.load(), "token-of-1.0.2-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "copied to the new item"); XCTAssertNil(old.load(), "and the old item removed only after the copy was read back")109 try store.save("rotated-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); XCTAssertEqual(store.load(), "rotated-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); XCTAssertNil(old.load())110 try store.clear(); XCTAssertNil(new.load()); XCTAssertNil(store.load())111 // the real data-protection keychain refuses an unsigned build: the 1.x item keeps serving, nothing is lost112 try old.save("still-here-cccccccccccccccccccccccccccccccccc")113 let unsigned = MigratingTokenStore(primary: KeychainTokenStore(service: tag + ".dp", account: "http://localhost:9", accessGroup: "3YM54G49SN.ai.spboucher.spnotes", useDataProtectionKeychain: true), legacy: old)114 XCTAssertEqual(unsigned.load(), "still-here-cccccccccccccccccccccccccccccccccc"); XCTAssertEqual(old.load(), "still-here-cccccccccccccccccccccccccccccccccc", "kept: the copy could not be made")115 try unsigned.save("rotated-again-dddddddddddddddddddddddddddddd"); XCTAssertEqual(unsigned.load(), "rotated-again-dddddddddddddddddddddddddddddd")116 try unsigned.clear(); XCTAssertNil(unsigned.load())117 }118119 @MainActor func testBlockSheetsRender() async throws {120 let (b, fake) = await fakeBench(); defer { b.cleanup(); fake.shutdown() }121 _ = await b.env.syncMonitor.run()122 let id = try must(await b.env.library.newNote(title: "Blocs")); let s = await b.session(id); let v = s.editor.textView; let w = WindowModel(env: b.env)123 v.insertMermaid(); v.insertRunCode(code: "const r = [0.012, -0.008];\nconsole.log(r.length);"); v.insertQueryView(source: .tasks, title: "Tâches ouvertes"); v.insertBibliography(); v.insertDrawing()124 v.insertBlockAtom(ChartBlock(kind: .line, title: "Volatilité réalisée (%)", columns: ["Mois", "1 min", "5 min"], rows: [["jan", 18.2, 17.1], ["fév", 21.4, 19.8], ["mars", 34.9, 31.2], ["avr", 27.3, 25.9]], x: "Mois", y: ["1 min", "5 min"]).node())125 _ = await b.env.tasks.add("Relire le chapitre 3"); _ = await b.env.tasks.add("Envoyer la figure 2")126 let context = BlockDetailContext(env: b.env, session: s, editable: true, router: w, apply: { _ in }, remove: {}, dismiss: {})127 for dark in [false, true] {128 for node in s.editor.document().lines.compactMap(\.atomNode) {129 guard let view = b.env.blockDetails.detail(for: node, context: context) else { continue }130 let shot = renderOffscreen(view.environment(b.env).environment(w).preferredColorScheme(dark ? .dark : .light), size: CGSize(width: 820, height: 640), dark: dark, name: "sheet-" + node.type)131 XCTAssertGreaterThan(shot.distinctColors, 6, "\(node.type) draws its sheet")132 }133 let ink = InkDocument(width: 640, height: 360, strokes: [InkStroke(tool: .pen, color: InkColor(red: UInt8(47), green: 93, blue: 219), width: 3, points: (0...50).map { InkPoint(x: 40 + Double($0) * 11, y: 180 + 90 * sin(Double($0) / 5)) })])134 let editor = InkEditorView(document: ink, onCancel: {}, onSave: { _, _ in }).frame(width: 820, height: 600)135 XCTAssertGreaterThan(renderOffscreen(editor.preferredColorScheme(dark ? .dark : .light), size: CGSize(width: 820, height: 600), dark: dark, name: "sheet-ink-editor").distinctColors, 6)136 }137 }138}139