SPB Git

Repository Public

AppIntegrationTests.swift 12.8 KB 236 lines swift

1import XCTest2import AppKit3import SheetCore4import SheetIO5import SheetUI6@testable import ORIXSheet78/// Tests hosted inside the running application: real documents, real windows, real grid view,9/// synthesized key and mouse events delivered to the grid.10@MainActor11final class AppIntegrationTests: XCTestCase {12    var tempDir: URL!1314    override func setUp() async throws {15        tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("orix-app-tests-\(UUID().uuidString)")16        try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)17    }18    override func tearDown() async throws {19        for d in NSDocumentController.shared.documents { d.close() }20        try? FileManager.default.removeItem(at: tempDir)21    }2223    private func newDocument() -> WorkbookDocument {24        let doc = WorkbookDocument()25        NSDocumentController.shared.addDocument(doc)26        doc.makeWindowControllers()27        doc.showWindows()28        RunLoop.current.run(until: Date().addingTimeInterval(0.4))29        return doc30    }3132    private func key(_ chars: String, code: UInt16, flags: NSEvent.ModifierFlags = [], window: NSWindow) -> NSEvent {33        NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber,34                         context: nil, characters: chars, charactersIgnoringModifiers: chars, isARepeat: false, keyCode: code)!35    }3637    private func type(_ text: String, into doc: WorkbookDocument, commit: MoveDirection? = .down) {38        // first character through the grid (starts editing), the rest through the session like the field editor does39        let grid = doc.session.gridView!40        grid.keyDown(with: key(String(text.prefix(1)), code: 0, window: doc.window!))41        XCTAssertTrue(doc.session.isEditing)42        doc.session.userEdited(text)43        XCTAssertTrue(doc.session.commitEdit(move: commit))44    }4546    func testFeaturesAreRegistered() {47        let panes = Set(Workspace.shared.panes.map(\.id))48        for id in ["auditor", "dependencies", "formula", "rules", "validation", "table", "statistics", "finance", "whatif", "chart", "chart-view", "figure",49                   "python", "data", "transform", "pivot", "assistant"] {50            XCTAssertTrue(panes.contains(id), "missing pane \(id)")51        }52        XCTAssertNotNil(Workspace.shared.objectRenderers["chart"])53        XCTAssertNotNil(Workspace.shared.objectRenderers["pivot"])54        XCTAssertNotNil(Workspace.shared.effectsProvider)55        XCTAssertNotNil(Workspace.shared.validator)56        XCTAssertGreaterThan(FunctionRegistry.standard.count, 400)57    }5859    func testTypingFormulasInTheGridAndUndo() throws {60        let doc = newDocument()61        let s = doc.session62        XCTAssertNotNil(s.gridView, "the grid view should exist once the window is shown")63        s.select(cell: CellRef(0, 0))64        type("12", into: doc)65        type("30", into: doc)66        XCTAssertEqual(s.selection.active, CellRef(2, 0))67        type("=SUM(A1:A2)*2", into: doc)68        XCTAssertEqual(s.sheet.value(2, 0), .number(84))69        // arrow keys move, ⌘Z through the document's undo manager restores70        let grid = s.gridView!71        grid.keyDown(with: key("\u{F700}", code: 126, window: doc.window!))72        XCTAssertEqual(s.selection.active, CellRef(2, 0))73        doc.undoManager?.undo()74        XCTAssertEqual(s.sheet.value(2, 0), .blank)75        doc.undoManager?.redo()76        XCTAssertEqual(s.sheet.value(2, 0), .number(84))77        RunLoop.current.run(until: Date().addingTimeInterval(0.2))      // the undo group closes at the end of the event78        XCTAssertTrue(doc.isDocumentEdited)79        // an invalid formula keeps the editor open with an error80        s.select(cell: CellRef(5, 5))81        grid.keyDown(with: key("=", code: 24, window: doc.window!))82        s.userEdited("=SUM(")83        XCTAssertFalse(s.commitEdit(move: nil))84        XCTAssertNotNil(s.editError)85        s.cancelEdit()86    }8788    func testMouseSelectionAndRedraw() throws {89        let doc = newDocument()90        let grid = doc.session.gridView!91        grid.display()92        XCTAssertGreaterThan(grid.drawCount, 0)93        XCTAssertLessThan(grid.lastDrawDuration, 0.1)94        // click the cell C4 (third column, fourth row) using the grid's own geometry95        let target = CGPoint(x: grid.xFor(col: 2) + 10, y: grid.yFor(row: 3) + 6)96        let inWindow = grid.convert(target, to: nil)97        func mouse(_ type: NSEvent.EventType, _ p: CGPoint) -> NSEvent {98            NSEvent.mouseEvent(with: type, location: p, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: doc.window!.windowNumber,99                               context: nil, eventNumber: 0, clickCount: 1, pressure: 1)!100        }101        grid.mouseDown(with: mouse(.leftMouseDown, inWindow))102        let drag = grid.convert(CGPoint(x: grid.xFor(col: 4) + 10, y: grid.yFor(row: 6) + 6), to: nil)103        grid.mouseDragged(with: mouse(.leftMouseDragged, drag))104        grid.mouseUp(with: mouse(.leftMouseUp, drag))105        XCTAssertEqual(doc.session.selection.primary, RangeRef(a1: "C4:E7"))106        XCTAssertEqual(doc.session.selection.active, CellRef(a1: "C4"))107    }108109    func testNativeSaveReopenIsLossless() throws {110        let doc = newDocument()111        let s = doc.session112        s.perform("fill") { e in113            for r in 0..<50 {114                e.set(sheet: 0, row: r, col: 0, .value(.number(Double(r) * 1.5)))115                e.setFormula(sheet: 0, row: r, col: 1, "=A\(r + 1)^2")116                e.set(sheet: 0, row: r, col: 2, .value(.text("row \(r)")))117            }118            e.setStyle(sheet: 0, range: RangeRef(a1: "A1:A50")!) { $0.numberFormat = "#,##0.00"; $0.bold = true }119            e.merge(sheet: 0, range: RangeRef(a1: "E1:F2")!)120            e.editMeta(sheet: 0) { $0.frozenRows = 1; $0.colWidths[2] = 140; $0.comments[CellRef(1, 1)] = CellComment(author: "test", text: "note") }121            _ = e.addSheet(named: "Second")122            e.setFormula(sheet: 1, row: 0, col: 0, "=SUM(Sheet1!B:B)")123        }124        let url = tempDir.appendingPathComponent("roundtrip.orixsheet")125        try doc.write(to: url, ofType: WorkbookDocument.nativeType)126        XCTAssertTrue(try NativeFormat.verify(url: url).isEmpty, "integrity check of the saved package")127128        let reopened = WorkbookDocument()129        try reopened.read(from: url, ofType: WorkbookDocument.nativeType)130        let w = reopened.session.workbook131        XCTAssertEqual(w.sheets.count, 2)132        XCTAssertEqual(w.sheets[0].value(49, 1), .number(pow(49 * 1.5, 2)))133        XCTAssertEqual(w.sheets[0].value(10, 2), .text("row 10"))134        XCTAssertEqual(w.styles[w.sheets[0].styleID(3, 0)].numberFormat, "#,##0.00")135        XCTAssertEqual(w.sheets[0].meta.merges, [RangeRef(a1: "E1:F2")!])136        XCTAssertEqual(w.sheets[0].meta.frozenRows, 1)137        XCTAssertEqual(w.sheets[0].meta.comments[CellRef(1, 1)]?.text, "note")138        XCTAssertEqual(reopened.session.engine.inputText(sheet: 1, row: 0, col: 0), "=SUM(Sheet1!B:B)")139        XCTAssertEqual(WorkbookDiff.differences(s.workbook, w).count, 0)140        // the reopened workbook stays live141        reopened.session.perform("edit") { $0.set(sheet: 0, row: 0, col: 0, .value(.number(100))) }142        XCTAssertEqual(w.sheets[0].value(0, 1), .number(10_000))143    }144145    func testForeignFilesAreImportedAsUntitledAndExportIsPreflighted() throws {146        // write an XLSX with the app's own writer, open it through the document layer147        let wb = Workbook(sheetNames: ["Data"])148        let e = CalcEngine(workbook: wb)149        e.set(sheet: 0, "A1", .value(.number(2))); e.setFormula(sheet: 0, row: 1, col: 0, "=A1*21"); e.recalculate()150        let xlsx = tempDir.appendingPathComponent("in.xlsx")151        _ = try WorkbookWriter.save(wb, to: xlsx, format: .xlsx)152        let before = try Data(contentsOf: xlsx)153154        let doc = WorkbookDocument()155        try doc.read(from: xlsx, ofType: "org.openxmlformats.spreadsheetml.sheet")156        NSDocumentController.shared.addDocument(doc)157        doc.fileURL = xlsx158        doc.makeWindowControllers()159        XCTAssertNil(doc.fileURL, "an imported file must not be saved over in place")160        XCTAssertEqual(doc.fileType, WorkbookDocument.nativeType)161        XCTAssertEqual(doc.session.workbook.sheets[0].value(1, 0), .number(42))162        XCTAssertEqual(try Data(contentsOf: xlsx), before, "the original file is untouched")163164        // an embedded object cannot be stored in XLSX: the preflight must say so before anything is written165        doc.session.addObject(SheetObject(kind: "chart", name: "Chart 1", x: 10, y: 10, width: 300, height: 200, payload: Data("{}".utf8)))166        let issues = WorkbookWriter.preflight(doc.session.workbook, format: .xlsx, preserved: nil)167        XCTAssertTrue(issues.contains { $0.severity == .loss }, "exporting a workbook with native-only content must be reported as a loss")168        XCTAssertTrue(WorkbookWriter.preflight(doc.session.workbook, format: .orixsheet, preserved: nil).allSatisfy { $0.severity != .loss })169    }170171    func testCorruptedAndUnsupportedFilesFailCleanly() throws {172        let bad = tempDir.appendingPathComponent("broken.xlsx")173        try Data("PK\u{03}\u{04} this is not a real archive".utf8).write(to: bad)174        XCTAssertThrowsError(try WorkbookDocument().read(from: bad, ofType: "org.openxmlformats.spreadsheetml.sheet"))175        let empty = tempDir.appendingPathComponent("empty.orixsheet")176        try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)177        XCTAssertThrowsError(try WorkbookDocument().read(from: empty, ofType: WorkbookDocument.nativeType))178    }179180    func testPrintingProducesPaginatedVectorPDF() throws {181        let doc = newDocument()182        doc.session.perform("fill") { e in for r in 0..<150 { for c in 0..<6 { e.set(sheet: 0, row: r, col: c, .value(.number(Double(r * c)))) } } }183        let pages = PrintRenderer.pageCount(session: doc.session)184        XCTAssertEqual(pages, 5)       // 150 rows × 20 pt over a 684 pt printable height (Letter, default margins)185        let pdf = PrintRenderer.pdfData(session: doc.session, fileName: "t")186        let document = try XCTUnwrap(CGPDFDocument(CGDataProvider(data: pdf as CFData)!))187        XCTAssertEqual(document.numberOfPages, pages)188        XCTAssertTrue(String(decoding: pdf, as: UTF8.self).contains("/Font"), "text must stay text in the PDF")189        let op = try doc.printOperation(withSettings: [:])190        XCTAssertTrue(op.view is SheetPrintView)191    }192193    func testMenuBarHasNoDuplicateShortcuts() {194        var seen: [String: String] = [:]195        var duplicates: [String] = []196        func walk(_ menu: NSMenu, path: String) {197            for item in menu.items {198                if !item.keyEquivalent.isEmpty {199                    let k = "\(item.keyEquivalentModifierMask.rawValue)|\(item.keyEquivalent)"200                    if let other = seen[k] { duplicates.append("\(path)/\(item.title) = \(other)") }201                    seen[k] = "\(path)/\(item.title)"202                }203                if let sub = item.submenu { walk(sub, path: path + "/" + item.title) }204            }205        }206        walk(NSApp.mainMenu!, path: "")207        XCTAssertTrue(duplicates.isEmpty, "duplicate key equivalents: \(duplicates)")208    }209210    func testLargeSheetStaysResponsive() throws {211        let doc = newDocument()212        let s = doc.session213        let wb = s.workbook214        // fill 200 000 cells directly, then let the session recalculate in the background215        for r in 0..<50_000 {216            wb.sheets[0].cells.set(row: r, col: 0, Cell(value: .number(Double(r))))217            wb.sheets[0].cells.set(row: r, col: 1, Cell(value: .number(Double(r % 97))))218            wb.sheets[0].cells.set(row: r, col: 2, Cell(formula: Formula(expr: try FormulaParser.parse("A\(r + 1)*B\(r + 1)"))))219            wb.sheets[0].cells.set(row: r, col: 3, Cell(formula: Formula(expr: try FormulaParser.parse("IF(C\(r + 1)>1000,\"high\",\"low\")"))))220        }221        s.engine.rebuildGraph()222        s.runCalc()223        let deadline = Date().addingTimeInterval(20)224        while s.isCalculating, Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.02)) }225        XCTAssertFalse(s.isCalculating)226        XCTAssertEqual(wb.sheets[0].value(49_999, 2), .number(49_999 * Double(49_999 % 97)))227        // scrolling to the end and repainting stays within a frame budget (measured, generous bound for CI noise)228        let grid = s.gridView!229        s.select(cell: CellRef(49_999, 3)); grid.scrollToVisible(CellRef(49_999, 3))230        var worst = 0.0231        for _ in 0..<20 { grid.needsDisplay = true; grid.display(); worst = max(worst, grid.lastDrawDuration) }232        XCTAssertLessThan(worst, 0.05, "grid repaint took \(worst * 1000) ms")233        print("large sheet repaint worst case: \(String(format: "%.2f", worst * 1000)) ms")234    }235}236
Files main
Menu

Theme