SPB Git

Repository Public MIT

WorkspaceTests.swift 9.3 KB 168 lines swift

1// ORIX Calc2// File: Packages/ORIXWorkspace/Tests/ORIXWorkspaceTests/WorkspaceTests.swift3// Description: Tests for reactive recalculation, dependency tracking, cycle detection, exports and the native file format.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10@testable import ORIXWorkspace1112func npvDocument() -> WorkspaceDocument {13    WorkspaceDocument(title: "Project NPV", cells: [14        .text("Capital budgeting example"),15        .formula("Investment = 100000", unit: "$"),16        .parameter("DiscountRate", value: 0.08, range: 0...0.3, step: 0.005),17        .formula("CashFlow1 = 25000", unit: "$"),18        .formula("CashFlow2 = 30000", unit: "$"),19        .formula("CashFlow3 = 40000", unit: "$"),20        .formula("NPV = -Investment + CashFlow1/(1+DiscountRate) + CashFlow2/(1+DiscountRate)^2 + CashFlow3/(1+DiscountRate)^3", unit: "$"),21        .formula("Unrelated = 2 + 2"),22        .formula("Decision = if(NPV > 0, 1, 0)"),23    ])24}25func value(_ e: WorkspaceEngine, _ name: String) -> Double? {26    e.document.cells.first { e.results[$0.id]?.definedName == name }.flatMap { e.results[$0.id]?.value?.doubleValue }27}28func cell(_ e: WorkspaceEngine, _ name: String) -> WorkspaceCell { e.document.cells.first { e.results[$0.id]?.definedName == name || $0.parameter?.name == name }! }2930@Suite struct Reactive {31    @Test func npvExample() throws {32        var e = WorkspaceEngine(document: npvDocument())33        // independent reference: −100000 + 25000/1.08 + 30000/1.08² + 40000/1.08³34        let reference = -100000 + 25000 / 1.08 + 30000 / pow(1.08, 2) + 40000 / pow(1.08, 3)35        #expect(abs(try #require(value(e, "NPV")) - reference) < 1e-9)36        #expect(value(e, "Decision") == 0)37        // the NPV is exact: only rational arithmetic was needed38        #expect(e.results[cell(e, "NPV").id]?.isExact == true)3940        e.setParameter(cell(e, "DiscountRate").id, value: 0.0)41        #expect(value(e, "NPV") == -5000)42        // only the parameter, NPV and Decision were recalculated — not the unrelated cells43        let names = e.lastRecalculated.compactMap { e.results[$0]?.definedName }44        #expect(names == ["DiscountRate", "NPV", "Decision"])4546        e.setSource(cell(e, "CashFlow3").id, "CashFlow3 = 60000")47        #expect(value(e, "NPV") == 15000)48        #expect(value(e, "Decision") == 1)49    }50    @Test func orderDoesNotMatter() {51        let e = WorkspaceEngine(document: WorkspaceDocument(cells: [.formula("c = a + b"), .formula("b = a * 2"), .formula("a = 5")]))52        #expect(value(e, "c") == 15)53    }54    @Test func cyclesAreDetectedAndDoNotLoop() {55        var e = WorkspaceEngine(document: WorkspaceDocument(cells: [.formula("a = b + 1"), .formula("b = c + 1"), .formula("c = a + 1"), .formula("d = 4"), .formula("z = a * 2")]))56        for name in ["a", "b", "c"] {57            let id = e.document.cells.first { $0.source.hasPrefix(name + " ") }!.id58            guard case .circularReference(let path)? = e.results[id]?.error else { Issue.record("expected a cycle for \(name)"); continue }59            #expect(path.first == name && path.last == name && path.count == 4)60        }61        #expect(value(e, "d") == 4)62        let z = e.document.cells.last!.id63        #expect(e.results[z]?.error != nil)64        // self reference65        e = WorkspaceEngine(document: WorkspaceDocument(cells: [.formula("x = x + 1")]))66        #expect(e.results[e.document.cells[0].id]?.error == .circularReference(["x", "x"]))67        // breaking the cycle heals everything68        e = WorkspaceEngine(document: WorkspaceDocument(cells: [.formula("a = b + 1"), .formula("b = a + 1")]))69        e.setSource(e.document.cells[1].id, "b = 10")70        #expect(value(e, "a") == 11)71    }72    @Test func errorsPropagateWithAClearMessage() {73        var e = WorkspaceEngine(document: WorkspaceDocument(cells: [.formula("a = 1/0"), .formula("b = a + 1"), .formula("c = 3")]))74        #expect(e.results[e.document.cells[0].id]?.error == .divisionByZero)75        #expect(e.results[e.document.cells[1].id]?.error == .domain("Depends on “a”, which has an error"))76        #expect(value(e, "c") == 3)77        e.setSource(e.document.cells[0].id, "a = 1/4")78        #expect(value(e, "b") == 1.25)79    }80    @Test func functionsAndDuplicates() {81        let e = WorkspaceEngine(document: WorkspaceDocument(cells: [82            .formula("area = f(3)"), .formula("f(r) = k * r^2"), .formula("k = 2"), .formula("k = 5"), .formula("f(2) + 1"),83        ]))84        #expect(value(e, "area") == 18)85        #expect(e.results[e.document.cells[3].id]?.error != nil)          // duplicate definition86        #expect(e.results[e.document.cells[4].id]?.value == Value(9))87    }88    @Test func renamingRewiresDependents() {89        var e = WorkspaceEngine(document: WorkspaceDocument(cells: [.formula("rate = 0.05"), .formula("fv = 100 * (1 + rate)")]))90        #expect(value(e, "fv") == 105)91        e.setSource(e.document.cells[0].id, "r = 0.05")92        #expect(e.results[e.document.cells[1].id]?.error == .unknownVariable("rate"))93        e.setSource(e.document.cells[1].id, "fv = 100 * (1 + r)")94        #expect(value(e, "fv") == 105)95    }96    @Test func tablesAndGraphsTrackDependencies() {97        var e = WorkspaceEngine(document: WorkspaceDocument(cells: [98            .parameter("a", value: 2, range: 0...10, step: 1),99            .table(TableSpec(expression: "a * x^2", variable: "x", start: 0, step: 1, count: 4)),100            .graph(GraphSpec(expressions: ["a * sin(x)", "1/x"])),101            .table(TableSpec(expression: "1/x", variable: "x", start: -1, step: 1, count: 3)),102        ]))103        #expect(e.results[e.document.cells[1].id]?.table?.map(\.y) == [0, 2, 8, 18])104        #expect(e.results[e.document.cells[2].id]?.dependencies == ["a"])105        #expect(e.results[e.document.cells[3].id]?.table?.map(\.y) == [-1, nil, 1])106        e.setParameter(e.document.cells[0].id, value: 3)107        #expect(e.results[e.document.cells[1].id]?.table?.map(\.y) == [0, 3, 12, 27])108        #expect(Set(e.lastRecalculated) == Set(e.document.cells.prefix(3).map(\.id)))109        #expect(e.dependents(of: "a") == Set(e.document.cells[1...2].map(\.id)))110    }111    @Test func largeChainRecalculatesQuickly() {112        var cells = [WorkspaceCell.formula("v0 = 1")]113        for i in 1..<400 { cells.append(.formula("v\(i) = v\(i - 1) + 1")) }114        var e = WorkspaceEngine(document: WorkspaceDocument(cells: cells.reversed()))115        #expect(value(e, "v399") == 400)116        e.setSource(e.document.cells.last!.id, "v0 = 10")117        #expect(value(e, "v399") == 409)118    }119}120121@Suite struct Exports {122    @Test func textCsvLatex() throws {123        let e = WorkspaceEngine(document: npvDocument())124        let exporter = WorkspaceExporter(engine: e)125        let text = exporter.plainText()126        #expect(text.contains("Project NPV") && text.contains("→ −19378.397602") && text.contains("Angle mode: radians"))127        let csv = exporter.csv()128        #expect(csv.hasPrefix("Kind,Name,Expression,Value,Unit,Exact,Notes\r\n"))129        #expect(csv.contains("formula,Investment,Investment = 100000,100000,$,yes,"))130        #expect(csv.contains("parameter,DiscountRate,0.08,0.08,,yes,"))131        let latex = exporter.latex()132        #expect(latex.contains("\\begin{document}") && latex.contains("\\mathrm{NPV} &= ") && latex.contains("\\frac{\\mathrm{CashFlow}_{1}}{1 + \\mathrm{DiscountRate}}"))133        #expect(latex.contains("\\ \\text{\\$}"))134        #expect(exporter.markdown().contains("| `Investment = 100000` | 100000 | $ |"))135        #expect(WorkspaceExporter.csvField("a,\"b\"") == "\"a,\"\"b\"\"\"")136    }137}138139@Suite struct NativeFile {140    @Test func roundTripAndCorruption() throws {141        let doc = npvDocument()142        let data = try WorkspaceFile.encode(doc)143        let back = try WorkspaceFile.decode(data)144        #expect(back.cells == doc.cells && back.title == doc.title && back.id == doc.id)145        #expect(value(WorkspaceEngine(document: back), "NPV") == value(WorkspaceEngine(document: doc), "NPV"))146147        // bit rot inside the document: detected, content still recoverable148        var text = String(decoding: data, as: UTF8.self)149        text = text.replacingOccurrences(of: "100000", with: "900000")150        #expect(throws: WorkspaceFileError.self) { try WorkspaceFile.decode(Data(text.utf8)) }151        do { _ = try WorkspaceFile.decode(Data(text.utf8)); Issue.record("should fail") }152        catch WorkspaceFileError.corrupted(let recovered) { #expect(recovered?.cells.count == doc.cells.count) }153154        // truncation155        #expect(throws: WorkspaceFileError.corrupted(recovered: nil)) { try WorkspaceFile.decode(data.prefix(data.count / 2)) }156        #expect(throws: WorkspaceFileError.notAWorkspaceFile) { try WorkspaceFile.decode(Data("{\"hello\": 1}".utf8)) }157        #expect(throws: WorkspaceFileError.notAWorkspaceFile) { try WorkspaceFile.decode(Data("not json".utf8)) }158        let future = String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\"version\" : 1", with: "\"version\" : 99")159        #expect(throws: WorkspaceFileError.unsupportedVersion(99)) { try WorkspaceFile.decode(Data(future.utf8)) }160    }161    @Test func duplicate() {162        let doc = npvDocument()163        let copy = doc.duplicated()164        #expect(copy.id != doc.id && copy.title == "Project NPV copy" && Set(copy.cells.map(\.id)).isDisjoint(with: doc.cells.map(\.id)))165        #expect(copy.cells.map(\.source) == doc.cells.map(\.source))166    }167}168
Files main
Menu

Theme