importCottonKitimportFoundationimport XCTest@testable importCottonUI/// A library's Export library (export-open-swift, 7 Nov 2026): the tool's act/// answers `export_open`; the core lays the open bundle into a fresh folder/// under the temporary directory (`package.exportOpen`), the phone zips it as/// `Cotton <Kit> <date>.zip`, hands the zip to the share sheet, says what was/// written once the sheet closes, and removes the folder and the zip.@MainActorfinalclassLibraryExportTests: XCTestCase {/// A core that lays a synthetic bundle into the folder asked, as/// `package.exportOpen` does, and answers how much it wrote.private actor LayingCore: CottonCalling {let missing: [String]private(set) var asked: [String] = []init(missing: [String]) { self.missing = missing }func callRaw(_ method: String, requestJSON: String) throws -> String {structSent: Decodable {structArgs: Decodable { let kit: String; let dir: String; let media: Bool }let args: Args } asked.append(method)let sent = try JSONDecoder().decode(Sent.self, from: Data(requestJSON.utf8)).argslet shelf = URL(fileURLWithPath: sent.dir).appendingPathComponent("Synthetic Author/Synthetic Book", isDirectory: true)tryFileManager.default.createDirectory(at: shelf, withIntermediateDirectories: true)tryData("<package/>".utf8).write(to: shelf.appendingPathComponent("metadata.opf"))tryData("<feed/>".utf8).write(to: URL(fileURLWithPath: sent.dir).appendingPathComponent("catalog.xml"))let keys = String(data: try JSONEncoder().encode(missing), encoding: .utf8)!let dir = String(data: try JSONEncoder().encode(sent.dir), encoding: .utf8)!return #"{"ok":true,"data":{"dir":\#(dir),"files":2,"missingMedia":\#(keys),"kit":"\#(sent.kit)","exportedAt":"2026-11-07T10:00:00Z"}}"# }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}func close() {} }/// The share sheet, held: what it was handed, and whether the zip was/// there and a zip while it stood. @MainActorprivatefinalclassHeldSheet: FileSharing {var shared: [(title: String, url: URL, zip: Bool)] = []func share(title: String, url: URL) async {let head = (try? Data(contentsOf: url))?.prefix(2) shared.append((title, url, head == Data("PK".utf8))) } }privatefunc temporary() throws -> URL {let dir = FileManager.default.temporaryDirectory.appendingPathComponent("library-export-tests-\(UUID().uuidString)", isDirectory: true)tryFileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) addTeardownBlock { try? FileManager.default.removeItem(at: dir) }return dir }privatestaticlet day = Date(timeIntervalSince1970: 1_793_000_000)/// RULE: Export library lays the bundle under the temporary directory, shares it zipped as `Cotton <Kit> <date>.zip`, says the files written once the sheet closes, and leaves nothing behind.func testTheBundleIsZippedSharedSaidAndRemoved() asyncthrows {let dir = try temporary()let sheet = HeldSheet()let core = LayingCore(missing: [])var told: [String] = []var said: [String] = []let export = LibraryExport(sharing: sheet, temporary: dir, now: { Self.day }) export.attach(core: core, say: { said.append($0) }, tell: { told.append($0) })await export.export(kit: "films", name: "Cinemas")let asked = await core.asked XCTAssertEqual(asked, [CottonMethod.packageExportOpen])let title = LibraryExport.title(name: "Cinemas", on: Self.day) XCTAssertEqual(title, ShellLines.line("databases", "export_open.name", ["kit": "Cinemas", "date": Self.day.formatted(Date.ISO8601FormatStyle(timeZone: .current).year().month().day())])) XCTAssertTrue(title.contains("Cinemas"), title) XCTAssertEqual(sheet.shared.map(\.title), [title]) XCTAssertEqual(sheet.shared.first?.url.lastPathComponent, "\(title).zip") XCTAssertEqual(sheet.shared.first?.zip, true, "the share sheet is handed a zip") XCTAssertEqual(told, [ShellLines.line("databases", "export_open.written", ["n": "2"])]) XCTAssertEqual(said, []) XCTAssertEqual(tryFileManager.default.contentsOfDirectory(atPath: dir.path), [], "the folder and the zip go once the sheet closes") }/// RULE: where some of the library's files are not on this phone, the receipt says how many, in the lines' words.func testTheMissingMediaLineIsChosenWhenFilesAreNotHere() throws {let decode = { (json: String) intry JSONDecoder().decode(OpenBundleExported.self, from: Data(json.utf8)) }let whole = try decode(#"{"dir":"/tmp/x","files":12,"missingMedia":[],"kit":"books","exportedAt":"2026-11-07T10:00:00Z"}"#)let short = try decode(#"{"dir":"/tmp/x","files":12,"missingMedia":["db/books/a.epub","db/books/b.pdf","db/books/c.epub"],"kit":"books","exportedAt":"2026-11-07T10:00:00Z"}"#) XCTAssertEqual(LibraryExport.receipt(whole), ShellLines.line("databases", "export_open.written", ["n": "12"])) XCTAssertEqual(LibraryExport.receipt(short), ShellLines.line("databases", "export_open.written_missing", ["n": "12", "missing": "3"])) XCTAssertNotEqual(LibraryExport.receipt(whole), LibraryExport.receipt(short)) XCTAssertTrue(LibraryExport.receipt(short).contains("3"), LibraryExport.receipt(short)) }/// RULE: a refusal says the core's own sentence, and nothing is shared or left behind.func testARefusalSaysTheCoresSentence() asyncthrows {let dir = try temporary()let sheet = HeldSheet()let core = ScriptedCore([CottonMethod.packageExportOpen: .refuse(code: "export_refused", message: "The library could not be read on this phone.")])var said: [String] = []var told: [String] = []let export = LibraryExport(sharing: sheet, temporary: dir, now: { Self.day }) export.attach(core: core, say: { said.append($0) }, tell: { told.append($0) })await export.export(kit: "books", name: "Books") XCTAssertEqual(said, ["The library could not be read on this phone."]) XCTAssertEqual(told, []) XCTAssertTrue(sheet.shared.isEmpty) XCTAssertEqual(tryFileManager.default.contentsOfDirectory(atPath: dir.path), []) }/// RULE: the act's answer is the platform's `export_open`, naming the bundle's kit and the tool.func testTheActsAnswerDecodesAsExportOpen() throws {let answer = try JSONDecoder().decode(ToolActAnswer.self, from: Data(#"{"platform_action":"export_open","kit":"films","name":"Films"}"#.utf8)) XCTAssertEqual(answer.platform, .exportOpen(kit: "films", name: "Films")) }}