import Observation import XCTest @testable import OldFella extension AppModelTests { func testAvatarRequestsShareAndRetryFailures() async { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [AvatarTestProtocol.self] configuration.urlCache = nil let store = AvatarStore(session: URLSession(configuration: configuration)) let url = URL(string: "https://example.test/avatar")! let before = AvatarTestProtocol.calls.count async let first = store.image(for: url) async let second = store.image(for: url) let images = await (first, second) XCTAssertNotNil(images.0) XCTAssertNotNil(images.1) XCTAssertEqual(AvatarTestProtocol.calls.count - before, 1) let cached = await store.image(for: url) XCTAssertNotNil(cached) XCTAssertTrue(store.cachedImage(for: url) === images.0) let entry = store.cachedAvatar(for: url) XCTAssertNotNil(entry?.ringColors) let reusedEntry = await store.avatar(for: url) XCTAssertTrue(entry === reusedEntry) XCTAssertEqual(AvatarTestProtocol.calls.count - before, 1) store.clear() XCTAssertNil(store.cachedImage(for: url)) let reloaded = await store.image(for: url) XCTAssertNotNil(reloaded) XCTAssertEqual(AvatarTestProtocol.calls.count - before, 2) let errorURL = URL(string: "https://example.test/error")! let failed = await store.image(for: errorURL) let retried = await store.image(for: errorURL) XCTAssertNil(failed) XCTAssertNil(retried) XCTAssertEqual(AvatarTestProtocol.calls.count - before, 4) } func testProfileRequestsShareAndRefresh() async { let gate = ThreadGate() let service = ProfilePostTestService(profileGate: gate) let model = makeAppModel(service: service) let first = Task { await model.loadProfile(actorID: "mae") } await gate.waitUntilStarted() var secondStarted = false var secondFinished = false let second = Task { secondStarted = true await model.loadProfile(actorID: "mae") secondFinished = true } while !secondStarted { await Task.yield() } XCTAssertEqual(service.profileCalls.count, 1) XCTAssertFalse(secondFinished) await gate.release() await first.value await second.value XCTAssertTrue(secondFinished) XCTAssertNotNil(model.profile(actorID: "mae")) await model.loadProfile(actorID: "mae") XCTAssertEqual(service.profileCalls.count, 1) let refresh = Task { await model.loadProfile(actorID: "mae", forceRefresh: true) } await gate.waitUntilStarted() XCTAssertEqual(service.profileCalls.count, 2) await gate.release() await refresh.value } func testForcedProfileRefreshAfterJoiningInitialLoadReloadsAuthorPosts() async { let gate = ThreadGate() let service = ProfilePostTestService(emptyProfileFeedAfterFirst: true, profileGate: gate) let model = makeAppModel(service: service) await model.signIn(handle: "demo", appPassword: "password") let initial = Task { await model.loadProfile(actorID: "mae") } await gate.waitUntilStarted() var forceStarted = false var forceFinished = false let forced = Task { forceStarted = true await model.loadProfile(actorID: "mae", forceRefresh: true) forceFinished = true } while !forceStarted { await Task.yield() } XCTAssertEqual(service.profileCalls.count, 1) XCTAssertFalse(forceFinished) await gate.release() await initial.value for _ in 0..<100 where service.profileCalls.count < 2 && !forceFinished { await Task.yield() } XCTAssertEqual(service.profileCalls.count, 2) if service.profileCalls.count == 2 { await gate.waitUntilStarted() await gate.release() } await forced.value XCTAssertEqual(service.authorProfileCalls.count, 2) XCTAssertTrue(model.posts(for: "mae").isEmpty) XCTAssertNil(model.profileCursors["mae"]) } func testProfileRefreshReplacesPostsCursorAndReposts() async { let reposter = Post.Author(id: "reposter", name: "Reposter", handle: "reposter.test") let service = ProfilePostTestService(emptyProfileFeedAfterFirst: true, initialRepostedBy: ["post-1": reposter]) let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.loadProfile(actorID: "mae") XCTAssertEqual(model.posts(for: "mae").map(\.id), ["post-1"]) XCTAssertNotNil(model.profileCursors["mae"]) XCTAssertEqual(model.profileRepostedBy["mae"]?["post-1"], reposter) await model.loadProfile(actorID: "mae", forceRefresh: true) XCTAssertTrue(model.posts(for: "mae").isEmpty) XCTAssertNil(model.profileCursors["mae"]) XCTAssertTrue(model.profileRepostedBy["mae", default: [:]].isEmpty) XCTAssertEqual(service.authorProfileCalls.count, 2) } func testRetryFailedProfileRefreshLoadsFirstPageWithExistingCursor() async { let service = ProfilePostTestService(emptyProfileFeedAfterFirst: true, failSecondProfilePageRequest: true) let model = makeAppModel(service: service) await model.signIn(handle: "demo", appPassword: "password") await model.loadProfile(actorID: "mae") XCTAssertNotNil(model.profileCursors["mae"]) XCTAssertFalse(model.posts(for: "mae").isEmpty) await model.loadProfile(actorID: "mae", forceRefresh: true) XCTAssertNotNil(model.profileErrors["mae"]) XCTAssertTrue(model.failedProfileRefreshIDs.contains("mae")) XCTAssertNotNil(model.profileCursors["mae"]) await model.retryProfilePosts(actorID: "mae") XCTAssertEqual(service.authorProfileCalls.count, 3) XCTAssertNil(model.profileErrors["mae"]) XCTAssertFalse(model.failedProfileRefreshIDs.contains("mae")) XCTAssertNil(model.profileCursors["mae"]) XCTAssertTrue(model.posts(for: "mae").isEmpty) } func testMissingProfileRefreshReportsErrorAndKeepsPosts() async { let service = ProfilePostTestService(missingProfileAfterFirst: true) let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.loadProfile(actorID: "mae") let posts = model.posts(for: "mae") await model.loadProfile(actorID: "mae", forceRefresh: true) XCTAssertEqual(model.posts(for: "mae"), posts) XCTAssertNil(model.errorMessage) XCTAssertEqual(model.profileErrors["mae"], "This profile could not be found.") } func testFreshProfilePostReplacesCachedQuote() async throws { let base = MockBlueskyService() var fresh = try await base.loadFollowingFeed(cursor: nil).posts.first { $0.id == "post-3" }! XCTAssertNotNil(fresh.quote) fresh.quote = nil let model = makeAppModel(service: ProfilePostTestService(freshProfilePost: fresh)) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") XCTAssertNotNil(model.post(id: "post-3")?.quote) await model.loadProfile(actorID: fresh.author.id) XCTAssertNil(model.post(id: "post-3")?.quote) XCTAssertNil(model.posts(for: fresh.author.id).first { $0.id == "post-3" }?.quote) } func testFreshProfilePageReplacesCachedQuote() async throws { let base = MockBlueskyService() var fresh = try await base.loadFollowingFeed(cursor: nil).posts.first { $0.id == "post-3" }! fresh.quote = nil let model = makeAppModel( service: ProfilePostTestService(freshProfilePost: fresh, freshPostOnlyOnLaterPage: true)) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.loadProfile(actorID: fresh.author.id) XCTAssertNotNil(model.post(id: "post-3")?.quote) await model.loadNextProfilePage(actorID: fresh.author.id) XCTAssertNil(model.post(id: "post-3")?.quote) XCTAssertNil(model.posts(for: fresh.author.id).first { $0.id == "post-3" }?.quote) } func testOlderThreadCannotRestoreMutedPostAndLaterRequestCanRestoreIt() async throws { let base = MockBlueskyService() let original = try await base.loadFollowingFeed(cursor: nil).posts.first { $0.id == "post-1" }! let gate = ThreadGate() let page = FeedPage(posts: [], cursor: nil, mutedPostIDs: [original.id]) let service = ProfilePostTestService( threadResult: ThreadResult(posts: [original], mutedPostIDs: []), refreshedFeed: page, threadGate: gate) let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") let older = Task { await model.loadPost(id: original.id) } await gate.waitUntilStarted() await model.loadFeed() XCTAssertNil(model.post(id: original.id)) await gate.release() await older.value XCTAssertNil(model.post(id: original.id)) let newer = Task { await model.loadPost(id: original.id) } await gate.waitUntilStarted() await gate.release() await newer.value XCTAssertNotNil(model.post(id: original.id)) } func testInvalidatedInitialProfileAndThreadOfferRetry() async { let profileGate = ThreadGate() let threadGate = ThreadGate() let page = FeedPage(posts: [], cursor: nil, mutedPostIDs: ["unrelated"]) let model = makeAppModel( service: ProfilePostTestService(refreshedFeed: page, threadGate: threadGate, profileGate: profileGate)) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") let profile = Task { await model.loadProfile(actorID: "mae") } let thread = Task { await model.loadPost(id: "post-2") } await profileGate.waitUntilStarted() await threadGate.waitUntilStarted() await model.loadFeed() await profileGate.release() await threadGate.release() await profile.value await thread.value XCTAssertNotNil(model.profileErrors["mae"]) XCTAssertTrue(model.failedPostIDs.contains("post-2")) XCTAssertFalse(model.loadingProfileIDs.contains("mae")) XCTAssertFalse(model.loadingPostIDs.contains("post-2")) } }