SPB Git

Repository Public

NativeContainerTests.swift 26.5 KB 434 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocFormatsTests/NativeContainerTests.swift3// Description: The .orixdoc container: lossless round trip, manifest contents, corruption detection per entry, truncation,4//              wrong mimetype, missing manifest, future versions, recovery, unknown entries and the migration pipeline.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Testing9import Foundation10import DocModel11import DocContainer12@testable import DocFormats1314@Suite struct NativeContainerTests {15    /// Offset of the first byte of an entry's data inside a ZIP produced by ZipWriter (local header + name).16    private func dataRange(of name: String, in zip: Data) throws -> Range<Int> {17        let bytes = [UInt8](zip)18        let needle = Array(name.utf8)19        var p = 020        while p + 30 + needle.count <= bytes.count {21            if bytes[p] == 0x50, bytes[p + 1] == 0x4B, bytes[p + 2] == 0x03, bytes[p + 3] == 0x04 {22                let nameLen = Int(bytes[p + 26]) | Int(bytes[p + 27]) << 8, extraLen = Int(bytes[p + 28]) | Int(bytes[p + 29]) << 823                let csize = Int(bytes[p + 18]) | Int(bytes[p + 19]) << 8 | Int(bytes[p + 20]) << 16 | Int(bytes[p + 21]) << 2424                if nameLen == needle.count, Array(bytes[(p + 30)..<(p + 30 + nameLen)]) == needle {25                    let start = p + 30 + nameLen + extraLen26                    return start..<(start + csize)27                }28                p += 30 + nameLen + extraLen + csize29            } else { p += 1 }30        }31        throw FormatError.unreadable("entry \(name) not found in test archive")32    }3334    private func flipped(_ zip: Data, entry: String, at fraction: Double = 0.5) throws -> Data {35        let range = try dataRange(of: entry, in: zip)36        var copy = zip37        let offset = range.lowerBound + Int(Double(range.count - 1) * fraction)38        copy[offset] ^= 0x5539        return copy40    }4142    @Test func richDocumentRoundTripsLosslessly() throws {43        let doc = Fixture.rich()44        let data = try NativeContainer.write(doc)45        let result = try NativeContainer.read(data)46        #expect(result.document == doc)47        #expect(result.warnings.isEmpty)48        #expect(result.document.assets["img/1 é"]?.data == doc.assets["img/1 é"]?.data)49        #expect(result.document.preservedParts.keys.sorted() == ["/word/vbaProject.bin", "customXml/item1.xml", "odd:name?.bin"])50        #expect(result.document.meta.created == Fixture.date1)       // sub-millisecond dates survive51        #expect(NativeContainer.validate(data).isEmpty)52        // Every Block and Inline case really is in the fixture that was compared.53        var blockCases = Set<String>(), inlineCases = Set<String>()54        for block in result.document.body {55            switch block {56            case .paragraph(let p):57                blockCases.insert("paragraph")58                for r in p.runs {59                    guard let inline = r.inline else { continue }60                    switch inline {61                    case .image: inlineCases.insert("image")62                    case .shape: inlineCases.insert("shape")63                    case .equation: inlineCases.insert("equation")64                    case .note: inlineCases.insert("note")65                    case .citation: inlineCases.insert("citation")66                    case .crossRef: inlineCases.insert("crossRef")67                    case .field: inlineCases.insert("field")68                    case .bookmark: inlineCases.insert("bookmark")69                    }70                }71            case .table: blockCases.insert("table")72            case .pageBreak: blockCases.insert("pageBreak")73            case .sectionBreak: blockCases.insert("sectionBreak")74            case .toc: blockCases.insert("toc")75            case .bibliography: blockCases.insert("bibliography")76            }77        }78        #expect(blockCases.count == 6)79        #expect(inlineCases.count == 8)80    }8182    @Test func containerLayoutAndManifest() throws {83        let doc = Fixture.rich()84        let created = Date(timeIntervalSinceReferenceDate: 800_000_000)85        let data = try NativeContainer.write(doc, generator: "Unit Test", created: created)86        let zip = try ZipReader(data: data)87        #expect(zip.names.first == "mimetype")88        #expect(zip.entries.first?.compressedSize == zip.entries.first?.uncompressedSize)      // stored89        #expect(try zip.data(for: "mimetype") == Data("application/vnd.orix.docs+zip".utf8))90        #expect(NativeContainer.mimeType == "application/vnd.orix.docs+zip")91        // The mimetype is readable at a fixed offset, like OpenDocument and EPUB.92        #expect(String(decoding: data[30..<38], as: UTF8.self) == "mimetype")93        #expect(String(decoding: data[38..<(38 + NativeContainer.mimeType.utf8.count)], as: UTF8.self) == NativeContainer.mimeType)9495        let manifest = try NativeJSON.decoder().decode(NativeManifest.self, from: try #require(try zip.data(for: "manifest.json")))96        #expect(manifest.containerVersion == 1)97        #expect(manifest.schemaVersion == DocumentModel.currentSchemaVersion)98        #expect(manifest.generator == .init(name: "Unit Test", version: NativeContainer.generatorVersion))99        #expect(manifest.created == created)100        // Every entry other than the manifest is listed with its size and SHA-256.101        #expect(Set(manifest.entries.map(\.name)) == Set(zip.names).subtracting(["manifest.json"]))102        for entry in manifest.entries {103            let content = try #require(try zip.data(for: entry.name))104            #expect(content.count == entry.size)105            #expect(NativeContainer.sha256(content) == entry.sha256)106            #expect(entry.sha256.count == 64)107        }108        let assets = manifest.entries.filter { $0.role == .asset }109        #expect(assets.map(\.key).sorted { ($0 ?? "") < ($1 ?? "") } == ["img/1 é", "photo"])110        #expect(assets.first { $0.key == "photo" }?.name == "assets/photo.jpg")111        #expect(assets.first { $0.key == "photo" }?.mimeType == "image/jpeg")112        #expect(assets.allSatisfy { $0.name.hasPrefix("assets/") && !$0.name.contains(" ") })113        let preserved = manifest.entries.filter { $0.role == .preserved }114        #expect(preserved.first { $0.key == "customXml/item1.xml" }?.name == "preserved/customXml/item1.xml")115        #expect(preserved.first { $0.key == "/word/vbaProject.bin" }?.name == "preserved/word/vbaProject.bin")116        #expect(preserved.contains { $0.key == "odd:name?.bin" && $0.name.hasPrefix("preserved/_part") })117118        // document.json: sorted keys, ISO-8601 dates, no assets and no preserved parts.119        let json = String(decoding: try #require(try zip.data(for: "document.json")), as: UTF8.self)120        #expect(json.hasPrefix("{\"bibliography\":"))121        #expect(json.range(of: #""created":"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{1,9}Z""#, options: .regularExpression) != nil)122        #expect(!json.contains("assets"))123        #expect(!json.contains("vbaProject"))124        let tree = try #require(try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])125        #expect(tree["schemaVersion"] as? Int == 1)126        #expect(((tree["meta"] as? [String: Any])?["created"] as? String)?.hasSuffix("Z") == true)127    }128129    @Test func writingIsDeterministicForTheSameInput() throws {130        let doc = Fixture.rich()131        let created = Date(timeIntervalSinceReferenceDate: 1)132        #expect(try NativeContainer.write(doc, generator: "G", created: created) == NativeContainer.write(doc, generator: "G", created: created))133    }134135    @Test func isoDatesAreExact() {136        for t in [0.0, 815_000_000.123456789, -31_622_400.75, 1e9 + 0.000001, 123.999999999, 5e8 + 1.0 / 3.0] {137            let date = Date(timeIntervalSinceReferenceDate: t)138            let s = NativeJSON.string(from: date)139            #expect(NativeJSON.date(from: s) == date, "\(s)")140            #expect(s.hasSuffix("Z") && s.contains("T"))141        }142        #expect(NativeJSON.string(from: Date(timeIntervalSinceReferenceDate: 0)) == "2001-01-01T00:00:00Z")143        #expect(NativeJSON.date(from: "2001-01-01T00:00:01Z") == Date(timeIntervalSinceReferenceDate: 1))144        #expect(NativeJSON.date(from: "2001-01-01T00:00:01.5Z") == Date(timeIntervalSinceReferenceDate: 1.5))145        #expect(NativeJSON.date(from: "yesterday") == nil)146    }147148    @Test(arguments: ["document.json", "manifest.json", "mimetype", "assets/photo.jpg", "preserved/customXml/item1.xml", "preserved/word/vbaProject.bin"])149    func byteFlipInAnyEntryIsDetected(entry: String) throws {150        let data = try NativeContainer.write(Fixture.rich())151        for fraction in [0.0, 0.5, 1.0] {152            let damaged = try flipped(data, entry: entry, at: fraction)153            #expect(damaged != data)154            #expect(throws: FormatError.self) { _ = try NativeContainer.read(damaged) }155            #expect(!NativeContainer.validate(damaged).isEmpty, "flip at \(fraction) of \(entry) not reported by validate")156            do {157                _ = try NativeContainer.read(damaged)158            } catch let error as FormatError {159                // A damaged mimetype is "not our format"; everything else is an integrity failure.160                if entry == "mimetype" { #expect(error == .unreadable("the file is not an ORIX Docs document (no mimetype marker)")) }161                else if case .integrityCheckFailed = error {} else { Issue.record("unexpected error \(error) for \(entry)") }162            }163        }164    }165166    @Test func checksumMismatchWithValidZipIsDetected() throws {167        // A well-formed ZIP whose asset was swapped for other bytes: CRC is right, only the SHA-256 of the manifest catches it.168        let doc = Fixture.rich()169        let json = try NativeJSON.encoder().encode(doc)170        let good = try NativeContainer.pack(documentJSON: json, schemaVersion: 1, assets: doc.assets, preserved: [:], generator: "T", created: Date())171        let zip = try ZipReader(data: good)172        var rebuilt = ZipWriter()173        for name in zip.names {174            var content = try #require(try zip.data(for: name))175            if name == "assets/photo.jpg" { content[content.count / 2] ^= 0xFF }176            try rebuilt.add(name, content, compress: name != "mimetype")177        }178        let tampered = rebuilt.finalize()179        #expect(throws: FormatError.integrityCheckFailed("assets/photo.jpg fails its SHA-256 checksum")) { _ = try NativeContainer.read(tampered) }180        #expect(NativeContainer.validate(tampered) == ["assets/photo.jpg fails its SHA-256 checksum"])181        // Recovery keeps the text and the sound asset, and says which image was skipped.182        let recovered = try NativeContainer.recover(tampered)183        #expect(recovered.document.body == doc.body)184        #expect(recovered.document.assets.keys.sorted() == ["img/1 é"])185        #expect(recovered.warnings.contains { $0.severity == .dropped && $0.feature == "Damaged images" && $0.detail.contains("assets/photo.jpg") })186        #expect(recovered.warnings.contains { $0.feature == "Missing images" })187    }188189    @Test func truncatedFileIsRejectedAndPartlyRecoverable() throws {190        let doc = Fixture.rich()191        let data = try NativeContainer.write(doc)192        for keep in [data.count - 1, data.count - 30, data.count / 2, 40, 3, 0] {193            let cut = data.prefix(keep)194            #expect(throws: FormatError.self) { _ = try NativeContainer.read(Data(cut)) }195            #expect(!NativeContainer.validate(Data(cut)).isEmpty)196        }197        do { _ = try NativeContainer.read(Data(data.prefix(data.count - 30))); Issue.record("should throw") } catch let e as FormatError {198            guard case .integrityCheckFailed = e else { Issue.record("truncation should be an integrity failure, got \(e)"); return }199        }200        // The central directory is gone but every local entry before the cut is intact.201        let cut = Data(data.prefix(data.count - 30))202        let recovered = try NativeContainer.recover(cut)203        #expect(recovered.document == doc)204        #expect(recovered.warnings.contains { $0.feature == "Damaged container" && $0.detail.contains("scanning") })205        // Cut in the middle of the assets: the text survives, the missing image is reported.206        let assetRange = try dataRange(of: "assets/photo.jpg", in: data)207        let partial = try NativeContainer.recover(Data(data.prefix(assetRange.lowerBound + 5)))208        #expect(partial.document.body == doc.body)209        #expect(partial.document.notes == doc.notes)210        #expect(partial.document.assets["photo"] == nil)211        #expect(partial.warnings.contains { $0.severity == .dropped && $0.feature == "Damaged images" })212        // Nothing left of document.json: recovery says so instead of inventing a document.213        #expect(throws: FormatError.self) { _ = try NativeContainer.recover(Data(data.prefix(60))) }214    }215216    @Test func recoverSkipsDamagedAssetsAndKeepsTheRest() throws {217        let doc = Fixture.rich()218        let data = try NativeContainer.write(doc)219        let damaged = try flipped(data, entry: "assets/photo.jpg")220        let recovered = try NativeContainer.recover(damaged)221        #expect(recovered.document.body == doc.body)222        #expect(recovered.document.comments == doc.comments)223        #expect(recovered.document.assets.keys.sorted() == ["img/1 é"])224        #expect(recovered.document.assets["img/1 é"] == doc.assets["img/1 é"])225        #expect(recovered.document.preservedParts == doc.preservedParts)226        #expect(recovered.warnings.contains { $0.severity == .dropped && $0.detail.contains("assets/photo.jpg") })227        // A sound file recovers to exactly the same document, without damage warnings.228        let clean = try NativeContainer.recover(data)229        #expect(clean.document == doc)230        #expect(clean.warnings.isEmpty)231    }232233    @Test func recoverWithoutManifest() throws {234        let doc = Fixture.rich()235        let data = try NativeContainer.write(doc)236        let damaged = try flipped(data, entry: "manifest.json")237        let recovered = try NativeContainer.recover(damaged)238        #expect(recovered.document.body == doc.body)239        #expect(recovered.warnings.contains { $0.detail.contains("manifest") })240        // Without the manifest asset ids come from the file names, so the id with unsafe characters cannot be matched again.241        #expect(recovered.document.assets["photo"]?.data == doc.assets["photo"]?.data)242        #expect(recovered.document.assets["photo"]?.mimeType == "image/jpeg")243    }244245    @Test func wrongMimetypeAndForeignZipAreRejected() throws {246        let json = try NativeJSON.encoder().encode(DocumentModel())247        var odt = ZipWriter()248        try odt.add("mimetype", text: "application/vnd.oasis.opendocument.text", compress: false)249        try odt.add("manifest.json", text: "{}")250        try odt.add("document.json", json)251        #expect(throws: FormatError.unreadable("the file is not an ORIX Docs document (unexpected mimetype)")) { _ = try NativeContainer.read(odt.finalize()) }252253        var noMime = ZipWriter()254        try noMime.add("document.json", json)255        try noMime.add("mimetype", text: NativeContainer.mimeType, compress: false)      // present, but not first256        #expect(throws: FormatError.unreadable("the file is not an ORIX Docs document (no mimetype marker)")) { _ = try NativeContainer.read(noMime.finalize()) }257258        #expect(throws: FormatError.self) { _ = try NativeContainer.read(Data("not a zip at all, just some text that is long enough".utf8)) }259        #expect(throws: FormatError.self) { _ = try NativeContainer.read(Data()) }260        #expect(NativeContainer.validate(Data("hello".utf8)).count == 1)261    }262263    @Test func missingManifestIsAnIntegrityFailure() throws {264        let json = try NativeJSON.encoder().encode(DocumentModel())265        var zip = ZipWriter()266        try zip.add("mimetype", text: NativeContainer.mimeType, compress: false)267        try zip.add("document.json", json)268        let data = zip.finalize()269        #expect(throws: FormatError.integrityCheckFailed("manifest.json is missing")) { _ = try NativeContainer.read(data) }270        #expect(NativeContainer.validate(data) == ["The document is damaged: manifest.json is missing"])271        // The document itself is fine, so recovery succeeds and reports the missing manifest.272        let recovered = try NativeContainer.recover(data)273        #expect(recovered.document.body.count == 1)274        #expect(recovered.warnings.contains { $0.detail.contains("manifest is missing") })275    }276277    @Test func manifestEntryMissingFromArchive() throws {278        let doc = Fixture.rich()279        let data = try NativeContainer.write(doc)280        let zip = try ZipReader(data: data)281        var rebuilt = ZipWriter()282        for name in zip.names where name != "assets/photo.jpg" { try rebuilt.add(name, try #require(try zip.data(for: name)), compress: name != "mimetype") }283        let stripped = rebuilt.finalize()284        #expect(throws: FormatError.integrityCheckFailed("assets/photo.jpg is listed in the manifest but missing")) { _ = try NativeContainer.read(stripped) }285        let recovered = try NativeContainer.recover(stripped)286        #expect(recovered.warnings.contains { $0.detail == "assets/photo.jpg is missing from the file." })287    }288289    @Test func futureVersionsAreRefused() throws {290        var doc = DocumentModel()291        doc.schemaVersion = DocumentModel.currentSchemaVersion + 1292        let future = try NativeContainer.write(doc)293        #expect(throws: FormatError.unsupportedVersion(2)) { _ = try NativeContainer.read(future) }294        #expect(throws: FormatError.unsupportedVersion(2)) { _ = try NativeContainer.recover(future) }295        #expect(NativeContainer.validate(future).first?.contains("newer version") == true)296297        // The manifest says 1 but document.json says 7: the document's own version wins.298        var tree = try #require(try JSONSerialization.jsonObject(with: try NativeJSON.encoder().encode(DocumentModel())) as? [String: Any])299        tree["schemaVersion"] = 7300        let lying = try NativeContainer.pack(documentJSON: try JSONSerialization.data(withJSONObject: tree), schemaVersion: 1, assets: [:], preserved: [:], generator: "T", created: Date())301        #expect(throws: FormatError.unsupportedVersion(7)) { _ = try NativeContainer.read(lying) }302303        // A newer container layout is refused as well.304        let zip = try ZipReader(data: try NativeContainer.write(DocumentModel()))305        var manifest = try NativeJSON.decoder().decode(NativeManifest.self, from: try #require(try zip.data(for: "manifest.json")))306        manifest.containerVersion = 9307        var rebuilt = ZipWriter()308        try rebuilt.add("mimetype", text: NativeContainer.mimeType, compress: false)309        try rebuilt.add("manifest.json", try NativeJSON.encoder().encode(manifest))310        try rebuilt.add("document.json", try #require(try zip.data(for: "document.json")))311        #expect(throws: FormatError.unsupportedVersion(9)) { _ = try NativeContainer.read(rebuilt.finalize()) }312    }313314    @Test func unknownExtraEntriesAreTolerated() throws {315        let doc = Fixture.rich()316        let json = try NativeJSON.encoder().encode(doc)317        let data = try NativeContainer.pack(documentJSON: json, schemaVersion: 1, assets: doc.assets, preserved: doc.preservedParts, generator: "T", created: Date(),318                                            extraEntries: [("thumbnail.png", Fixture.png()), ("META-INF/signatures.xml", Data("<sig/>".utf8)), ("assets/rogue.png", Fixture.png())])319        let result = try NativeContainer.read(data)320        #expect(result.document == doc)321        #expect(result.document.assets.count == 2)       // the unlisted asset is not loaded322        let warning = try #require(result.warnings.first)323        #expect(warning.severity == .info)324        #expect(warning.detail.contains("3 entries"))325        #expect(warning.detail.contains("thumbnail.png"))326        #expect(NativeContainer.validate(data).isEmpty)327    }328329    @Test func malformedDocumentJSON() throws {330        func container(_ json: String) throws -> Data {331            try NativeContainer.pack(documentJSON: Data(json.utf8), schemaVersion: 1, assets: [:], preserved: [:], generator: "T", created: Date())332        }333        #expect(throws: FormatError.integrityCheckFailed("document.json is not a JSON object")) { _ = try NativeContainer.read(try container("[1, 2")) }334        #expect(throws: FormatError.unreadable("document.json has no schema version")) { _ = try NativeContainer.read(try container("{\"meta\": {}}")) }335        #expect(throws: FormatError.unreadable("document.json has no schema version")) { _ = try NativeContainer.read(try container("{\"schemaVersion\": true}")) }336        do { _ = try NativeContainer.read(try container("{\"schemaVersion\": 1, \"meta\": 3}")); Issue.record("should throw") } catch let e as FormatError {337            guard case .unreadable(let why) = e else { Issue.record("\(e)"); return }338            #expect(why.contains("meta"))339        }340        #expect(!NativeContainer.validate(try container("{\"schemaVersion\": 1}")).isEmpty)341    }342343    @Test func oversizedInputIsRejectedBeforeParsing() {344        // The limit is checked on the byte count alone; no gigabyte buffer is needed to prove the comparison.345        #expect(FormatLimits.maxContainerBytes == 1 << 30)346        #expect(FormatError.from(.entryTooLarge(name: "x", size: 1)) == .tooLarge(ZipError.entryTooLarge(name: "x", size: 1).description))347        #expect(FormatError.from(.suspiciousCompressionRatio(name: "x")) == .tooLarge(ZipError.suspiciousCompressionRatio(name: "x").description))348        #expect(FormatError.from(.unsafeEntryName("../x")) == .integrityCheckFailed(ZipError.unsafeEntryName("../x").description))349    }350351    // MARK: Migration pipeline352353    /// Only schema 1 exists. These tests inject a migration table to prove the pipeline, with invented older layouts.354    private func legacyMigrator() -> SchemaMigrator {355        SchemaMigrator(steps: [356            // "version -1": the body lived under "blocks".357            -1: { tree in358                var t = tree359                t["body"] = t.removeValue(forKey: "blocks")360                return t361            },362            // "version 0": metadata lived under "metadata" and the title was called "name".363            0: { tree in364                var t = tree365                guard var meta = t.removeValue(forKey: "metadata") as? [String: Any] else { throw FormatError.unreadable("version 0 document without metadata") }366                meta["title"] = meta.removeValue(forKey: "name") ?? ""367                t["meta"] = meta368                return t369            },370        ], targetVersion: 1)371    }372373    private func legacyContainer(version: Int) throws -> (data: Data, doc: DocumentModel) {374        var doc = DocumentModel(meta: DocumentMetadata(title: "Old title", created: Fixture.date1, modified: Fixture.date1), body: [.paragraph(Paragraph(id: "p", runs: [Run("Legacy text")]))])375        doc.assets = ["a": Asset(id: "a", mimeType: "image/png", data: Fixture.png())]376        var tree = try #require(try JSONSerialization.jsonObject(with: try NativeJSON.encoder().encode(doc)) as? [String: Any])377        var meta = try #require(tree.removeValue(forKey: "meta") as? [String: Any])378        meta["name"] = meta.removeValue(forKey: "title")379        tree["metadata"] = meta380        if version < 0 { tree["blocks"] = tree.removeValue(forKey: "body") }381        tree["schemaVersion"] = version382        let json = try JSONSerialization.data(withJSONObject: tree)383        return (try NativeContainer.pack(documentJSON: json, schemaVersion: version, assets: doc.assets, preserved: [:], generator: "Old", created: Fixture.date1), doc)384    }385386    @Test func migrationsRunInSequenceBeforeDecoding() throws {387        for version in [0, -1] {388            let (data, original) = try legacyContainer(version: version)389            let result = try NativeContainer.read(data, migrator: legacyMigrator())390            #expect(result.document == original)391            #expect(result.document.schemaVersion == 1)392            #expect(result.document.meta.title == "Old title")393            #expect(result.warnings.contains { $0.severity == .info && $0.feature == "Document format upgraded" && $0.detail.contains("schema \(version)") })394            // recover() goes through the same pipeline.395            #expect(try NativeContainer.recover(data, migrator: legacyMigrator()).document == original)396        }397    }398399    @Test func standardMigratorHasNoStepAndRefusesUnknownOldVersions() throws {400        #expect(SchemaMigrator.standard.targetVersion == DocumentModel.currentSchemaVersion)401        #expect(SchemaMigrator.standard.steps.isEmpty)402        #expect(SchemaMigrator.standard.canRead(1))403        #expect(!SchemaMigrator.standard.canRead(0))404        #expect(!SchemaMigrator.standard.canRead(2))405        let (data, _) = try legacyContainer(version: 0)406        #expect(throws: FormatError.unreadable("no migration is available from document schema 0")) { _ = try NativeContainer.read(data) }407    }408409    @Test func migrationPipelineOnRawTrees() throws {410        let migrator = SchemaMigrator(steps: [411            1: { var t = $0; t["trail"] = (t["trail"] as? String ?? "") + "a"; return t },412            2: { var t = $0; t["trail"] = (t["trail"] as? String ?? "") + "b"; t["schemaVersion"] = 999; return t },      // the pipeline owns the version field413            3: { var t = $0; t["trail"] = (t["trail"] as? String ?? "") + "c"; return t },414        ], targetVersion: 4)415        let from1 = try migrator.migrate(["schemaVersion": 1])416        #expect(from1.json["trail"] as? String == "abc")417        #expect(from1.json["schemaVersion"] as? Int == 4)418        #expect(from1.applied == [1, 2, 3])419        let from3 = try migrator.migrate(["schemaVersion": 3, "trail": "x"])420        #expect(from3.json["trail"] as? String == "xc")421        #expect(from3.applied == [3])422        let current = try migrator.migrate(["schemaVersion": 4])423        #expect(current.applied.isEmpty)424        #expect(throws: FormatError.unsupportedVersion(5)) { _ = try migrator.migrate(["schemaVersion": 5]) }425        #expect(throws: FormatError.unreadable("no migration is available from document schema 0")) { _ = try migrator.migrate(["schemaVersion": 0]) }426        #expect(throws: FormatError.unreadable("document.json has no schema version")) { _ = try migrator.migrate(["schemaVersion": "1"]) }427        #expect(throws: FormatError.unreadable("document.json has no schema version")) { _ = try migrator.migrate(["schemaVersion": 1.5]) }428        // A failing step stops the pipeline with its own error.429        let failing = SchemaMigrator(steps: [1: { _ in throw FormatError.unreadable("step failed") }], targetVersion: 2)430        #expect(throws: FormatError.unreadable("step failed")) { _ = try failing.migrate(["schemaVersion": 1]) }431        #expect(migrator.canRead(1) && migrator.canRead(4) && !migrator.canRead(0) && !migrator.canRead(5))432    }433}434
Files main
Menu

Theme