TeraTodayStoreTests.swift (15821B)
1 @testable import TeraApp 2 import XCTest 3 4 final class TeraTodayStoreTests: XCTestCase { 5 @MainActor 6 func testFrozenPaginationPreservesEqualTimestampCardsWithoutDuplicates() async throws { 7 let context = makeContext(id: "one", label: "One") 8 let first = makeCard(id: "a", type: .update, authoredAt: 1_800_000_000) 9 let second = makeCard(id: "b", type: .ask, authoredAt: 1_800_000_000) 10 let backend = TodayBackend( 11 pages: [ 12 "one:first": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: [first], nextCursor: "same-time", calendar: TeraScopeFixtures.viewerCalendar(asOf: 1_800_000_100)), 13 "one:same-time": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: [first, second], nextCursor: nil, calendar: TeraScopeFixtures.viewerCalendar(asOf: 1_800_000_100)), 14 ] 15 ) 16 let client = try await startedClient(backend: backend) 17 let store = TeraTodayStore( 18 runtimeClient: client, 19 contexts: [context], 20 pageSize: 1, 21 clock: .fixed(unixSeconds: 1_800_000_100) 22 ) 23 24 await store.reload(refreshProjection: false) 25 XCTAssertEqual(store.cards.map(\.id), ["a"]) 26 XCTAssertTrue(store.canLoadNextPage) 27 await store.loadNextPage() 28 29 XCTAssertEqual(store.cards.map(\.id), ["a", "b"]) 30 XCTAssertEqual(store.presentation.content, .available) 31 XCTAssertFalse(store.canLoadNextPage) 32 _ = try await client.stop() 33 } 34 35 @MainActor 36 func testEmptyBoundedProgressRemainsLoadableUntilActualEmptyOrAvailableEOF() async throws { 37 for hasPost in [false, true] { 38 let context = makeContext(id: "one", label: "One") 39 let calendar = TeraScopeFixtures.viewerCalendar(asOf: 1_800_000_100) 40 let backend = TodayBackend(pages: [ 41 "one:first": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: [], nextCursor: "progress1", calendar: calendar), 42 "one:progress1": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: [], nextCursor: "progress2", calendar: calendar), 43 "one:progress2": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: hasPost ? [makeCard(id: "a", type: .update)] : [], nextCursor: nil, calendar: calendar), 44 ]) 45 let client = try await startedClient(backend: backend) 46 let store = TeraTodayStore(runtimeClient: client, contexts: [context], clock: .fixed(unixSeconds: 1_800_000_100)) 47 await store.reload(refreshProjection: false) 48 XCTAssertEqual(store.presentation.content, .notLoaded) 49 XCTAssertTrue(store.canLoadNextPage) 50 XCTAssertTrue(store.hasMorePages) 51 await store.loadNextPage() 52 XCTAssertEqual(store.presentation.content, .notLoaded) 53 XCTAssertTrue(store.canLoadNextPage) 54 await store.loadNextPage() 55 XCTAssertEqual(store.presentation.content, hasPost ? .available : .empty) 56 XCTAssertFalse(store.hasMorePages) 57 XCTAssertEqual(store.cards.count, hasPost ? 1 : 0) 58 _ = try await client.stop() 59 } 60 } 61 62 @MainActor 63 func testContextSwitchRejectsLateCancelledContextResult() async throws { 64 let firstContext = makeContext(id: "slow", label: "Slow") 65 let secondContext = makeContext(id: "current", label: "Current") 66 let stale = makeCard(id: "stale", type: .update) 67 let current = makeCard(id: "current", type: .photoUpdate) 68 let backend = TodayBackend( 69 pages: [ 70 "slow:first": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: [stale], nextCursor: nil, calendar: TeraScopeFixtures.viewerCalendar(asOf: 1_800_000_100)), 71 "current:first": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: [current], nextCursor: nil, calendar: TeraScopeFixtures.viewerCalendar(asOf: 1_800_000_100)), 72 ], 73 delays: ["slow": 80_000_000] 74 ) 75 let client = try await startedClient(backend: backend) 76 let store = TeraTodayStore( 77 runtimeClient: client, 78 contexts: [firstContext, secondContext], 79 clock: .fixed(unixSeconds: 1_800_000_100) 80 ) 81 82 let staleRequest = Task { await store.reload(refreshProjection: false) } 83 try await Task.sleep(nanoseconds: 2_000_000) 84 store.selectContext(id: "current") 85 await staleRequest.value 86 try await Task.sleep(nanoseconds: 20_000_000) 87 88 XCTAssertEqual(store.selectedContextID, "current") 89 XCTAssertEqual(store.cards.map(\.id), ["current"]) 90 _ = try await client.stop() 91 } 92 93 @MainActor 94 func testFiveCardsExposeProfileThreadMediaOverlayAndAccessibleProductFields() { 95 let profile = TeraProfileSummary( 96 authorPublicKey: String(repeating: "a", count: 64), 97 name: "fieldnotes", 98 displayName: "Field Notes Farm", 99 about: nil, 100 picture: nil, 101 banner: nil, 102 nip05: "farm@example.com", 103 website: nil, 104 lightningAddress: nil 105 ) 106 let failedMedia = TeraMediaReference( 107 referenceFingerprint: String(repeating: "d", count: 64), 108 url: "https://blossom.example/\(String(repeating: "b", count: 64))", 109 sha256: String(repeating: "b", count: 64), 110 mediaType: "image/jpeg", 111 width: 1200, 112 height: 800, 113 byteSize: 400, 114 alt: "Carrots in a basket", 115 verification: .failed 116 ) 117 let thread = TeraThreadEntry( 118 id: "reply", 119 authorPublicKey: String(repeating: "c", count: 64), 120 content: "Are these available Saturday?", 121 authoredAtUnixSeconds: 1_800_000_001, 122 type: .reply, 123 root: "root", 124 parentEventID: "root", 125 authorProfile: nil 126 ) 127 let cards = TeraTodayCardType.allCases.map { type in 128 makeCard( 129 id: type.rawValue, 130 type: type, 131 profile: profile, 132 media: type == .photoUpdate ? [failedMedia] : [], 133 thread: type == .ask ? [thread] : [], 134 localState: type == .foodAvailability ? "partially_delivered" : nil 135 ) 136 } 137 138 XCTAssertEqual(cards.map(\.type), TeraTodayCardType.allCases) 139 XCTAssertEqual(cards[1].media.first?.verifiedArtifactID, nil) 140 XCTAssertEqual(cards[2].thread.first?.type, .reply) 141 XCTAssertEqual(cards[4].priceSummary, "3 CAD/lb") 142 XCTAssertEqual(cards[4].quantity, "12") 143 XCTAssertTrue(cards[4].accessibilitySummary.contains("Food availability")) 144 XCTAssertTrue(cards[4].accessibilitySummary.contains("Field Notes Farm")) 145 XCTAssertTrue(cards[4].accessibilitySummary.contains("partially_delivered")) 146 } 147 148 @MainActor 149 func testStorageRefreshFailureKeepsCachedFeedWithoutClaimingOffline() async throws { 150 try await assertCachedRefreshFailure( 151 code: "today_storage_failed", 152 expected: .failed(message: TeraUserMessages.text(.secureStateUnavailable)) 153 ) 154 } 155 156 @MainActor 157 func testOfflineRefreshStillLoadsTheDurableCachedFeed() async throws { 158 try await assertCachedRefreshFailure( 159 code: "today_relay_offline", 160 expected: .offline(message: TeraUserMessages.text(.networkUnavailable)) 161 ) 162 } 163 164 @MainActor 165 func testOfflineRefreshStillShowsTheGenuineEmptyLocalPage() async throws { 166 try await assertCachedRefreshFailure( 167 code: "today_relay_offline", 168 expected: .offline(message: TeraUserMessages.text(.networkUnavailable)), 169 hasCachedCards: false 170 ) 171 } 172 173 @MainActor 174 private func assertCachedRefreshFailure( 175 code: String, expected: TeraTodayFailure, hasCachedCards: Bool = true 176 ) async throws { 177 let context = makeContext(id: "offline", label: "Offline") 178 let cached = makeCard(id: "cached", type: .update) 179 let failure = TeraRuntimeFailure( 180 schemaVersion: 1, 181 code: code, 182 category: "relay", 183 retryable: true, 184 recoveryActions: ["retry"], 185 operationID: "test.today.refresh", 186 capabilityID: "nostr_source", 187 safeMessage: "Saved posts are available offline." 188 ) 189 let backend = TodayBackend( 190 pages: [ 191 "offline:first": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: hasCachedCards ? [cached] : [], nextCursor: hasCachedCards ? "cached-next" : nil, calendar: TeraScopeFixtures.viewerCalendar(asOf: 1_800_000_100)), 192 "offline:cached-next": TeraTodayPage(asOfUnixSeconds: 1_800_000_100, items: [makeCard(id: "cached-next", type: .ask)], nextCursor: nil, calendar: TeraScopeFixtures.viewerCalendar(asOf: 1_800_000_100)), 193 ], 194 refreshFailure: failure 195 ) 196 let client = try await startedClient(backend: backend) 197 let store = TeraTodayStore( 198 runtimeClient: client, 199 contexts: [context], 200 clock: .fixed(unixSeconds: 1_800_000_100) 201 ) 202 203 await store.reload() 204 205 XCTAssertEqual(store.cards.map(\.id), hasCachedCards ? ["cached"] : []) 206 XCTAssertEqual(store.presentation.content, hasCachedCards ? .available : .empty) 207 XCTAssertEqual(store.presentation.refresh, .failed(expected)) 208 await store.loadNextPage() 209 XCTAssertEqual(store.cards.map(\.id), hasCachedCards ? ["cached", "cached-next"] : []) 210 XCTAssertEqual(store.presentation.content, hasCachedCards ? .available : .empty) 211 XCTAssertEqual(store.presentation.refresh, .failed(expected)) 212 _ = try await client.stop() 213 } 214 215 @MainActor 216 private func startedClient(backend: TodayBackend) async throws -> TeraRuntimeClient { 217 let client = TeraRuntimeClient { _ in 218 await TeraRuntimeBackendStart(backend: backend, snapshot: backend.snapshot()) 219 } 220 _ = try await client.start(configuration: makeConfiguration()) 221 return client 222 } 223 224 private func makeConfiguration() -> TeraRuntimeLaunchConfiguration { 225 TeraRuntimeLaunchConfiguration( 226 applicationSupportDirectory: "/tmp/radroots-today-tests", 227 publicKeyHex: String(repeating: "ab", count: 32), 228 sourceGenerationHex: String(repeating: "cd", count: 32), 229 sourceGenerationCreatedAtUnixMilliseconds: 1, 230 protectedData: .available, 231 networkProfile: .simulator, 232 writableRelays: ["ws://127.0.0.1:7447"], 233 blossom: TeraBlossomEndpointConfiguration( 234 hostKind: .simulator, 235 endpointAuthority: .loopbackDevelopment, 236 primaryOrigin: "http://127.0.0.1:3000", 237 fallbackOrigins: [] 238 ), 239 app: TeraRuntimeAppMetadata( 240 bundleIdentifier: "org.radroots.today-tests", 241 version: "0.1.0-alpha", 242 buildNumber: "1", 243 buildSHA: nil 244 ), 245 signerGeneration: "today-tests", 246 signer: TodayTestSigner(), 247 adoptBootstrapSettings: false 248 ) 249 } 250 } 251 252 private func makeContext(id: String, label: String) -> TeraLocalNetwork { 253 TeraLocalNetwork( 254 schemaVersion: 1, 255 id: id, 256 label: label, 257 relayURLs: ["ws://127.0.0.1:7447"], 258 locality: nil, 259 followedAuthors: [], 260 generation: 1 261 ) 262 } 263 264 private func makeCard( 265 id: String, 266 type: TeraTodayCardType, 267 authoredAt: UInt64 = 1_800_000_000, 268 profile: TeraProfileSummary? = nil, 269 media: [TeraMediaReference] = [], 270 thread: [TeraThreadEntry] = [], 271 localState: String? = nil 272 ) -> TeraTodayCard { 273 TeraTodayCard( 274 id: id, 275 type: type, 276 sourceEventID: "event-\(id)", 277 sourceAddress: type == .event || type == .foodAvailability ? "address-\(id)" : nil, 278 authorPublicKey: String(repeating: "a", count: 64), 279 contractID: "contract-\(type.rawValue)", 280 title: type == .event ? "Saturday market" : type == .foodAvailability ? "Carrots" : nil, 281 content: type == .ask ? "Who has seedlings?" : "Fresh from the field", 282 authoredAtUnixSeconds: authoredAt, 283 effectiveAtUnixSeconds: authoredAt, 284 calendarTiming: type == .event ? .timeBased( 285 startUnixSeconds: authoredAt + 3600, endExclusiveUnixSeconds: nil, 286 startTimezoneID: nil, endTimezoneID: nil 287 ) : nil, 288 location: type == .event || type == .foodAvailability ? "Town square" : nil, 289 priceAmount: type == .foodAvailability ? "3" : nil, 290 priceCurrency: type == .foodAvailability ? "CAD" : nil, 291 priceUnit: type == .foodAvailability ? "lb" : nil, 292 quantity: type == .foodAvailability ? "12" : nil, 293 foodSummary: type == .foodAvailability ? "Fresh carrots" : nil, 294 foodPublishedAtUnixSeconds: type == .foodAvailability ? authoredAt : nil, 295 foodStatus: type == .foodAvailability ? "active" : nil, 296 contextRank: 1, 297 inclusionReason: "locality_missing_fallback", 298 media: media, 299 lifecycle: .active, 300 rankDigest: "rank-\(id)", 301 authorProfile: profile, 302 thread: thread, 303 threadNextCursor: nil, 304 localOperationID: localState == nil ? nil : "operation-\(id)", 305 localOperationState: localState 306 ) 307 } 308 309 private struct TodayTestSigner: TeraRuntimeSigner { 310 func availability() async -> TeraRuntimeSignerAvailability { 311 .ready 312 } 313 314 func sign(_: TeraRuntimeSigningRequest) async -> TeraRuntimeSigningOutcome { 315 .failed 316 } 317 } 318 319 private actor TodayBackend: TeraRuntimeBackend { 320 private let pages: [String: TeraTodayPage] 321 private let delays: [String: UInt64] 322 private let refreshFailure: TeraRuntimeFailure? 323 private var closed = false 324 325 init( 326 pages: [String: TeraTodayPage], 327 delays: [String: UInt64] = [:], 328 refreshFailure: TeraRuntimeFailure? = nil 329 ) { 330 self.pages = pages 331 self.delays = delays 332 self.refreshFailure = refreshFailure 333 } 334 335 func snapshot() -> TeraRuntimeSnapshot { 336 TeraRuntimeSnapshot( 337 identity: TeraRuntimeIdentity( 338 publicKeyHex: String(repeating: "ab", count: 32), 339 hostSignerConfigured: true 340 ), 341 relay: nil, 342 blossomConfiguration: nil, 343 blossomEvidence: nil, 344 crateName: "tera_ffi", 345 crateVersion: "0.1.0-alpha", 346 isClosed: closed 347 ) 348 } 349 350 func todayPage(request: TeraTodayPageRequest) async throws -> TeraTodayPage { 351 if let delay = delays[request.context.id] { 352 try await Task.sleep(nanoseconds: delay) 353 } 354 let key = "\(request.context.id):\(request.cursor ?? "first")" 355 guard let page = pages[key] else { 356 throw TeraRuntimeFailure.local( 357 operation: "test.today.page", 358 code: "test.page_missing", 359 safeMessage: "The requested test page is missing." 360 ) 361 } 362 return page 363 } 364 365 func refreshToday( 366 context _: TeraLocalNetwork, 367 nowUnixSeconds _: UInt64, 368 update: TeraTodayProjectionUpdate, 369 backfillCursor _: String? 370 ) throws -> TeraTodaySyncReceipt { 371 if let refreshFailure { 372 throw refreshFailure 373 } 374 return TeraTodaySyncFixtures.receipt(update: update) 375 } 376 377 func subscribe( 378 bufferCapacity _: Int, 379 receive _: @escaping @Sendable (TeraRuntimeChange) async -> Void 380 ) -> any TeraRuntimeSubscriptionToken { 381 TodaySubscriptionToken() 382 } 383 384 func shutdown() -> TeraRuntimeShutdownReceipt { 385 let alreadyClosed = closed 386 closed = true 387 return TeraRuntimeShutdownReceipt(state: "closed", alreadyClosed: alreadyClosed) 388 } 389 } 390 391 private actor TodaySubscriptionToken: TeraRuntimeSubscriptionToken { 392 func cancel() {} 393 }