SPB Git

Repository Public

SyncModelTests.swift 12.6 KB 179 lines swift

1import Foundation2import Testing3@testable import VQuantKit45@Suite struct SyncModelTests {6    /// Forward compatibility: keys this version does not know survive decode → typed edit → encode, at every depth.7    @Test func unknownKeysSurviveATypedEdit() throws {8        let original = try VQJSON.parse(#"""9        {"name":"Core","baseCurrency":"USD","benchmark":null,"futureTopLevel":{"deep":[1,{"x":null}]},10         "cash":[{"currency":"USD","amount":10,"heldAt":"broker-1"}],11         "positions":[{"symbol":"AAPL","quantity":10,"costBasis":150.25,"updatedAt":1700000001000,"lots":[{"q":4,"p":140},{"q":6,"p":157}]},12                      {"symbol":"MSFT","quantity":2,"taxLot":"B"}]}13        """#)14        var p = VQPortfolio(json: original)15        #expect(p.json == original)                                         // untouched: identical JSON, explicit null included16        var positions = p.positions17        positions[0].quantity = 1218        positions[0].note = "added"19        p.positions = positions20        p.name = "Core 2"21        let out = p.json22        #expect(out["futureTopLevel"] == original["futureTopLevel"])23        #expect(out["benchmark"] == .null)24        #expect(out["cash"] == original["cash"])25        #expect(out["positions"]?[0]?["lots"] == original["positions"]?[0]?["lots"])26        #expect(out["positions"]?[0]?["updatedAt"] == .number(1_700_000_001_000))27        #expect(out["positions"]?[0]?["quantity"] == .number(12) && out["positions"]?[0]?["note"] == .string("added"))28        #expect(out["positions"]?[1] == original["positions"]?[1])29        // and through bytes30        #expect(VQPortfolio(json: try VQJSON.parse(out.data())) == p)31        // Codable too (the apps' caches)32        #expect(try JSONDecoder().decode(VQPortfolio.self, from: try JSONEncoder().encode(p)) == p)33    }3435    @Test func recordedObjectsRoundTripExactly() throws {36        for file in ["objects_watchlist", "objects_portfolio", "objects_workspace", "objects_chart", "objects_project", "objects_note", "objects_review"] {37            for e in try Fixture.json("\(file).json").models("objects", as: VQObjectEnvelope.self) {38                let again = VQObjectEnvelope(json: try VQJSON.parse(e.json.data()))39                #expect(again == e)40                switch e.kind {41                case .watchlist: #expect(VQWatchlist(json: e.data).json == e.data)42                case .portfolio: #expect(VQPortfolio(json: e.data).json == e.data)43                case .workspace:44                    var w = VQWorkspace(json: e.data)45                    w.layout = w.layout; w.panels = w.panels              // re-encoding the typed parts changes nothing46                    #expect(w.json == e.data)47                case .chart:48                    var c = VQChart(json: e.data); c.drawings = c.drawings; c.indicators = c.indicators49                    #expect(c.json == e.data)50                case .project:51                    var p = VQProject(json: e.data); p.items = p.items; p.hypotheses = p.hypotheses52                    #expect(p.json == e.data)53                default: break54                }55            }56        }57    }5859    @Test func settingNilRemovesTheKeyAndWrongTypesReadAsAbsent() {60        var w = VQWatchlist(name: "A", symbols: ["X"], note: "n")61        w.note = nil62        #expect(w.raw["note"] == nil)63        let odd = VQWatchlist(json: ["name": 12, "symbols": "AAPL"])64        #expect(odd.name == "" && odd.symbols.isEmpty)65        #expect(Set(odd.validationIssues()) == ["name", "symbols"])66        #expect(VQWatchlist(name: "ok").validationIssues().isEmpty)67        var list = VQWatchlist(name: "L")68        #expect(list.add(" aapl ") && !list.add("AAPL") && list.symbols == ["AAPL"])69    }7071    @Test func layoutTree() {72        var ws = VQWorkspace(name: "W", layout: .split(.row, sizes: [0.6, 0.4], children: [.panel("a"), .split(.column, children: [.panel("b"), .panel("c")])]),73                             panels: ["a": VQPanel(type: .chart), "b": VQPanel(type: .watchlist), "c": VQPanel(type: .quote, title: "MSFT", config: ["symbol": "MSFT"])])74        #expect(ws.validationIssues().isEmpty)75        #expect(ws.layout.panelIds == ["a", "b", "c"] && ws.layout.fractions == [0.6, 0.4] && ws.layout.children[1].fractions == [0.5, 0.5])76        ws.removePanel("b")                                                  // the inner split collapses into its remaining child77        #expect(ws.layout.panelIds == ["a", "c"] && ws.layout.children[1].kind == .panel && ws.panels["b"] == nil)78        ws.addPanel(VQPanel(type: .news), id: "d", beside: "c", direction: .column)79        #expect(ws.layout.panelIds == ["a", "c", "d"] && ws.layout.children[1].direction == .column && ws.validationIssues().isEmpty)80        ws.removePanel("a"); ws.removePanel("c"); ws.removePanel("d")81        #expect(ws.layout.kind == nil && ws.layout.panelIds.isEmpty)82        ws.addPanel(VQPanel(type: .chat), id: "e")83        #expect(ws.layout == .panel("e"))84        // a node or panel type from a later version is kept and reported, not dropped85        let future = VQWorkspace(json: ["name": "F", "layout": ["type": "tabs", "children": [["type": "panel", "panelId": "x"]], "activeTab": 0], "panels": ["x": ["type": "hologram", "title": "?"]]])86        #expect(future.layout.kind == nil && future.layout.raw["activeTab"] == .number(0) && future.panels["x"]?.type.known == nil && future.panels["x"]?.type.rawValue == "hologram")87        #expect(future.validationIssues().contains("layout.type"))88        // bad sizes fall back to equal shares89        #expect(VQLayoutNode.split(.row, sizes: [1], children: [.panel("a"), .panel("b")]).fractions == [0.5, 0.5])90    }9192    @Test func idsAndKinds() {93        #expect(VQObjectID.isValid("kit-test_1") && !VQObjectID.isValid("") && !VQObjectID.isValid("a/b") && !VQObjectID.isValid(String(repeating: "a", count: 65)))94        #expect(VQObjectID.isValid(VQObjectID.make()))95        #expect(VQObjectKind.review.isServerOnly && !VQObjectKind.note.isServerOnly)96        #expect(VQObjectKind("auto_research").rawValue == "auto_research")       // a kind from a later contract section is just a string97        var pref = VQPreference()98        pref.upDownColors = .known(.cvd); pref.routing = .init(strategy: .economy, providers: ["anthropic", "local"]); pref.budget = .init(maxCostUsd: 2)99        #expect(pref.json == ["upDownColors": "cvd", "routing": ["strategy": "economy", "providers": ["anthropic", "local"]], "budget": ["maxCostUsd": 2]])100        #expect(VQNumberLocale(preference: pref.numberFormat) == .frCA)101    }102}103104@Suite struct MergeTests {105    private func merge(_ kind: VQObjectKind, base: VQJSON?, local: VQJSON, remote: VQJSON, _ g: VQMergeGranularity = .object) -> VQMergeOutcome {106        VQMerge.merge(kind: kind, base: base, local: local, remote: remote, granularity: g)107    }108109    @Test func watchlistSymbolsUnionLocalEditWins() {110        let base: VQJSON = ["name": "W", "symbols": ["A", "B", "C", "D"]]111        let local: VQJSON = ["name": "W", "symbols": ["A", "C", "D", "L"]]              // removed B, added L112        let remote: VQJSON = ["name": "W", "symbols": ["A", "B", "C", "R"]]             // removed D, added R113        let o = merge(.watchlist, base: base, local: local, remote: remote)114        #expect(o.merged["symbols"] == ["A", "C", "L", "R"])                             // B stays removed (local), D follows the server's removal115        #expect(o.mergedLists == ["symbols"] && o.overwrittenKeys.isEmpty)116        // without a base (two devices created the same id): plain union, local order first117        let u = merge(.watchlist, base: nil, local: ["name": "W", "symbols": ["X", "A"]], remote: ["name": "W", "symbols": ["A", "Y"]])118        #expect(u.merged["symbols"] == ["X", "A", "Y"])119    }120121    @Test func portfolioPositionsBySymbolAndCashByCurrency() {122        let base: VQJSON = ["name": "P", "baseCurrency": "USD", "cash": [["currency": "USD", "amount": 100]],123                            "positions": [["symbol": "AAPL", "quantity": 10], ["symbol": "MSFT", "quantity": 5], ["symbol": "TLT", "quantity": 1]]]124        let local: VQJSON = ["name": "P", "baseCurrency": "USD", "cash": [["currency": "USD", "amount": 80]],125                             "positions": [["symbol": "AAPL", "quantity": 12], ["symbol": "MSFT", "quantity": 5], ["symbol": "GLD", "quantity": 3]]]    // edited AAPL, removed TLT, added GLD126        let remote: VQJSON = ["name": "P", "baseCurrency": "USD", "cash": [["currency": "USD", "amount": 100], ["currency": "CAD", "amount": 50]],127                              "positions": [["symbol": "AAPL", "quantity": 11, "updatedAt": 5], ["symbol": "MSFT", "quantity": 7, "updatedAt": 6], ["symbol": "TLT", "quantity": 2], ["symbol": "NVDA", "quantity": 1]]]128        let o = merge(.portfolio, base: base, local: local, remote: remote)129        #expect(o.merged["positions"] == [["symbol": "AAPL", "quantity": 12],                    // both edited: local wins the element130                                          ["symbol": "MSFT", "quantity": 7, "updatedAt": 6],      // untouched here: the server's version, unknown key kept131                                          ["symbol": "GLD", "quantity": 3],                       // added here132                                          ["symbol": "NVDA", "quantity": 1]])                     // added there; TLT stays removed133        #expect(o.merged["cash"] == [["currency": "USD", "amount": 80], ["currency": "CAD", "amount": 50]])134        #expect(Set(o.mergedLists) == ["positions", "cash"] && o.overwrittenKeys.isEmpty)135    }136137    @Test func projectItemsMergeButTheRestIsLastWriterWins() {138        let base: VQJSON = ["title": "T", "summary": "s0", "items": [["id": "1", "ref": "a"]]]139        let local: VQJSON = ["title": "T local", "summary": "s0", "items": [["id": "1", "ref": "a"], ["id": "2", "ref": "b"]]]140        let remote: VQJSON = ["title": "T remote", "summary": "s1", "items": [["id": "1", "ref": "a", "title": "renamed"], ["id": "3", "ref": "c"]], "newServerKey": true]141        let o = merge(.project, base: base, local: local, remote: remote)142        #expect(o.merged["items"] == [["id": "1", "ref": "a", "title": "renamed"], ["id": "2", "ref": "b"], ["id": "3", "ref": "c"]])143        #expect(o.merged["title"] == "T local" && o.merged["summary"] == "s0" && o.merged["newServerKey"] == nil)       // the object of the last writer144        #expect(o.overwrittenKeys == ["newServerKey", "summary", "title"])                                               // …and the UI is told what was overwritten145        // field granularity keeps what this device did not touch146        let f = merge(.project, base: base, local: local, remote: remote, .field)147        #expect(f.merged["title"] == "T local" && f.merged["summary"] == "s1" && f.merged["newServerKey"] == true)148        #expect(f.overwrittenKeys == ["title"])149    }150151    @Test func chartDrawingsById() {152        let base: VQJSON = ["symbol": "AAPL", "interval": "1d", "drawings": [["id": "d1", "type": "line"], ["id": "d2", "type": "line"]]]153        let local: VQJSON = ["symbol": "AAPL", "interval": "1h", "drawings": [["id": "d1", "type": "line", "text": "mine"], ["id": "d2", "type": "line"]]]154        let remote: VQJSON = ["symbol": "AAPL", "interval": "1d", "drawings": [["id": "d1", "type": "ray"], ["id": "d3", "type": "fib"]]]     // edited d1, removed d2, added d3155        let o = merge(.chart, base: base, local: local, remote: remote)156        #expect(o.merged["drawings"] == [["id": "d1", "type": "line", "text": "mine"], ["id": "d3", "type": "fib"]])157        #expect(o.merged["interval"] == "1h" && o.overwrittenKeys.isEmpty)               // only this device changed the interval: nothing lost158    }159160    @Test(arguments: [VQObjectKind.note, .workspace, .preference, VQObjectKind("kind_from_the_future")])161    func otherKindsAreLastWriterWins(_ kind: VQObjectKind) {162        let base: VQJSON = ["title": "t", "body": "b0", "list": [["id": "1"]]]163        let local: VQJSON = ["title": "t", "body": "local text", "list": [["id": "1"], ["id": "L"]]]164        let remote: VQJSON = ["title": "t2", "body": "remote text", "list": [["id": "1"], ["id": "R"]]]165        let o = merge(kind, base: base, local: local, remote: remote)166        #expect(o.merged == local && o.mergedLists.isEmpty)167        #expect(o.overwrittenKeys == ["body", "list", "title"])168        // identical text on both sides is not a conflict169        #expect(merge(kind, base: base, local: local, remote: local).overwrittenKeys.isEmpty)170    }171172    @Test func remoteUnchangedMeansLocalAsIs() {173        let base: VQJSON = ["name": "W", "symbols": ["A"]]174        let local: VQJSON = ["name": "W2", "symbols": ["B"]]175        let o = merge(.watchlist, base: base, local: local, remote: base)176        #expect(o.merged == local && o.overwrittenKeys.isEmpty)177    }178}179
Files main
Menu

Theme