import Observation import XCTest @testable import OldFella extension AppModelTests { func testDiscardingUncertainDraftAllowsNewPost() async { let service = ActionFailureTestService() let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") let key = ComposerDraftKey(replyTo: nil, quotePostID: nil) let image = ImageAttachment(data: Data([1, 2, 3]), altText: "A boat", mimeType: "image/jpeg") let failed = await model.publish(text: "Original", images: [image]) XCTAssertFalse(failed) XCTAssertTrue(model.uncertainDraftKeys.contains(key)) model.discardUncertainDraft(for: key) XCTAssertFalse(model.uncertainDraftKeys.contains(key)) let succeeded = await model.publish(text: "A different post") XCTAssertTrue(succeeded) XCTAssertEqual(service.publishedTexts, ["Original", "A different post"]) } func testSignOutClearsUncertainActionsAndDrafts() async { let service = ActionFailureTestService() let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.toggleLike(postID: "post-1") await model.toggleFollow(actorID: "mae") _ = await model.publish(text: "Original") XCTAssertFalse(model.uncertainPostIDs.isEmpty) XCTAssertFalse(model.uncertainFollowIDs.isEmpty) XCTAssertFalse(model.uncertainDraftKeys.isEmpty) await model.signOut() await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") XCTAssertTrue(model.uncertainPostIDs.isEmpty) XCTAssertTrue(model.uncertainFollowIDs.isEmpty) XCTAssertTrue(model.uncertainDraftKeys.isEmpty) } func testDelayedActionsDoNotChangeNextSession() async { let service = ActionFailureTestService() service.actionDelay = 200_000_000 service.followDelay = 200_000_000 service.publishDelay = 200_000_000 service.failActions = false let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") let like = Task { await model.toggleLike(postID: "post-1") } let repost = Task { await model.toggleRepost(postID: "post-2") } let follow = Task { await model.toggleFollow(actorID: "mae") } let publish = Task { await model.publish(text: "Old session") } while service.likeCalls == 0 || service.repostCalls == 0 || service.followCalls == 0 || service.publishedTexts.isEmpty { await Task.yield() } await model.signOut() await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") let original = model.posts await like.value await repost.value await follow.value let result = await publish.value XCTAssertFalse(result) XCTAssertEqual(model.posts, original) XCTAssertFalse(model.followingActorIDs.contains("mae")) XCTAssertNil(model.errorMessage) XCTAssertFalse(model.isPublishing) } func testKnownFailureAllowsRetry() async { let service = ActionFailureTestService() service.likeFailure = ActionNotSentError(underlying: ServiceError.invalidResponse) service.followFailure = ActionNotSentError(underlying: ServiceError.invalidResponse) service.publishFailure = ActionNotSentError(underlying: ServiceError.invalidUploadResponse) let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.toggleLike(postID: "post-1") await model.toggleFollow(actorID: "mae") let failed = await model.publish(text: "A post") XCTAssertFalse(failed) XCTAssertTrue(model.uncertainPostIDs.isEmpty) XCTAssertTrue(model.uncertainFollowIDs.isEmpty) XCTAssertTrue(model.uncertainDraftKeys.isEmpty) await model.toggleLike(postID: "post-1") await model.toggleFollow(actorID: "mae") let succeeded = await model.publish(text: "A post") XCTAssertTrue(succeeded) XCTAssertEqual(service.likeCalls, 2) XCTAssertEqual(service.followCalls, 2) XCTAssertEqual(service.publishedTexts.count, 2) } func testGIFDecoderRejectsOversizedDimensions() throws { var data = try XCTUnwrap( Data( base64Encoded: "R0lGODlhAQABAIAAAAAAAP///yH5BAAAAAAALAAAAAABAAEAAAIBRAAh+QQAAAAAACwAAAAAAQABAAACAUQAOw==")) XCTAssertTrue(RemoteImageDecoder.isGIF(data)) XCTAssertFalse(RemoteImageDecoder.isGIF(Data([0x89, 0x50, 0x4e, 0x47]))) XCTAssertNotNil(RemoteImageDecoder.decode(data)) data[6] = 0xff data[7] = 0x7f data[8] = 0xff data[9] = 0x7f XCTAssertNil(RemoteImageDecoder.decode(data)) } func testDownloadSizeLimitAppliesOnlyToGIFs() throws { var data = Data(repeating: 0, count: GIFDownload.byteLimit + 1) XCTAssertNoThrow(try GIFDownload.validate(data)) data.replaceSubrange(0..<6, with: Data("GIF89a".utf8)) XCTAssertThrowsError(try GIFDownload.validate(data)) data.removeLast() XCTAssertNoThrow(try GIFDownload.validate(data)) } func testChunkedDownloadLimitsGIFWithoutLimitingOtherImages() throws { var gif = ImageDownloadBuffer() try gif.append(Data("GIF".utf8)) try gif.append(Data("89a".utf8)) try gif.append(Data(repeating: 0, count: GIFDownload.byteLimit - 6)) XCTAssertThrowsError(try gif.append(Data([0]))) XCTAssertEqual(gif.data.count, GIFDownload.byteLimit) var image = ImageDownloadBuffer() try image.append(Data([0x89, 0x50, 0x4e, 0x47])) try image.append(Data(repeating: 0, count: GIFDownload.byteLimit)) XCTAssertEqual(image.data.count, GIFDownload.byteLimit + 4) try image.append(Data(repeating: 0, count: GIFDownload.imageByteLimit - image.data.count)) XCTAssertThrowsError(try image.append(Data([0]))) { error in XCTAssertEqual(error as? ImageDownloadError, .imageTooLarge) } XCTAssertEqual(image.data.count, GIFDownload.imageByteLimit) } func testDownloadRejectsHTTPError() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [ImageTestProtocol.self] do { _ = try await GIFDownload.load(URL(string: "https://example.test/error")!, configuration: configuration) XCTFail("Expected an HTTP error") } catch let error as ImageDownloadError { XCTAssertEqual(error, .httpStatus(503)) } } func testDownloadEnforcesLimitWithoutContentLength() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [ImageTestProtocol.self] do { _ = try await GIFDownload.load(URL(string: "https://example.test/gif")!, configuration: configuration) XCTFail("Expected a GIF size error") } catch let error as ImageDownloadError { XCTAssertEqual(error, .gifTooLarge) } } func testDownloadCancellation() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [ImageTestProtocol.self] let task = Task { try await GIFDownload.load(URL(string: "https://example.test/wait")!, configuration: configuration) } task.cancel() do { _ = try await task.value XCTFail("Expected cancellation") } catch is CancellationError { } catch let error as URLError { XCTAssertEqual(error.code, .cancelled) } } func testMediaDestinations() { XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/photo.JPG")!), .image) XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/clip.gif?size=1")!), .gif) XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/movie.mp4")!), .video) XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/article")!), .ordinaryLink) } func testQuotePostKeepsOriginalPostLinkTarget() async { let model = makeAppModel(service: MockBlueskyService()) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") let quote = model.post(id: "post-3")?.quote XCTAssertEqual(quote?.postID, "post-2") } func testMockProfilesHaveDetailsAndTheirPosts() async { let model = makeAppModel(service: MockBlueskyService()) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.loadProfile(actorID: "mae") let profile = model.profile(actorID: "mae") XCTAssertEqual(profile?.author.name, "Mae Rivers") XCTAssertEqual(profile?.location, "Portland, OR") XCTAssertEqual(model.posts(for: "mae").map(\.id), ["post-1"]) XCTAssertNil(model.profile(actorID: "unknown")) } func testSuccessfulEmptyProfileFeedIsStoredAsEmptyWithoutError() async { let model = makeAppModel(service: ProfilePostTestService(returnsEmptyProfileFeed: true)) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.loadProfile(actorID: "mae") XCTAssertNotNil(model.profile(actorID: "mae")) XCTAssertEqual(model.authorPosts["mae"], []) XCTAssertNil(model.profileErrors["mae"]) } func testProfileRetriesAuthorFeedAfterHeaderLoads() async { let service = MockBlueskyService(failsFirstAuthorFeedLoad: true) let model = makeAppModel(service: service) await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") await model.loadProfile(actorID: "mae") XCTAssertEqual(model.profile(actorID: "mae")?.author.name, "Mae Rivers") XCTAssertNil(model.authorPosts["mae"]) XCTAssertNotNil(model.profileErrors["mae"]) XCTAssertNil(model.errorMessage) await model.loadProfile(actorID: "mae") XCTAssertEqual(model.profile(actorID: "mae")?.author.name, "Mae Rivers") XCTAssertEqual(model.posts(for: "mae").map(\.id), ["post-1"]) XCTAssertNil(model.profileErrors["mae"]) XCTAssertNil(model.errorMessage) XCTAssertEqual(service.authorFeedLoadCount, 2) } }