Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXFeatureWorkspace/Tests/ORIXFeatureWorkspaceTests/StoreTests.swift3// Description: Tests of the workspace session against a real AppModel — library operations, auto-save and reload, hand-offs, import.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10import ORIXUI11import ORIXWorkspace12@testable import ORIXFeatureWorkspace1314@MainActor @Suite struct LibraryTests {15 @Test func createOpenRenameDuplicateDelete() throws {16 let app = makeApp()17 let store = WorkspaceStore(app: app)18 #expect(store.entries.isEmpty && store.sheet == nil)19 let blank = try #require(store.create())20 #expect(store.sheet?.id == blank && store.entries.map(\.title) == ["Untitled"] && store.entries[0].cellCount == 1)21 let second = try #require(store.create())22 #expect(Set(store.entries.map(\.title)) == ["Untitled", "Untitled 2"])23 for template in WorkspaceTemplate.allCases {24 let id = try #require(store.create(template: template))25 let entry = try #require(store.entries.first { $0.id == id })26 #expect(entry.title == template.title && entry.cellCount == template.document().cells.count)27 #expect(store.sheet?.cells.allSatisfy { store.sheet?.result($0.id)?.error == nil } == true)28 }29 #expect(app.workspaces().count == 6)3031 store.rename(second, to: " Budget 2027 ")32 #expect(app.loadWorkspace(second)?.document.title == "Budget 2027")33 let open = try #require(store.sheet)34 store.rename(open.id, to: "Open one")35 #expect(open.title == "Open one" && app.loadWorkspace(open.id)?.document.title == "Open one")3637 let copy = try #require(store.duplicate(open.id))38 let copied = try #require(app.loadWorkspace(copy)?.document)39 #expect(copied.title == "Open one copy" && copied.cells.map(\.source) == open.cells.map(\.source))40 #expect(Set(copied.cells.map(\.id)).isDisjoint(with: open.cells.map(\.id)))4142 store.delete(open.id)43 #expect(store.sheet == nil && app.loadWorkspace(open.id) == nil && store.entries.count == 6)44 store.open(blank)45 #expect(store.sheet?.id == blank)46 store.delete(second)47 #expect(store.sheet?.id == blank, "deleting another workspace leaves the open one alone")48 #expect(store.entries.count == 5)49 }5051 @Test func newDocumentsTakeTheAppDefaults() throws {52 let app = makeApp()53 app.settings.data.angleMode = .gradians54 app.settings.data.complexEnabled = true55 let store = WorkspaceStore(app: app)56 store.create()57 #expect(store.sheet?.settings.angleMode == .gradians && store.sheet?.settings.complexEnabled == true)58 store.create(template: .projectile)59 #expect(store.sheet?.settings.angleMode == .degrees, "the projectile template works in degrees")60 }61}6263@MainActor @Suite struct AutoSaveTests {64 @Test func debouncedSaveThenReloadRoundTrip() async throws {65 let app = makeApp()66 let store = WorkspaceStore(app: app)67 store.saveDebounce = .milliseconds(60)68 let id = try #require(store.create(template: .capitalBudgeting))69 let sheet = try #require(store.sheet)70 let rate = try #require(sheet.cells.first { $0.kind == .parameter })71 for k in 1...20 { sheet.setParameterValue(rate.id, 0.08 + Double(k) * 0.005, continuous: true) }72 sheet.setSource(try #require(sheet.cellDefining("Investment")).id, "Investment = 90000")73 sheet.addCell(.text)74 #expect(store.hasUnsavedChanges)75 #expect(value(SheetModel(document: try #require(app.loadWorkspace(id)).document, app: app), "Investment") == 100000, "persistence is debounced, not done on every change")76 for _ in 0..<200 where store.hasUnsavedChanges { try await Task.sleep(for: .milliseconds(25)) }77 #expect(!store.hasUnsavedChanges, "the debounced save ran by itself")7879 // "relaunch": a new session over the same store reopens the last workspace, intact80 let relaunched = WorkspaceStore(app: app)81 let restored = try #require(relaunched.sheet)82 #expect(restored.id == id && restored.cells == sheet.cells && restored.title == sheet.title && restored.settings == sheet.settings)83 let expected: Double = npv(0.18) + 1000084 #expect(close(value(restored, "NPV"), expected))85 #expect(relaunched.entries.first { $0.id == id }?.cellCount == sheet.cells.count)86 #expect(restored.warning == nil)87 }8889 @Test func flushSavesImmediatelyAndCloseForgetsTheLastWorkspace() throws {90 let app = makeApp()91 let store = WorkspaceStore(app: app)92 store.saveDebounce = .seconds(60)93 let id = try #require(store.create())94 let sheet = try #require(store.sheet)95 // an edit still in the field is part of what gets saved96 sheet.beginEditing(sheet.cells[0].id)97 sheet.setDraft(sheet.cells[0].id, "x = 6 * 7")98 sheet.setTitle("Scratch")99 store.flush()100 let saved = try #require(app.loadWorkspace(id)?.document)101 #expect(saved.title == "Scratch" && saved.cells[0].source == "x = 6 * 7")102 #expect(store.entries.first?.title == "Scratch")103104 sheet.setSource(sheet.cells[0].id, "x = 43")105 store.close()106 #expect(store.sheet == nil && app.loadWorkspace(id)?.document.cells[0].source == "x = 43", "closing saves pending changes")107 #expect(WorkspaceStore(app: app).sheet == nil, "after returning to the library, nothing reopens by itself")108109 store.open(id)110 store.sheet?.setSource(sheet.cells[0].id, "x = 44")111 store.open(try #require(store.create()))112 #expect(app.loadWorkspace(id)?.document.cells[0].source == "x = 44", "switching workspace saves the previous one")113 }114115 @Test func demoIsNeverSaved() throws {116 let app = makeApp()117 let store = WorkspaceStore(app: app, demo: true)118 let sheet = try #require(store.sheet)119 #expect(sheet.isDemo && sheet.title == "Project NPV")120 #expect(close(value(sheet, "NPV"), npv(0.08)))121 #expect(sheet.cells.contains { $0.parameter?.name == "DiscountRate" } && sheet.cells.contains { $0.kind == .table } && sheet.cells.contains { $0.kind == .graph })122 sheet.setSource(try #require(sheet.cellDefining("Investment")).id, "Investment = 1")123 store.flush()124 store.close()125 #expect(app.workspaces().isEmpty && store.entries.isEmpty && app.history.isEmpty)126 #expect(WorkspaceStore(app: app).sheet == nil)127 }128129 @Test func aDamagedPayloadIsRecoveredWithAWarningOnce() throws {130 let app = makeApp()131 let document = npvDocument()132 var text = String(decoding: try WorkspaceFile.encode(document), as: UTF8.self)133 text = text.replacingOccurrences(of: "100000", with: "900000")134 app.container.mainContext.insert(WorkspaceRecord(id: document.id, title: document.title, modified: document.modified, payload: Data(text.utf8)))135 try app.container.mainContext.save()136137 let store = WorkspaceStore(app: app)138 #expect(store.entries.first?.cellCount == 9)139 store.open(document.id)140 let sheet = try #require(store.sheet)141 #expect(sheet.warning?.contains("recovered") == true)142 #expect(value(sheet, "Investment") == 900000)143 // the recovered content was re-saved cleanly: the warning does not come back144 #expect(app.loadWorkspace(document.id)?.recovered == false)145 let again = WorkspaceStore(app: app)146 #expect(again.sheet?.id == document.id && again.sheet?.warning == nil)147148 // unreadable payload: a clear message, nothing opened149 let broken = UUID()150 app.container.mainContext.insert(WorkspaceRecord(id: broken, title: "Broken", modified: .now, payload: Data("{ nope".utf8)))151 try app.container.mainContext.save()152 again.close()153 again.open(broken)154 #expect(again.sheet == nil && again.message?.contains("could not be read") == true)155 }156}157158@MainActor @Suite struct HandOffTests {159 @Test func pendingLineGoesToTheOpenWorkspace() throws {160 let app = makeApp()161 let store = WorkspaceStore(app: app)162 store.create(template: .capitalBudgeting)163 let sheet = try #require(store.sheet)164 let count = sheet.cells.count165 app.sendToWorkspace("MonthlyPayment = 1744.81")166 #expect(app.pendingWorkspaceLine == "MonthlyPayment = 1744.81")167 store.consumePending()168 #expect(app.pendingWorkspaceLine == nil)169 let added = try #require(sheet.cells.last)170 #expect(sheet.cells.count == count + 1 && added.kind == .formula && added.source == "MonthlyPayment = 1744.81")171 #expect(sheet.selection == added.id && sheet.scrollTarget == added.id && sheet.highlighted == [added.id])172 #expect(value(sheet, "MonthlyPayment") == 1744.81)173 store.flush()174 #expect(app.loadWorkspace(sheet.id)?.document.cells.last?.source == "MonthlyPayment = 1744.81")175 }176177 @Test func pendingLineCreatesQuickCalculationsWhenNothingIsOpen() throws {178 let app = makeApp()179 app.pendingWorkspaceLine = "Tip = 84.50 * 0.15"180 let store = WorkspaceStore(app: app) // consumed while attaching181 let sheet = try #require(store.sheet)182 #expect(app.pendingWorkspaceLine == nil && sheet.title == "Quick calculations" && sheet.cells.map(\.source) == ["Tip = 84.50 * 0.15"])183 #expect(close(value(sheet, "Tip"), 12.675))184 store.close()185 // a second line reuses the same workspace instead of piling up new ones186 app.pendingWorkspaceLine = "Total = 84.50 + Tip"187 store.consumePending()188 #expect(store.sheet?.id == sheet.id && store.entries.filter { $0.title == "Quick calculations" }.count == 1)189 #expect(close(value(try #require(store.sheet), "Total"), 97.175))190 }191192 @Test func pendingDocumentIsOpened() throws {193 let app = makeApp()194 let store = WorkspaceStore(app: app)195 store.create()196 let data = try WorkspaceFile.encode(npvDocument())197 #expect(app.openWorkspaceFile(data) == nil)198 #expect(app.pendingWorkspaceDocument != nil)199 store.consumePending()200 #expect(app.pendingWorkspaceDocument == nil)201 #expect(store.sheet?.title == "Project NPV" && store.entries.contains { $0.title == "Project NPV" && $0.cellCount == 9 })202 #expect(close(value(try #require(store.sheet), "NPV"), npv(0.08)))203 // it is now the last open workspace204 #expect(WorkspaceStore(app: app).sheet?.title == "Project NPV")205 }206}207208@MainActor @Suite struct ImportTests {209 @Test func validFileOpensAndASecondImportBecomesACopy() throws {210 let app = makeApp()211 let store = WorkspaceStore(app: app)212 let document = npvDocument()213 let data = try WorkspaceFile.encode(document)214 #expect(store.importFile(data))215 #expect(store.sheet?.id == document.id && store.sheet?.warning == nil && store.message == nil)216 store.sheet?.setSource(document.cells[1].id, "Investment = 50000")217 #expect(store.importFile(data))218 #expect(store.entries.count == 2 && store.sheet?.id != document.id && store.sheet?.title == "Project NPV 2")219 #expect(app.loadWorkspace(document.id)?.document.cells[1].source == "Investment = 50000", "the existing workspace keeps its edits")220 }221222 @Test func damagedAndForeignFiles() throws {223 let app = makeApp()224 let store = WorkspaceStore(app: app)225 let data = try WorkspaceFile.encode(npvDocument())226 let tampered = Data(String(decoding: data, as: UTF8.self).replacingOccurrences(of: "100000", with: "900000").utf8)227 #expect(store.importFile(tampered))228 let recovered = try #require(store.sheet)229 #expect(recovered.warning?.contains("damaged") == true)230 #expect(value(recovered, "Investment") == 900000)231 store.close()232233 #expect(!store.importFile(data.prefix(data.count / 2)))234 #expect(store.message == "The workspace file is damaged and could not be read." && store.sheet == nil)235 #expect(!store.importFile(Data("{\"hello\": 1}".utf8)))236 #expect(store.message == "This file is not an ORIX Calc workspace.")237 let future = Data(String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\"version\" : 1", with: "\"version\" : 99").utf8)238 #expect(!store.importFile(future))239 #expect(store.message?.contains("newer version") == true)240 #expect(store.entries.count == 1)241242 // through a file URL, as the importer delivers it243 let url = try WorkspaceExport.write(data, named: "Imported.orixcalc")244 #expect(store.importFile(at: url))245 #expect(!store.importFile(at: url.deletingLastPathComponent().appendingPathComponent("missing.orixcalc")))246 #expect(store.message == "The file could not be opened.")247 }248}249