// // SynchronizationTests.swift // PadelClubDataTests // // Created by Laurent Morvillier on 17/04/2025. // import Testing @testable import PadelClubData @testable import LeStorage struct SynchronizationTests { let username: String = "UserDataTests" let password: String = "MyPass1234--" var secondStoreCenter: StoreCenter init() async throws { self.secondStoreCenter = StoreCenter(directoryName: "storage-2") self.secondStoreCenter.configureURLs(secureScheme: false, domain: "127.0.0.1:8000", webSockets: false) self.secondStoreCenter.tokenKeychain = MockKeychainStore(fileName: "storage-2/token.json") self.secondStoreCenter.deviceKeychain = MockKeychainStore(fileName: "storage-2/device.json") self.secondStoreCenter.classProject = "PadelClubData" let token2 = try? self.secondStoreCenter.rawTokenShouldNotBeUsed() if token2 == nil { try await self.login(storeCenter: self.secondStoreCenter) } StoreCenter.main.configureURLs(secureScheme: false, domain: "127.0.0.1:8000", webSockets: false) StoreCenter.main.tokenKeychain = MockKeychainStore(fileName: "storage/token.json") StoreCenter.main.deviceKeychain = MockKeychainStore(fileName: "storage/device.json") StoreCenter.main.classProject = "PadelClubData" let token = try? StoreCenter.main.rawTokenShouldNotBeUsed() if token == nil { try await self.login(storeCenter: StoreCenter.main) } } mutating func login(storeCenter: StoreCenter) async throws { let _: CustomUser = try await storeCenter.service().login(username: self.username, password: self.password) } @Test func testAuthentication() { #expect(StoreCenter.main.isAuthenticated) #expect(self.secondStoreCenter.isAuthenticated) } @Test func testSynchronization() async throws { guard let userId = StoreCenter.main.userId else { throw TestError.notAuthenticated } // Cleanup let eventCollection1: SyncedCollection = StoreCenter.main.mainStore.registerSynchronizedCollection(synchronousLoading: true) await eventCollection1.deleteAsync(contentOfs: Array(eventCollection1)) let eventCollection2: SyncedCollection = self.secondStoreCenter.mainStore.registerSynchronizedCollection(synchronousLoading: true) eventCollection2.clear() // Create let event: Event = Event(creator: userId, club: nil, name: "test") await eventCollection1.addOrUpdateAsync(instance: event) let serverEvents: [Event] = try await StoreCenter.main.service().get() #expect(serverEvents.count == 1) try await eventCollection1.loadDataFromServerIfAllowed(clear: true) #expect(eventCollection1.count == 1) try await eventCollection2.loadDataFromServerIfAllowed(clear: true) #expect(eventCollection2.count == 1) try await self.secondStoreCenter.testSynchronizeOnceAsync() #expect(eventCollection2.count == 1) } }