AuthorIdentityTests.swift (2861B)
1 import CloudKit 2 import Foundation 3 import Testing 4 5 @testable import Crossmate 6 7 @Suite("AuthorIdentity") 8 @MainActor 9 struct AuthorIdentityTests { 10 11 private func makeIsolatedStorage() -> UserDefaults { 12 UserDefaults(suiteName: "test-authoridentity-\(UUID().uuidString)")! 13 } 14 15 @Test("Initial state returns nil before any refresh") 16 func initialStateIsNil() { 17 let identity = AuthorIdentity(storage: makeIsolatedStorage()) 18 #expect(identity.currentID == nil) 19 } 20 21 @Test("Testing initializer seeds currentID") 22 func testingInitializerSeedsValue() { 23 let identity = AuthorIdentity(testing: "_abc") 24 #expect(identity.currentID == "_abc") 25 } 26 27 @Test("refresh with unavailable account leaves currentID nil") 28 func refreshFailurePreservesNil() async { 29 let identity = AuthorIdentity(storage: makeIsolatedStorage()) 30 // Using the default CKContainer without a signed-in account will fail. 31 // The contract is: on failure, currentID stays nil (or unchanged). 32 let containerWithNoAccount = CKContainer(identifier: "iCloud.net.inqk.crossmate.v3") 33 await identity.refresh(using: containerWithNoAccount) 34 // On a simulator/CI with no account, this should stay nil. 35 // We can only assert it doesn't crash; value depends on sim state. 36 _ = identity.currentID 37 } 38 39 @Test("Persists currentID across instances sharing storage") 40 func currentIDPersistsAcrossInstances() { 41 let storage = makeIsolatedStorage() 42 storage.set("_persisted", forKey: "AuthorIdentity.currentID") 43 let identity = AuthorIdentity(storage: storage) 44 #expect(identity.currentID == "_persisted") 45 } 46 } 47 48 /// `AppServices.accountSwitchRequiresPurge` gates the local-store wipe on an 49 /// account-change event. Only a switch between two *known, different* accounts 50 /// should purge. 51 @Suite("Account switch purge gate") 52 @MainActor 53 struct AccountSwitchPurgeTests { 54 55 @Test("Switch to a different account purges") 56 func differentAccountPurges() { 57 #expect(AppServices.accountSwitchRequiresPurge(previousID: "_alice", newID: "_bob")) 58 } 59 60 @Test("Same account does not purge") 61 func sameAccountKeeps() { 62 #expect(!AppServices.accountSwitchRequiresPurge(previousID: "_alice", newID: "_alice")) 63 } 64 65 @Test("First sign-in (no previous ID) does not purge") 66 func firstSignInKeeps() { 67 #expect(!AppServices.accountSwitchRequiresPurge(previousID: nil, newID: "_bob")) 68 } 69 70 @Test("Transient sign-out (no new ID) does not purge") 71 func signOutKeeps() { 72 #expect(!AppServices.accountSwitchRequiresPurge(previousID: "_alice", newID: nil)) 73 } 74 75 @Test("Both unknown does not purge") 76 func bothUnknownKeeps() { 77 #expect(!AppServices.accountSwitchRequiresPurge(previousID: nil, newID: nil)) 78 } 79 }