Repository Public
1// SP Drive iOS2// File: KitTests/NextKitTests.swift3// Description: SP Drive 2.0 from the device's point of view, against the real 2.0 backend of the test bed: the event stream feeding the4// sync engine (and the fall back to polling when it dies), capability discovery, content search, tags, collections,5// activity, versions, storage, grants between two accounts, sessions, the bandwidth cap — and « ask » against the test6// bed's FAKE language model (no real model is exercised anywhere).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPDriveNext12import Testing13@testable import SPDriveKit1415@Suite struct TextDiffTests {16 @Test func lineDiffFindsWhatChanged() throws {17 let old = "titre\nligne A\nligne B\nligne C\nfin", new = "titre\nligne A\nligne B modifiée\nligne C\nnouvelle\nfin"18 let lines = try #require(TextDiff.lines(old: old, new: new))19 #expect(TextDiff.summary(lines) == .init(added: 2, removed: 1, unchanged: 4))20 #expect(lines.filter { $0.kind == .removed }.map(\.text) == ["ligne B"])21 #expect(lines.filter { $0.kind == .added }.map(\.text) == ["ligne B modifiée", "nouvelle"])22 #expect(lines.first { $0.text == "fin" }?.old == 5 && lines.first { $0.text == "fin" }?.new == 6)23 #expect(TextDiff.summary(try #require(TextDiff.lines(old: old, new: old))).added == 0)24 #expect(TextDiff.lines(old: "", new: "a\nb")?.filter { $0.kind == .added }.count == 2)25 #expect(TextDiff.lines(old: String(repeating: "x\n", count: 5000), new: "y") == nil) // too long: the caller falls back26 #expect(TextDiff.isText(extension: "MD") && !TextDiff.isText(extension: "pdf"))27 }28}2930@Suite(.enabled(if: TestEnv.next, "2.0 test bed not running: Scripts/test-server.sh up"), .serialized)31struct NextKitTests {32 func wait(_ timeout: TimeInterval = 30, _ what: String, _ condition: @Sendable () async -> Bool) async { #expect(await eventually(timeout, condition), "\(what)") }3334 @Test func serverAnnouncesItsFeaturesAndA1ServerIsDescribedAsSuch() async throws {35 let a = try await Device()36 let meta = try await a.api.next().capabilities()37 #expect(meta.api == 2)38 for f in [ServerMeta.Feature.events, .contentSearch, .collab, .collections, .activity, .storage] { #expect(meta.has(f), "\(f.rawValue)") }39 #expect(meta.has(.ai), "the test bed configures a fake provider")40 #expect(ServerMeta.v1.features.isEmpty && !ServerMeta.v1.has(.events))41 // the client identifies itself: the devices dashboard shows platform and version42 _ = try await a.api.rootID()43 let me = try #require(try await a.api.next().sessions().first { $0.current })44 #expect(me.client?.platform == "macos" || me.client?.platform == "ios" || me.client?.platform == "ipados")45 #expect(me.client?.version.isEmpty == false)46 }4748 @Test func eventStreamBringsAChangeWithoutWaitingForThePollAndADeadStreamFallsBackToPolling() async throws {49 let a = try await Device(), b = try await Device(host: "127.0.0.1")50 let ws = try await a.workspace("sse")51 await b.engine.sync()5253 // 1. live stream, polling far away (10 min): only an event can explain a prompt arrival54 let session = BasicNextTransport.defaultSession()55 let listener = ChangeListener(source: SSEChangeSource(client: b.api.next(session: session)), configuration: .init(pollInterval: .seconds(600), safetyInterval: .seconds(600), reconnectBase: 0.2, reconnectCap: 1)) { await b.engine.sync() }56 await listener.start()57 await wait(10, "the server says hello") { await listener.mode == .streaming }58 let started = Date.now59 _ = try await a.engine.createFolder(name: "Vu par évènement", in: ws.id)60 await a.settle()61 await wait(8, "the change reaches the other device's mirror through the stream") { b.child("Vu par évènement", of: ws.id) != nil }62 #expect(Date.now.timeIntervalSince(started) < 8)63 let hints = await listener.hintsReceived64 #expect(hints >= 2)6566 // 2. the stream dies and cannot come back (its session is gone): the listener polls, changes still arrive67 await listener.stop()68 let dead = ChangeListener(source: SSEChangeSource(client: NextClient(BasicNextTransport(baseURL: URL(string: "http://127.0.0.1:9")!, clientHeader: nil) { TestEnv.tokenA })),69 configuration: .init(pollInterval: .milliseconds(300), reconnectBase: 0.1, reconnectCap: 0.5)) { await b.engine.sync() }70 await dead.start()71 _ = try await a.engine.createFolder(name: "Vu par sondage", in: ws.id)72 await a.settle()73 await wait(8, "polling takes over") { b.child("Vu par sondage", of: ws.id) != nil }74 #expect(await dead.mode == .polling)75 #expect(await dead.connectAttempts >= 2, "it keeps trying to reconnect")76 await dead.stop()7778 // 3. a stream cut while it was live (the session is invalidated): polling again, without restarting anything79 let session2 = BasicNextTransport.defaultSession()80 let cut = ChangeListener(source: SSEChangeSource(client: b.api.next(session: session2)), configuration: .init(pollInterval: .milliseconds(300), safetyInterval: .seconds(600), reconnectBase: 5, reconnectCap: 5)) { await b.engine.sync() }81 await cut.start()82 await wait(10, "live again") { await cut.mode == .streaming }83 session2.invalidateAndCancel()84 await wait(10, "the cut is noticed") { await cut.mode == .polling }85 _ = try await a.engine.createFolder(name: "Après la coupure", in: ws.id)86 await a.settle()87 await wait(8, "polling after the cut") { b.child("Après la coupure", of: ws.id) != nil }88 await cut.stop()89 }9091 @Test func contentSearchTagsCollectionsActivityVersionsAndStorage() async throws {92 let a = try await Device()93 let next = a.api.next()94 let ws = try await a.workspace("next")95 let word = "zygomatique\(UUID().uuidString.prefix(6).lowercased())"96 _ = try await a.engine.importFile(at: a.tempFile("compte rendu.txt", Data("Réunion du lundi.\nLe mot rare est \(word), dans le texte seulement.".utf8)), into: ws.id)97 _ = try await a.engine.importFile(at: a.tempFile("autre.md", Data("# Rien à voir".utf8)), into: ws.id)98 await a.settle()99 let file = try #require(a.child("compte rendu.txt", of: ws.id))100101 // content search: found by a word that is not in the name, with a highlighted snippet102 await wait(40, "text indexed") { (try? await next.fileText(file.id).status) == "ready" }103 let hits = try await next.search(word, in: .all)104 let hit = try #require(hits.files.first { $0.id == file.id })105 #expect(hit.match?.where == "content")106 #expect(hit.match?.snippetRuns.contains { $0.matched && $0.text.lowercased() == word } == true)107 #expect(try await next.search(word, in: .name).files.isEmpty)108109 // tags (1.0 routes, used through the bridge)110 let tag = try await next.createTag(name: "Projet \(word.suffix(6))", color: "teal")111 try await next.setTags(of: file.id, to: [tag.id])112 #expect(try await next.tagIDs(of: file.id) == [tag.id])113 #expect(try await next.tags().first { $0.id == tag.id }?.files == 1)114115 // a smart collection: files of this folder carrying the tag; a preview before saving, then the saved one116 let rule = CollectionRule(match: "all", conditions: [.init(field: "tag", op: "is", value: .string(tag.id)), .init(field: "kind", op: "is", value: .string("text"))])117 #expect(try await next.previewCollection(rule).files.map(\.id) == [file.id])118 let collection = try await next.createCollection(.init(name: "Tests \(word.suffix(6))", icon: "tag", color: "teal", rule: rule))119 #expect(try await next.collectionItems(collection.id).files.map(\.id) == [file.id])120 #expect(try await next.collections().contains { $0.id == collection.id })121122 // versions: a second version, the list, a restore that keeps every version123 try await a.engine.replaceContent(of: file.id, with: a.tempFile("compte rendu.txt", Data("Version deux.".utf8)))124 await a.settle()125 var versions = try await next.versions(of: file.id)126 #expect(versions.versions.count == 2)127 let first = try #require(versions.versions.first { !$0.current })128 let scratch = a.root.appendingPathComponent("v1.txt")129 try await next.downloadVersion(fileID: file.id, versionID: first.id, to: scratch)130 #expect(try String(contentsOf: scratch, encoding: .utf8).contains(word))131 _ = try await next.restoreVersion(fileID: file.id, versionID: first.id)132 versions = try await next.versions(of: file.id)133 #expect(versions.versions.count == 3, "restoring adds a version, it removes none")134 #expect(versions.versions.first { $0.current }?.sha256 == first.sha256)135136 // activity: real audit events for the file and for the account137 let activity = try await next.fileActivity(file.id)138 #expect(activity.events.contains { $0.action.contains("restore") || $0.action.contains("version") }, "\(activity.events.map(\.action))")139 #expect(try await next.accountActivity(limit: 5).events.isEmpty == false)140141 // storage: totals, kinds, drill-down into the folder142 let storage = try await next.storageOverview()143 #expect(storage.quota.limit > 0 && storage.liveBytes > 0 && !storage.byKind.isEmpty)144 #expect(storage.duplicates.reclaimableBytes == 0)145 #expect(try await next.storageFolder(ws.id).total.files == 2)146 _ = try await next.duplicates(.exact)147148 try await next.deleteCollection(collection.id)149 try await next.deleteTag(tag.id)150 #expect(try await next.adminSystem().features.contains("events"), "account A is an administrator on the test bed")151 }152153 @Test func askAnswersFromRetrievedPassagesWithTheFakeModelAndSaysWhenNothingWasFound() async throws {154 let a = try await Device()155 let next = a.api.next()156 let providers = try await next.aiProviders()157 #expect(providers.enabled)158 let local = try #require(providers.providers.first { $0.id == "maclustr" })159 #expect(local.local && local.configured && local.usable != false)160 #expect(local.models.contains { $0.creator == "Alibaba" }, "the creator of a model is not the route to it")161 #expect(providers.providers.filter { !$0.local }.allSatisfy { $0.usable != true }, "external providers are off without the server switch and the account's consent")162163 let ws = try await a.workspace("ask")164 let word = "paléontologue\(UUID().uuidString.prefix(5).lowercased())"165 _ = try await a.engine.importFile(at: a.tempFile("note.txt", Data("Le \(word) arrive mardi à neuf heures.".utf8)), into: ws.id)166 await a.settle()167 let file = try #require(a.child("note.txt", of: ws.id))168 await wait(40, "text indexed") { (try? await next.fileText(file.id).status) == "ready" }169170 var sources: [AISource] = [], answer = "", done: AIDone?171 for try await e in next.aiAsk(.init(scope: .files([file.id]), question: "Quand arrive le \(word) ?")) {172 switch e { case .sources(let s): sources = s; case .delta(let t): answer += t; case .done(let d): done = d; default: break }173 }174 #expect(sources.first?.fileId == file.id && sources.first?.n == 1 && sources.first?.text.contains(word) == true)175 #expect(answer.contains("[1]") && answer.contains("factice"), "the test bed's endpoint is a fake, and says so: \(answer)")176 #expect(done?.provider == "maclustr" && done?.empty != true)177178 // nothing retrieved: no model call, a clear « empty »179 var empty: AIDone?, text = ""180 for try await e in next.aiAsk(.init(scope: .folder(ws.id), question: "xqzvwk inexistantissime")) {181 if case .done(let d) = e { empty = d }; if case .delta(let t) = e { text += t }182 }183 #expect(empty?.empty == true && text.isEmpty)184185 // suggestions are proposals: nothing is applied by the server186 let suggestions = try await next.aiSuggest(fileIDs: [file.id])187 #expect(suggestions.suggestions.first?.fileId == file.id)188 await a.engine.sync()189 #expect(a.store.item(file.id)?.name == "note.txt")190 }191192 @Test func grantsGiveExactlyTheirRoleToAnotherAccount() async throws {193 let owner = try await Device(), member = try await Device(token: TestEnv.tokenC, host: "127.0.0.1")194 let o = owner.api.next(), m = member.api.next()195 let ws = try await owner.workspace("partage")196 let read = try await owner.engine.createFolder(name: "Lecture", in: ws.id), drop = try await owner.engine.createFolder(name: "Dépôt", in: ws.id)197 await owner.settle()198 let readID = try #require(owner.child(read.name, of: ws.id)).id, dropID = try #require(owner.child(drop.name, of: ws.id)).id199 _ = try await owner.engine.importFile(at: owner.tempFile("visible.txt", Data("pour le lecteur".utf8)), into: readID)200 await owner.settle()201202 // exact e-mail only; an unknown address is a 404, not a hint203 #expect(try await o.resolveUser(email: TestEnv.emailC).displayName == "Test C")204 await #expect(throws: NextError.self) { _ = try await o.resolveUser(email: "personne-\(UUID().uuidString.prefix(6))@example.test") }205 let viewer = try await o.addMember(to: readID, email: TestEnv.emailC, as: .viewer, workspaceName: "Équipe test")206 _ = try await o.addMember(to: dropID, email: TestEnv.emailC, as: .uploader)207 #expect(try await o.members(of: readID).members.map(\.userId) == [viewer.userId])208209 let mine = try await m.sharedWithMe().filter { [readID, dropID].contains($0.folder.id) }210 #expect(mine.count == 2)211 let asViewer = try #require(mine.first { $0.role == .viewer }), asUploader = try #require(mine.first { $0.role == .uploader })212 #expect(asViewer.displayName == "Équipe test" && asViewer.owner.displayName == "Test A")213214 // viewer: lists and reads, cannot write (403: the grant is live, the role is too weak — D1)215 let listing = try await m.sharedChildren(grant: asViewer.grantId)216 let visible = try #require(listing.files.first)217 let copy = member.root.appendingPathComponent("visible.txt")218 try await m.downloadShared(grant: asViewer.grantId, fileID: visible.id, to: copy)219 #expect(try Data(contentsOf: copy) == Data("pour le lecteur".utf8))220 do { _ = try await m.sharedCreateFolder(grant: asViewer.grantId, name: "Interdit"); Issue.record("a viewer created a folder") } catch let e as NextError { #expect(e.isForbidden) }221222 // uploader: lists nothing, uploads; the file lands in the owner's folder223 do { _ = try await m.sharedChildren(grant: asUploader.grantId); Issue.record("an uploader listed the folder") } catch let e as NextError { #expect(e.isForbidden || e.isNotFound) }224 let payload = randomData(70_000)225 let dropped = try await m.uploadShared(grant: asUploader.grantId, file: member.tempFile("déposé.bin", payload))226 #expect(dropped.file.name == "déposé.bin", "an uploader is told the name it sent, nothing about the folder (D20)")227 // an uploader may only aim at the granted folder itself (D20)228 do { _ = try await m.sharedCreateUpload(grant: asUploader.grantId, folderID: readID, name: "ailleurs.bin", size: 10); Issue.record("an uploader aimed outside the grant root") } catch let e as NextError { #expect(e.isForbidden || e.isNotFound) }229 // an account identifier alone cannot be used to add a member (D18): the package refuses before any request230 do { _ = try await o.addMember(to: readID, userID: viewer.userId, role: .viewer); Issue.record("added by identifier") } catch let e as NextError { #expect(e.code == "invalid_request") }231 await owner.engine.sync()232 #expect(await eventually { await owner.engine.sync(); return owner.child("déposé.bin", of: dropID)?.sha256 == IntegrityVerifier.sha256(payload) })233 // the owner's own tree is untouched by the member's mirror: shared folders are browsed, not synced234 await member.engine.sync()235 #expect(member.store.item(readID) == nil)236237 // revoked: gone at once, with a 404238 try await o.removeMember(of: readID, userID: viewer.userId)239 do { _ = try await m.sharedChildren(grant: asViewer.grantId); Issue.record("a revoked grant still lists") } catch let e as NextError { #expect(e.isNotFound) }240 try await o.removeMember(of: dropID, userID: viewer.userId)241 }242243 @Test func bandwidthCapPacesUploadsAndDownloads() async throws {244 let a = try await Device(), b = try await Device(host: "127.0.0.1")245 let ws = try await a.workspace("cap")246 let data = randomData(600_000)247 await a.setPolicy { $0.bandwidthLimit = 200_000 } // 200 kB/s → about three seconds for 600 kB248 #expect(await a.engine.concurrencyState().effective == 1)249 var t0 = Date.now250 _ = try await a.engine.importFile(at: a.tempFile("lent.bin", data), into: ws.id)251 await a.settle()252 var took = Date.now.timeIntervalSince(t0)253 #expect(took >= 1.8 && took < 12, "upload took \(took) s")254 let up = try #require(a.child("lent.bin", of: ws.id))255 #expect(up.sha256 == IntegrityVerifier.sha256(data))256257 await b.engine.sync()258 await b.setPolicy { $0.bandwidthLimit = 200_000 }259 t0 = Date.now260 let url = try await b.engine.localCopy(of: up.id)261 took = Date.now.timeIntervalSince(t0)262 #expect(took >= 1.8 && took < 12, "download took \(took) s")263 #expect(try Data(contentsOf: url) == data)264265 // no cap: the same file travels at once266 let c = try await Device(host: "127.0.0.1")267 await c.engine.sync()268 t0 = Date.now269 _ = try await c.engine.localCopy(of: up.id)270 #expect(Date.now.timeIntervalSince(t0) < 1.5)271 }272}273