import Foundation import UIKit import XCTest @testable import OldFella extension ATProtoServiceTests { func testAppPasswordSignInAndImagePostUseSecureSessionAndBlobUpload() async throws { let fixture = try SecureSessionUploadFixture() fixture.install() defer { fixture.cleanUp() } try await assertSecureSessionSignIn(fixture) let seenAt = Date(timeIntervalSince1970: 1_735_787_045) try await assertSecureSessionSeenAt(fixture, seenAt: seenAt) try await assertSecureSessionNotifications(fixture) try await assertSecureSessionThread(fixture) let imageData = try await assertSecureSessionImageUpload(fixture) let parent = secureSessionParent try await assertSecureSessionReply(fixture, parent: parent) try await assertSecureSessionQuotedReply(fixture, parent: parent, imageData: imageData) try await assertSecureSessionInteractions(fixture, parent: parent) try await assertSecureSessionSignOut(fixture, seenAt: seenAt) } private func assertSecureSessionSignIn(_ fixture: SecureSessionUploadFixture) async throws { let service = fixture.service let account = try await service.signIn( handle: "reader.bsky.social", appPassword: "dedicated-app-password", authFactorToken: nil ) XCTAssertEqual(account.id, "did:plc:reader") XCTAssertEqual(account.displayName, "Reader") let feed = try await service.loadFollowingFeed(cursor: nil) XCTAssertEqual(feed.cursor, "next-page") XCTAssertEqual(feed.mutedPostIDs, ["muted-post", "list-muted-post"]) XCTAssertFalse(feed.mutedPostIDs.contains("muted-repost")) XCTAssertEqual( feed.posts.map(\.id), ["timeline-repost", "timeline-quote", "not-muted-post", "visible-reply", "unavailable-parent"]) XCTAssertEqual(feed.replyContexts["visible-reply"]?.map(\.id), ["root", "parent"]) XCTAssertNil(feed.replyContexts["muted-repost"]) XCTAssertEqual(feed.repostedBy["timeline-repost"]?.id, "did:plc:reader") XCTAssertNil(feed.repostedBy["timeline-quote"]) let loadedProfile = try await service.loadProfile(actorID: "did:plc:reader") let profile = try XCTUnwrap(loadedProfile) XCTAssertTrue(profile.isFollowing) } private func assertSecureSessionSeenAt(_ fixture: SecureSessionUploadFixture, seenAt: Date) async throws { let service = fixture.service try await service.markNotificationsRead(seenAt: seenAt) let seenRequest = try XCTUnwrap( StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/app.bsky.notification.updateSeen" }) XCTAssertEqual(seenRequest.url?.host, "pds.example.test") XCTAssertEqual(seenRequest.httpMethod, "POST") XCTAssertEqual(seenRequest.value(forHTTPHeaderField: "Authorization"), "Bearer \(fixture.token)") XCTAssertEqual(seenRequest.value(forHTTPHeaderField: "atproto-proxy"), "did:web:api.bsky.app#bsky_appview") let seenBody = try XCTUnwrap(StubURLProtocol.recordedBody(for: try XCTUnwrap(seenRequest.url))) let seenObject = try XCTUnwrap(JSONSerialization.jsonObject(with: seenBody) as? [String: Any]) let seenString = try XCTUnwrap(seenObject["seenAt"] as? String) let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] XCTAssertEqual(formatter.date(from: seenString) ?? ISO8601DateFormatter().date(from: seenString), seenAt) do { try await service.markNotificationsRead(seenAt: seenAt) XCTFail("Expected the server error") } catch ServiceError.serverResponse(let code, let message) { XCTAssertEqual(code, "Unavailable") XCTAssertEqual(message, "Try again later") } } private func assertSecureSessionThread(_ fixture: SecureSessionUploadFixture) async throws { let service = fixture.service let thread = try await service.loadPost(uri: "at://did:plc:reader/app.bsky.feed.post/selected") XCTAssertEqual( thread.map(\.id), [ "at://did:plc:reader/app.bsky.feed.post/root", "at://did:plc:reader/app.bsky.feed.post/selected", "at://did:plc:reader/app.bsky.feed.post/reply", "at://did:plc:reader/app.bsky.feed.post/nested" ]) XCTAssertEqual(thread.first?.replyCount, 7) XCTAssertEqual(thread[1].replyCount, 0) let threadRequest = try XCTUnwrap( StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/app.bsky.feed.getPostThread" }) let threadQuery = URLComponents(url: try XCTUnwrap(threadRequest.url), resolvingAgainstBaseURL: false)? .queryItems XCTAssertEqual(threadQuery?.first(where: { $0.name == "depth" })?.value, "1000") XCTAssertEqual(threadQuery?.first(where: { $0.name == "parentHeight" })?.value, "1000") let positionRequest = try XCTUnwrap( StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/app.bsky.unspecced.getPostThreadV2" }) XCTAssertEqual(positionRequest.url?.host, "pds.example.test") XCTAssertEqual(positionRequest.value(forHTTPHeaderField: "Authorization"), "Bearer \(fixture.token)") XCTAssertEqual(positionRequest.value(forHTTPHeaderField: "atproto-proxy"), "did:web:api.bsky.app#bsky_appview") } private func assertSecureSessionReply(_ fixture: SecureSessionUploadFixture, parent: Post) async throws { let service = fixture.service _ = try await service.publish(text: "A reply", replyTo: parent, quotePost: nil, images: []) let replyRecord = try secureSessionLatestRecord("app.bsky.feed.post") XCTAssertEqual(replyRecord["text"] as? String, "A reply") let reply = try XCTUnwrap(replyRecord["reply"] as? [String: Any]) let root = try XCTUnwrap(reply["root"] as? [String: String]) let replyParent = try XCTUnwrap(reply["parent"] as? [String: String]) XCTAssertEqual( root, [ "$type": "com.atproto.repo.strongRef", "uri": "at://did:plc:author/app.bsky.feed.post/root", "cid": "root-cid" ]) XCTAssertEqual(replyParent, ["$type": "com.atproto.repo.strongRef", "uri": parent.id, "cid": "parent-cid"]) } private func assertSecureSessionQuotedReply(_ fixture: SecureSessionUploadFixture, parent: Post, imageData: Data) async throws { let service = fixture.service _ = try await service.publish( text: "A reply with a quote and photo", replyTo: parent, quotePost: parent, images: [ImageAttachment(data: imageData, altText: "A blue photo")]) let quotedReply = try secureSessionLatestRecord("app.bsky.feed.post") XCTAssertEqual(quotedReply["text"] as? String, "A reply with a quote and photo") XCTAssertNotNil(quotedReply["reply"]) let quotedMedia = try XCTUnwrap(quotedReply["embed"] as? [String: Any]) XCTAssertEqual(quotedMedia["$type"] as? String, "app.bsky.embed.recordWithMedia") let quotedRecord = try XCTUnwrap(quotedMedia["record"] as? [String: Any]) XCTAssertEqual(quotedRecord["$type"] as? String, "app.bsky.embed.record") XCTAssertEqual( quotedRecord["record"] as? [String: String], ["$type": "com.atproto.repo.strongRef", "uri": parent.id, "cid": parent.cid]) let quotedImages = try XCTUnwrap(quotedMedia["media"] as? [String: Any]) XCTAssertEqual(quotedImages["$type"] as? String, "app.bsky.embed.images") XCTAssertEqual((quotedImages["images"] as? [[String: Any]])?.first?["alt"] as? String, "A blue photo") } private func assertSecureSessionInteractions(_ fixture: SecureSessionUploadFixture, parent: Post) async throws { let service = fixture.service _ = try await service.toggleLike(post: parent, liked: true) let like = try secureSessionLatestRecord("app.bsky.feed.like") XCTAssertEqual( like["subject"] as? [String: String], ["$type": "com.atproto.repo.strongRef", "uri": parent.id, "cid": "parent-cid"]) _ = try await service.toggleRepost(post: parent, reposted: true) let repost = try secureSessionLatestRecord("app.bsky.feed.repost") XCTAssertEqual( repost["subject"] as? [String: String], ["$type": "com.atproto.repo.strongRef", "uri": parent.id, "cid": "parent-cid"]) _ = try await service.setFollowing(true, actorID: "did:plc:reader") let follow = try secureSessionLatestRecord("app.bsky.graph.follow") XCTAssertEqual(follow["subject"] as? String, "did:plc:reader") } private func assertSecureSessionSignOut(_ fixture: SecureSessionUploadFixture, seenAt: Date) async throws { let service = fixture.service try await service.signOut() StubURLProtocol.clearRequests() do { try await service.markNotificationsRead(seenAt: seenAt) XCTFail("Expected a missing session error") } catch ServiceError.noSession { XCTAssertTrue(StubURLProtocol.recordedRequests.isEmpty) } } private var secureSessionParent: Post { Post( id: "at://did:plc:author/app.bsky.feed.post/parent", cid: "parent-cid", author: Post.Author(id: "did:plc:author", name: "Author", handle: "author.example"), text: "Parent", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyRootURI: "at://did:plc:author/app.bsky.feed.post/root", replyRootCID: "root-cid", replyIDs: []) } private func secureSessionLatestRecord(_ collection: String) throws -> [String: Any] { let request = try XCTUnwrap( StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" }) let body = try XCTUnwrap(StubURLProtocol.recordedBody(for: try XCTUnwrap(request.url))) let object = try XCTUnwrap(JSONSerialization.jsonObject(with: body) as? [String: Any]) XCTAssertEqual(object["repo"] as? String, "did:plc:reader") XCTAssertEqual(object["collection"] as? String, collection) let record = try XCTUnwrap(object["record"] as? [String: Any]) XCTAssertEqual(record["$type"] as? String, collection) XCTAssertNotNil(record["createdAt"] as? String) return record } }