Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : VQuant for macOS9// File : Tests/SyncTests/WatchlistMigrationTests.swift10// Description : The migration of this Mac's 1.x watchlists to synced11// objects, against the kit's in-memory server. The app12// target cannot be imported by SwiftPM, so `migrate` below13// transcribes the loop of `SyncStore.migrateLocalData`14// (App/Next/SyncStore.swift) — same id rule, same "save only15// when absent", same 200-symbol cap; the tests check what16// that loop relies on: ids the server accepts, no duplicate17// when it runs again, on a second Mac, or before the first18// pull.19// Module : SyncTests20// Repository : https://git.spboucher.ai/vquant-macos21// Created : 2026-11-2022// Last Modified : 2026-11-2023//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author : Simon-Pierre Boucher29// Position : Professor of Finance30// Institution : Université du Québec en Outaouais (UQO)31// Department : Département des sciences administratives32// Organization : SP Boucher33//34// Website : https://spboucher.ai35// Git : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General : info@spboucher.ai42// Professional : contact@spboucher.ai43// Direct : simon@spboucher.ai44// Research : research@spboucher.ai45// Development : dev@spboucher.ai46// Support : support@spboucher.ai47// Security/Admin : admin@spboucher.ai48// Notifications : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification : Public75// Distribution : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License : None specified (no license file in this repository)89// Maintainer : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import Foundation97import Testing98import VQuantCore99import VQuantKit100import VQuantKitTesting101102@MainActor @Suite struct WatchlistMigrationTests {103 /// `SyncStore.migratedID`.104 static func migratedID(_ local: UUID) -> String { "mac-" + local.uuidString.lowercased() }105106 /// The watchlist part of `SyncStore.migrateLocalData`. Returns how many lists were written.107 @discardableResult108 static func migrate(_ lists: [Watchlist], into collection: VQSyncedCollection<VQWatchlist>) async -> Int {109 var moved = 0110 for l in lists {111 let id = migratedID(l.id)112 if collection[id] == nil {113 await collection.save(VQWatchlist(name: l.name, symbols: Array(l.symbols.prefix(VQWatchlist.maxSymbols))), id: id)114 if collection.lastError == nil { moved += 1 }115 }116 }117 return moved118 }119120 func mac(_ server: VQFakeServer, _ device: String) -> (VQSyncEngine, VQSyncedCollection<VQWatchlist>) {121 let engine = VQSyncEngine(transport: server.transport(device: device), storage: VQMemorySyncStorage())122 return (engine, VQSyncedCollection<VQWatchlist>(engine: engine))123 }124125 /// Waits until the engine's queue has reached the server (a write schedules its own flush; one may be in flight).126 func settle(_ engine: VQSyncEngine, _ lists: VQSyncedCollection<VQWatchlist>) async {127 for _ in 0..<500 {128 await engine.flush()129 if await engine.pendingWrites.isEmpty { break }130 try? await Task.sleep(for: .milliseconds(10))131 }132 await lists.refresh()133 }134135 let local = [Watchlist(name: "Watchlist", symbols: ["AAPL", "MSFT", "NVDA"]), Watchlist(name: "Banks", symbols: ["JPM", "RY.TO"])]136137 @Test func idsAreDerivedFromTheLocalListAndAcceptedByTheServer() {138 let u = UUID(uuidString: "0A1B2C3D-4E5F-6789-ABCD-EF0123456789")!139 #expect(Self.migratedID(u) == "mac-0a1b2c3d-4e5f-6789-abcd-ef0123456789")140 #expect(Self.migratedID(u) == Self.migratedID(u)) // deterministic: the same list always gives the same object141 #expect(VQObjectID.isValid(Self.migratedID(u)) && Self.migratedID(u).count <= 64)142 #expect(Self.migratedID(UUID()) != Self.migratedID(UUID()))143 }144145 @Test func listsReachTheAccountOnceAndRunningAgainWritesNothing() async throws {146 let server = VQFakeServer()147 let (engine, lists) = mac(server, "mac-A")148 try await engine.syncNow(); await lists.refresh()149 #expect(await Self.migrate(local, into: lists) == 2)150 #expect(lists.items.count == 2) // shown at once, before the server has answered151 await settle(engine, lists)152 #expect(lists.pendingIDs.isEmpty)153 for l in local {154 let stored = server.stored(.watchlist, Self.migratedID(l.id))155 #expect(stored?.rev == 1 && stored?.deleted == false)156 #expect(stored.map { VQWatchlist(json: $0.data) }?.name == l.name)157 #expect(stored.map { VQWatchlist(json: $0.data) }?.symbols == l.symbols) // order kept158 }159 let puts = server.requestCount(.put, pathPrefix: "/api/v2/objects/watchlist")160 // a crash before the "migrated" flag is written: the migration runs again161 #expect(await Self.migrate(local, into: lists) == 0)162 await settle(engine, lists)163 #expect(server.requestCount(.put, pathPrefix: "/api/v2/objects/watchlist") == puts)164 #expect(lists.items.count == 2)165 }166167 @Test func aSecondMacRestoredFromTheSameBackupAddsNoDuplicate() async throws {168 let server = VQFakeServer()169 let (a, listsA) = mac(server, "mac-A")170 try await a.syncNow(); await listsA.refresh()171 await Self.migrate(local, into: listsA); await settle(a, listsA)172 // it pulled first: it sees the objects and writes nothing173 let (b, listsB) = mac(server, "mac-B")174 try await b.syncNow(); await listsB.refresh()175 let puts = server.requestCount(.put, pathPrefix: "/api/v2/objects/watchlist")176 #expect(await Self.migrate(local, into: listsB) == 0)177 await settle(b, listsB)178 #expect(server.requestCount(.put, pathPrefix: "/api/v2/objects/watchlist") == puts)179 #expect(listsB.items.count == 2)180 }181182 @Test func migratingBeforeTheFirstPullMergesIntoTheSameObjects() async throws {183 let server = VQFakeServer()184 let (a, listsA) = mac(server, "mac-A")185 try await a.syncNow(); await listsA.refresh()186 await Self.migrate(local, into: listsA); await settle(a, listsA)187 // meanwhile the list changed on the account188 await listsA.update(Self.migratedID(local[0].id)) { $0.add("TSLA") }189 await settle(a, listsA)190 // Mac C never managed its first round (offline at sign-in): its replica is empty, so it creates with baseRev 0191 let (c, listsC) = mac(server, "mac-C")192 await listsC.refresh()193 #expect(await Self.migrate(local, into: listsC) == 2)194 await settle(c, listsC); try await c.syncNow(); await listsC.refresh()195 try await a.syncNow(); await listsA.refresh()196 // the server refused the creations (409) and the engine merged symbol by symbol: still two objects, nothing twice197 #expect(listsC.items.count == 2 && listsA.items.count == 2)198 let merged = server.stored(.watchlist, Self.migratedID(local[0].id)).map { VQWatchlist(json: $0.data) }199 #expect(Set(merged?.symbols ?? []) == ["AAPL", "MSFT", "NVDA", "TSLA"])200 #expect(merged?.symbols.count == 4)201 #expect(listsC.pendingIDs.isEmpty)202 }203204 @Test func aListLongerThanTheServerAllowsIsCutNotRefused() async throws {205 let server = VQFakeServer()206 let (engine, lists) = mac(server, "mac-A")207 try await engine.syncNow(); await lists.refresh()208 let long = Watchlist(name: "Everything", symbols: (0..<260).map { "S\($0)" })209 #expect(await Self.migrate([long], into: lists) == 1)210 await settle(engine, lists)211 let stored = server.stored(.watchlist, Self.migratedID(long.id)).map { VQWatchlist(json: $0.data) }212 #expect(stored?.symbols.count == VQWatchlist.maxSymbols && stored?.symbols.first == "S0" && stored?.validationIssues().isEmpty == true)213 }214}215