SPB Git

Repository Public

ODSTests.swift 23.5 KB 315 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetIO/Tests/SheetIOTests/ODSTests.swift10// Module           : SheetIOTests11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import Testing89import SheetCore90@testable import SheetIO9192/// A workbook limited to what the ODS writer stores.93func makeODSWorkbook() -> Workbook {94    let wb = Workbook()95    let s = wb.addSheet(named: "Feuille 1")96    let t = wb.addSheet(named: "Second")97    let h = wb.addSheet(named: "Hidden")98    h.meta.isHidden = true99    setCell(h, "A1", .text("hidden"))100    var bold = CellStyle(); bold.bold = true; bold.italic = true; bold.fill = RGBA(hex: 0xFFE699); bold.textColor = RGBA(hex: 0xC00000); bold.hAlign = .center; bold.vAlign = .center101    bold.fontName = "Arial"; bold.fontSize = 14; bold.underline = .single; bold.strikethrough = true; bold.wrap = true102    bold.borders = Borders(left: BorderEdge(style: .thin), right: BorderEdge(style: .medium, color: RGBA(hex: 0xFF0000)), top: BorderEdge(style: .double, color: RGBA(hex: 0x00FF00)), bottom: BorderEdge(style: .dashed, color: RGBA(hex: 0x0000FF)))103    let boldID = wb.styles.intern(bold)104    func fmt(_ code: String) -> Int32 { var st = CellStyle(); st.numberFormat = code; return wb.styles.intern(st) }105    let money = fmt("#,##0.00"), pct = fmt("0.0%"), date = fmt("yyyy-mm-dd"), dateTime = fmt("dd/mm/yyyy hh:mm:ss"), time = fmt("hh:mm:ss"), sci = fmt("0.00E+00"), text = fmt("@"), int = fmt("0")106    for (c, v) in ["Label", "Number", "Formula"].enumerated() { s.cells.set(row: 0, col: c, Cell(value: .text(v), style: boldID)) }107    setCell(s, "A2", .text("plain")); setCell(s, "B2", .number(1234.5678), style: money); setFormula(s, "C2", "B2*2", cached: .number(2469.1356), style: money)108    setCell(s, "A3", .text("  two  spaces  inside  ")); setCell(s, "B3", .number(0.256), style: pct); setFormula(s, "C3", "SUM(B2:B3)", cached: .number(1234.8238))109    setCell(s, "A4", .text("multi\nline\ttab")); setCell(s, "B4", .number(45351), style: date); setFormula(s, "C4", "IF(B2>1000,\"big\",\"small\")", cached: .text("big"))110    setCell(s, "A5", .text("<&> \"q\" é 日本 😀")); setCell(s, "B5", .number(45351.5625), style: dateTime); setFormula(s, "C5", "Second!A1+$B$2", cached: .number(1244.5678))111    setCell(s, "A6", .bool(true)); setCell(s, "B6", .number(0.75), style: time); setFormula(s, "C6", "B2>B3", cached: .bool(true))112    setCell(s, "A7", .error(.na)); setCell(s, "B7", .number(12345.678), style: sci); setFormula(s, "C7", "1/0", cached: .error(.div0))113    setCell(s, "A8", .number(-0.5)); setCell(s, "B8", .number(42), style: text); setFormula(s, "C8", "SUM(B:B)+SUM($2:$3)", cached: .number(1))114    setCell(s, "A9", .number(1e-7)); setCell(s, "B9", .number(7), style: int); setFormula(s, "C9", "XLOOKUP(\"plain\",A2:A5,B2:B5)&\"\"", cached: .text("1234.5678"))115    setFormula(s, "C10", "{1,2;3,4}", cached: .number(1), spill: "C10:D11")116    for (r, c, v) in [(9, 3, 2.0), (10, 2, 3.0), (10, 3, 4.0)] { s.cells.set(row: r, col: c, Cell(value: .number(v), isSpill: true)) }117    setFormula(s, "C12", "SUM(Table1[Amount])", cached: .number(99))               // not expressible in OpenFormula118    s.cells.set(row: 13, col: 0, Cell(style: boldID))119    s.meta.colWidths = [0: 150, 1: 90.5, 4: 20]120    s.meta.rowHeights = [0: 30, 3: 48.25]121    s.meta.hiddenCols = [5]; s.meta.hiddenRows = [15]122    s.meta.merges = [RangeRef(a1: "E2:F4")!, RangeRef(a1: "A16:C16")!]123    setCell(s, "E2", .text("merged")); setCell(s, "A16", .text("wide"))124    s.meta.frozenRows = 1; s.meta.frozenCols = 1; s.meta.zoom = 1.2; s.meta.showGridlines = false125    s.meta.comments[CellRef(a1: "B2")!] = CellComment(author: "Simon", text: "first line\nsecond line")126    s.meta.comments[CellRef(a1: "H3")!] = CellComment(author: "", text: "on an empty cell")127    s.meta.hyperlinks[CellRef(a1: "A2")!] = Hyperlink(target: "https://example.com/?a=1&b=2")128    setCell(t, "A1", .number(10)); setCell(t, "B3", .text("far"))129    wb.setDefinedName(DefinedName(name: "Rate", formula: "0.15"))130    wb.setDefinedName(DefinedName(name: "Block", formula: "'Feuille 1'!$B$2:$B$5"))131    wb.properties.title = "ODS test"; wb.properties.author = "ORIX"; wb.properties.created = Date(timeIntervalSince1970: 1_700_000_000)132    wb.activeSheet = 1133    return wb134}135136@Suite(.serialized) struct ODSTests {137    @Test func openFormulaConversion() throws {138        let pairs: [(String, String)] = [139            ("of:=SUM([.A1:.B2];1)", "SUM(A1:B2,1)"), ("of:=[.A1]*[$Sheet2.$B$3]", "A1*Sheet2!$B$3"), ("of:=['My Sheet'.A1:.C3]", "'My Sheet'!A1:C3"),140            ("of:=IF([.A1]>0;\"a;b\";\"c\")", "IF(A1>0,\"a;b\",\"c\")"), ("of:={1;2|3;4}", "{1,2;3,4}"), ("of:=COM.MICROSOFT.XLOOKUP(1;[.A:.A];[.B:.B])", "XLOOKUP(1,A:A,B:B)"),141            ("of:=[$'It''s'.A1]", "'It''s'!A1"), ("of:=[.A1]&\"x \"\"q\"\"\"", "A1&\"x \"\"q\"\"\""), ("of:=[.#REF!]+1", "#REF!+1"), ("msoxl:=SUM(A1:A2)", "SUM(A1:A2)"),142        ]143        for (odf, ours) in pairs { #expect(OpenFormula.toCanonical(odf) == ours, "\(odf)") }144        for bad in ["of:=[.A1]~[.B1]", "of:=['file:///x.ods'#$S.A1]", "=[.A1]![.B1]", "nothing", "of:=[Sheet1.A1:Sheet2.B2]"] { #expect(OpenFormula.toCanonical(bad) == nil, "\(bad)") }145        let back: [(String, String)] = [146            ("SUM(A1:B2,1.5)", "of:=SUM([.A1:.B2];1.5)"), ("'My Sheet'!$A$1&\"x\"", "of:=[$'My Sheet'.$A$1]&\"x\""), ("IF(A1>=2,TRUE,FALSE)", "of:=IF([.A1]>=2;TRUE();FALSE())"),147            ("{1,2;3,4}", "of:={1;2|3;4}"), ("SUM(B:B)", "of:=SUM([.B$1:.B$1048576])"), ("SUM($2:3)", "of:=SUM([.$A$2:.$XFD3])"), ("XLOOKUP(1,A1:A3,B1:B3)", "of:=COM.MICROSOFT.XLOOKUP(1;[.A1:.A3];[.B1:.B3])"),148            ("-A1^2%", "of:=-[.A1]^2%"), ("STDEV.S(A1:A9)+Rate", "of:=COM.MICROSOFT.STDEV.S([.A1:.A9])+Rate"), ("PMT(0.05,10,,1)", "of:=PMT(0.05;10;;1)"),149        ]150        for (ours, odf) in back { #expect(OpenFormula.fromExpr(try FormulaParser.parse(ours)) == odf, "\(ours)") }151        for unsupported in ["Table1[Amount]", "A1#", "LAMBDA(x,x+1)(2)", "Sheet1!Name"] { #expect(OpenFormula.fromExpr(try FormulaParser.parse(unsupported)) == nil) }152        // whole columns and rows survive a round trip153        for f in ["SUM(B:B)", "SUM($2:$3)", "SUM(Second!A:C)", "A1+B2"] {154            let odf = try #require(OpenFormula.fromExpr(try FormulaParser.parse(f)))155            let canonical = try #require(OpenFormula.toCanonical(odf))156            #expect(OpenFormula.normalizeFullRanges(try FormulaParser.parse(canonical)).formulaText() == f)157        }158    }159160    @Test func roundTripThroughOurReader() throws {161        let dir = Scratch.dir("ods")162        defer { try? FileManager.default.removeItem(at: dir) }163        let wb = makeODSWorkbook()164        let url = dir.appendingPathComponent("t.ods")165        let issues = try WorkbookWriter.save(wb, to: url, format: .ods)166        #expect(issues.contains { $0.feature == "Formulas" && $0.severity == .loss && ($0.location ?? "").contains("C12") })167        #expect(FileFormat.detect(url: url) == .ods)168        #expect(try ZipArchive(url: url).entries.first?.name == "mimetype" && (try ZipArchive(url: url)).entries.first?.method == 0)169        let r = try WorkbookReader.load(url: url)170        let back = r.workbook171        // the formula OpenFormula cannot express comes back as its value172        #expect(cellFormula(back, 0, "C12") == nil && cellValue(back, 0, "C12") == .number(99))173        wb.sheets[0].cells.set(row: 11, col: 2, Cell(value: .number(99)))174        var o = WorkbookCompareOptions()175        o.properties = false176        let diff = WorkbookDiff.differences(wb, back, options: o)177        #expect(diff.isEmpty, "\(diff.joined(separator: "\n"))")178        #expect(back.properties.title == "ODS test" && back.properties.author == "ORIX" && back.properties.created == wb.properties.created)179        #expect(!r.issues.contains { $0.severity == .loss })180        // preflight lists what ODS cannot keep181        let full = makeFeatureWorkbook()182        let pre = WorkbookWriter.preflight(full, format: .ods)183        for feature in ["Conditional formatting", "Data validation", "Tables", "AutoFilter", "Page setup", "Outline"] { #expect(pre.contains { $0.feature == feature && $0.severity == .loss }, "\(feature)") }184    }185186    @Test func readsLibreOfficeDocument() throws {187        let r = try WorkbookReader.load(url: Scratch.fixture("features_lo.ods"))188        let wb = r.workbook189        #expect(wb.sheets.map(\.name) == ["Data", "Table", "Filter", "Hidden"])190        #expect(cellValue(wb, 0, "A1") == .text("Text") && cellValue(wb, 0, "B1") == .number(42) && cellValue(wb, 0, "C1") == .number(3.14159))191        #expect(cellValue(wb, 0, "D1") == .bool(true) && cellValue(wb, 0, "I1") == .error(.na) && cellValue(wb, 0, "H1") == .error(.div0))192        #expect(cellValue(wb, 0, "E1") == .number(DateSerial.serial(year: 2024, month: 2, day: 29)))193        #expect(abs((cellValue(wb, 0, "F1").numberValue ?? 0) - (45351 + (13 * 3600 + 30 * 60 + 15) / 86400.0)) < 1e-9)194        #expect(abs((cellValue(wb, 0, "G1").numberValue ?? 0) - 6.75 / 24) < 1e-12)195        #expect(NumberFormats.isDateTime(wbStyle(wb, 0, "E1").numberFormat) && NumberFormats.isDateTime(wbStyle(wb, 0, "F1").numberFormat) && NumberFormats.isDateTime(wbStyle(wb, 0, "G1").numberFormat))196        #expect(cellValue(wb, 0, "A2") == .text("Unicode: é ü 日本 😀") && cellValue(wb, 0, "E2") == .text("  leading and trailing  ") && cellValue(wb, 0, "F2") == .text("line1\nline2"))197        #expect(cellValue(wb, 0, "A3") == .text("plain bold tail"))198        #expect(cellFormula(wb, 0, "B5") == "A5*2" && cellFormula(wb, 0, "B6") == "SUM(A5:A7)" && cellFormula(wb, 0, "B7") == "IF(A7>2,\"big\",\"small\")")199        #expect(cellFormula(wb, 0, "C5") == "Table!B2+Rate" && cellFormula(wb, 0, "C6") == "XLOOKUP(2,A5:A7,B5:B7)" && cellFormula(wb, 0, "E5") == "$A$5+A$6+$A7")200        #expect(cellValue(wb, 0, "B6") == .number(6) && cellValue(wb, 0, "B7") == .text("big") && cellValue(wb, 0, "C5") == .number(200.15))201        #expect(wb.sheets[0].cell(4, 3)?.formula?.spill == RangeRef(a1: "D5:D7") && wb.sheets[0].cell(5, 3)?.isSpill == true && cellValue(wb, 0, "D7") == .number(30))202        let a9 = wbStyle(wb, 0, "A9")203        #expect(a9.fontName == "Arial" && a9.fontSize == 14 && a9.bold && a9.italic && a9.strikethrough && a9.underline == .double && a9.textColor == RGBA(hex: 0xFF0000))204        #expect(wbStyle(wb, 0, "B9").fill == RGBA(hex: 0x00B0F0))205        let d9 = wbStyle(wb, 0, "D9").borders206        #expect(d9.left?.style == .thin && d9.right?.color == RGBA(hex: 0x00FF00) && d9.top?.style == .double && d9.bottom?.style == .dotted)207        #expect(wbStyle(wb, 0, "E9").hAlign == .center && wbStyle(wb, 0, "E9").vAlign == .top && wbStyle(wb, 0, "E9").wrap && wbStyle(wb, 0, "E9").rotation == 45)208        #expect(wbStyle(wb, 0, "A10").numberFormat == "#,##0.00" && NumberFormats.kind(of: wbStyle(wb, 0, "B10").numberFormat) == .percent)209        #expect(NumberFormats.kind(of: wbStyle(wb, 0, "E10").numberFormat) == .scientific && wbStyle(wb, 0, "F10").numberFormat == "@")210        let m = wb.sheets[0].meta211        #expect(Set(m.merges) == [RangeRef(a1: "A12:C13")!, RangeRef(a1: "E12:E15")!])212        // LibreOffice converts character widths with its own font metrics (about 5.55 pt per character)213        #expect(abs((m.colWidths[0] ?? 0) - 30 * 5.55) < 3 && abs((m.colWidths[1] ?? 0) - 12.5 * 5.55) < 3 && m.hiddenCols.contains(9))214        #expect(abs((m.rowHeights[8] ?? 0) - 40) < 0.5 && m.hiddenRows.contains(19))215        #expect(m.comments[CellRef(a1: "A17")!]?.text == "Review this value\nsecond line" && m.comments[CellRef(a1: "A17")!]?.author == "Alice")216        #expect(m.hyperlinks[CellRef(a1: "A16")!]?.target == "https://example.org/page?a=1&b=2")217        #expect(wb.sheets[3].meta.isHidden && wb.sheets[1].meta.isProtected)218        #expect(wb.definedName("Rate")?.formula == "0.15" && wb.definedName("Amounts")?.formula == "Table!$B$2:$B$5")219        #expect(cellValue(wb, 1, "B6") == .number(1400) && cellFormula(wb, 1, "C2") == "Table!$B2*Rate")220        func has(_ feature: String) -> Bool { r.issues.contains { $0.feature == feature } }221        #expect(has("Data validation") && has("Conditional formatting") && has("Filters") && has("Functions"))222        // import → export → re-import is stable223        let dir = Scratch.dir("ods-reimport")224        defer { try? FileManager.default.removeItem(at: dir) }225        let out = dir.appendingPathComponent("again.ods")226        #expect(wbStyle(wb, 0, "D10").numberFormat == "[$€] #,##0.00;-[$€] #,##0.00")227        let saveIssues = try WorkbookWriter.save(wb, to: out, format: .ods)228        // the currency format has no conversion back to ODF: reported, and the cell is excluded from the comparison229        #expect(saveIssues.contains { $0.feature == "Number formats" && $0.detail.contains("€") })230        wb.sheets[0].cells.set(row: 9, col: 3, nil)231        var o = WorkbookCompareOptions()232        o.properties = false233        o.names = false                 // sheet-scoped names are not written to ODS234        let again = try WorkbookReader.load(url: out).workbook235        again.sheets[0].cells.set(row: 9, col: 3, nil)236        let diff = WorkbookDiff.differences(wb, again, options: o)237        #expect(diff.isEmpty, "\(diff.prefix(8).joined(separator: "\n"))")238    }239240    @Test(.enabled(if: Tools.hasLibreOffice)) func libreOfficeOpensOurDocuments() throws {241        let dir = Scratch.dir("lo-ods")242        defer { try? FileManager.default.removeItem(at: dir) }243        // 1. formulas without cached values are computed by LibreOffice and match our engine244        let expected = makeCalcWorkbook()245        CalcEngine(workbook: expected).recalculate()246        let calc = dir.appendingPathComponent("calc.ods")247        try WorkbookWriter.save(makeCalcWorkbook(), to: calc, format: .ods)248        // 2. the styled workbook249        let wb = makeODSWorkbook()250        let styled = dir.appendingPathComponent("styled.ods")251        try WorkbookWriter.save(wb, to: styled, format: .ods)252        let out = dir.appendingPathComponent("x")253        let converted = try Tools.libreOfficeConvert([calc, styled], to: "xlsx", outDir: out)254255        var o = WorkbookCompareOptions()256        o.styles = false; o.layout = false; o.features = false; o.properties = false; o.names = false; o.numberTolerance = 1e-9; o.spillState = false257        let diff = WorkbookDiff.differences(expected, try WorkbookReader.load(url: converted[0]).workbook, options: o)258        #expect(diff.isEmpty, "\(diff.joined(separator: "\n"))")259260        let lo = try WorkbookReader.load(url: converted[1]).workbook261        #expect(lo.sheets.map(\.name) == ["Feuille 1", "Second", "Hidden"] && lo.sheets[2].meta.isHidden)262        for ref in ["A2", "A3", "A4", "A5", "A6", "A8", "A9", "B2", "B3", "B4", "B5", "B6", "B7", "B9", "E2", "A16"] {263            #expect(WorkbookDiff.valuesEqual(cellValue(lo, 0, ref), cellValue(wb, 0, ref), tolerance: 1e-12), "\(ref): \(cellValue(lo, 0, ref)) vs \(cellValue(wb, 0, ref))")264        }265        for ref in ["C2", "C3", "C4", "C5", "C6", "C7"] { #expect(cellFormula(lo, 0, ref) == cellFormula(wb, 0, ref), "\(ref): \(String(describing: cellFormula(lo, 0, ref)))") }266        #expect(cellFormula(lo, 0, "C8")?.contains("SUM(") == true && cellFormula(lo, 0, "C9")?.hasPrefix("XLOOKUP(\"plain\",A2:A5,B2:B5)") == true)267        #expect(cellValue(lo, 0, "C2").numberValue.map { abs($0 - 2469.1356) < 1e-9 } == true && cellValue(lo, 0, "C4") == .text("big"))268        #expect(cellValue(lo, 0, "C9") == .text("1234.5678") || cellValue(lo, 0, "C9") == .text("1234,5678"))269        #expect(cellFormula(lo, 0, "C10") == "{1,2;3,4}" && cellValue(lo, 0, "D11") == .number(4))270        let a1 = wbStyle(lo, 0, "A1")271        #expect(a1.bold && a1.italic && a1.fill == RGBA(hex: 0xFFE699) && a1.textColor == RGBA(hex: 0xC00000) && a1.hAlign == .center && a1.vAlign == .center)272        #expect(a1.fontName == "Arial" && a1.fontSize == 14 && a1.strikethrough && a1.underline == .single && a1.wrap)273        #expect(a1.borders.right == BorderEdge(style: .medium, color: RGBA(hex: 0xFF0000)) && a1.borders.top?.style == .double && a1.borders.left?.style == .thin, "\(a1.borders)")274        #expect(wbStyle(lo, 0, "B2").numberFormat == "#,##0.00" && NumberFormats.kind(of: wbStyle(lo, 0, "B3").numberFormat) == .percent)275        #expect(NumberFormats.kind(of: wbStyle(lo, 0, "B4").numberFormat) == .date && NumberFormats.kind(of: wbStyle(lo, 0, "B5").numberFormat) == .dateTime)276        #expect(NumberFormats.kind(of: wbStyle(lo, 0, "B6").numberFormat) == .time && NumberFormats.kind(of: wbStyle(lo, 0, "B7").numberFormat) == .scientific)277        #expect(Set(lo.sheets[0].meta.merges) == Set(wb.sheets[0].meta.merges))278        // through LibreOffice's XLSX export widths shrink by its font metrics (112 twips per character instead of 105)279        #expect(abs((lo.sheets[0].meta.colWidths[0] ?? 0) / 150 - 0.9375) < 0.01 && abs((lo.sheets[0].meta.colWidths[1] ?? 0) / 90.5 - 0.9375) < 0.01 && abs((lo.sheets[0].meta.rowHeights[3] ?? 0) - 48.25) < 0.5)280        #expect(lo.sheets[0].meta.hiddenCols.contains(5) && lo.sheets[0].meta.hiddenRows.contains(15))281        // frozen panes are not checked here: a headless LibreOffice conversion ignores the view settings of ODS files282        #expect(lo.sheets[0].meta.comments[CellRef(a1: "B2")!]?.text == "first line\nsecond line")283        #expect(lo.sheets[0].meta.hyperlinks[CellRef(a1: "A2")!]?.target == "https://example.com/?a=1&b=2")284        #expect(lo.definedName("Rate")?.formula == "0.15" && lo.definedName("Block")?.formula == "'Feuille 1'!$B$2:$B$5")285        #expect(cellValue(lo, 1, "A1") == .number(10) && cellValue(lo, 1, "B3") == .text("far"))286    }287288    @Test func damagedAndForeignDocuments() throws {289        let dir = Scratch.dir("ods-bad")290        defer { try? FileManager.default.removeItem(at: dir) }291        let src = Scratch.fixture("features_lo.ods")292        func load(_ d: Data) throws -> LoadResult {293            let u = dir.appendingPathComponent("t.ods")294            try d.write(to: u)295            return try WorkbookReader.load(url: u, format: .ods)296        }297        let original = try Data(contentsOf: src)298        for cut in stride(from: 0, to: original.count, by: max(1, original.count / 40)) { #expect(throws: SheetIOError.self) { _ = try load(original.prefix(cut)) } }299        #expect(throws: SheetIOError.self) { _ = try load(try rebuildZip(src, replacing: ["content.xml": Data("<office:document-content><broken".utf8)])) }300        #expect(throws: SheetIOError.self) { _ = try load(try rebuildZip(src, replacing: ["content.xml": Data?.none])) }301        do { _ = try load(try rebuildZip(src, replacing: ["mimetype": Data("application/vnd.oasis.opendocument.text".utf8)])); Issue.record("text document accepted") }302        catch let e as SheetIOError { guard case .unsupported = e else { Issue.record("\(e)"); return } }303        let manifest = "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\"><manifest:file-entry manifest:full-path=\"content.xml\"><manifest:encryption-data/></manifest:file-entry></manifest:manifest>"304        do { _ = try load(try rebuildZip(src, replacing: ["META-INF/manifest.xml": Data(manifest.utf8)])); Issue.record("encrypted accepted") }305        catch let e as SheetIOError { guard case .unsupported(let m) = e else { Issue.record("\(e)"); return }; #expect(m.contains("password")) }306        // gigantic repeat counts do not materialise cells307        let content = "<?xml version=\"1.0\"?><office:document-content xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"><office:body><office:spreadsheet><table:table table:name=\"S\"><table:table-row table:number-rows-repeated=\"1048576\"><table:table-cell table:number-columns-repeated=\"16384\"/></table:table-row></table:table><table:table table:name=\"Big\"><table:table-row table:number-rows-repeated=\"1000000\"><table:table-cell office:value-type=\"float\" office:value=\"1\" table:number-columns-repeated=\"16000\"/></table:table-row></table:table></office:body></office:document-content>"308        var o = LoadOptions(); o.maxCells = 1_000_000309        let big = dir.appendingPathComponent("big.ods")310        try rebuildZip(src, replacing: ["content.xml": Data(content.utf8)]).write(to: big)311        do { _ = try WorkbookReader.load(url: big, options: o); Issue.record("bomb accepted") }312        catch let e as SheetIOError { guard case .tooLarge = e else { Issue.record("\(e)"); return } }313    }314}315
Files main
Menu

Theme