import Foundation import XCTest @testable import OldFella final class SearchServiceTests: XCTestCase { func testMockAccountSearchPaginatesAndFilters() async throws { let service = MockBlueskyService() let first = try await service.searchAccounts(query: "EXAMPLE", cursor: nil) let second = try await service.searchAccounts(query: "EXAMPLE", cursor: first.cursor) let third = try await service.searchAccounts(query: "EXAMPLE", cursor: second.cursor) XCTAssertEqual(first.accounts.map(\.id), ["mae"]) XCTAssertEqual(first.accounts.first?.bio, service.profiles[0].bio) XCTAssertEqual(second.accounts.map(\.id), ["alex"]) XCTAssertEqual(third.accounts.map(\.id), ["sam"]) XCTAssertNil(third.cursor) let empty = try await service.searchAccounts(query: "no such account", cursor: nil) XCTAssertTrue(empty.accounts.isEmpty) XCTAssertNil(empty.cursor) } private final class SearchURLProtocol: URLProtocol { static var handler: ((URLRequest) -> Data)? static var statusCode = 200 override static func canInit(with request: URLRequest) -> Bool { true } override static func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { guard let handler = Self.handler, let url = request.url, let response = HTTPURLResponse( url: url, statusCode: Self.statusCode, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": "application/json"]) else { client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse) return } let data = handler(request) client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: data) client?.urlProtocolDidFinishLoading(self) } override func stopLoading() {} } func testMockPostSearchFiltersBeforePagination() async throws { let service = MockBlueskyService() let first = try await service.searchPosts(query: "the", cursor: nil) let second = try await service.searchPosts(query: "the", cursor: first.cursor) let filtered = try await service.searchPosts(query: "the", cursor: nil, authorID: "alex") let missing = try await service.searchPosts(query: "the", cursor: nil, authorID: "missing") XCTAssertEqual(first.posts.map(\.id), ["post-1"]) XCTAssertEqual(second.posts.map(\.id), ["post-2"]) XCTAssertEqual(filtered.posts.map(\.id), ["post-2"]) XCTAssertNil(filtered.cursor) XCTAssertTrue(missing.posts.isEmpty) XCTAssertNil(missing.cursor) } func testLiveSearchForwardsQueryAndCursor() async throws { let suite = "SearchService.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [SearchURLProtocol.self] let session = URLSession(configuration: configuration) let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "") let token = "header.\(payload).signature" var requestedPaths: [String] = [] SearchURLProtocol.handler = { requestedPaths.append($0.url?.path ?? "") return self.searchResponse($0, token: token) } defer { SearchURLProtocol.handler = nil SearchURLProtocol.statusCode = 200 session.invalidateAndCancel() defaults.removePersistentDomain(forName: suite) } let service = ATProtoBlueskyService(defaults: defaults, session: session) _ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil) requestedPaths.removeAll() let accounts = try await service.searchAccounts(query: "birds & trees", cursor: "next/+ cursor") XCTAssertEqual(requestedPaths, ["/xrpc/app.bsky.actor.searchActors"]) XCTAssertEqual(accounts.accounts.first?.bio, "Birds, trees, and quiet walks.") let posts = try await service.searchPosts( query: "birds & trees", cursor: "next/+ cursor", authorID: "did:plc:author") XCTAssertEqual(accounts.accounts.map(\.id), ["did:plc:visible"]) XCTAssertEqual(accounts.cursor, "server-next") XCTAssertEqual(posts.cursor, "server-next") let suggestions = try await service.suggestAccounts(query: "al") XCTAssertEqual(suggestions.map(\.id), ["did:plc:visible"]) SearchURLProtocol.statusCode = 503 do { _ = try await service.suggestAccounts(query: "al") XCTFail("Expected a server error") } catch ServiceError.requestFailed {} catch { XCTFail("Unexpected error: \(error)") } } func testLiveSearchRequiresSession() async throws { let service = ATProtoBlueskyService() do { _ = try await service.suggestAccounts(query: "example") XCTFail("Expected an error") } catch ServiceError.noSession {} catch { XCTFail("Unexpected error: \(error)") } do { _ = try await service.searchAccounts(query: "example", cursor: nil) XCTFail("Expected an error") } catch ServiceError.noSession {} catch { XCTFail("Unexpected error: \(error)") } do { _ = try await service.searchPosts(query: "example", cursor: nil) XCTFail("Expected an error") } catch ServiceError.noSession {} catch { XCTFail("Unexpected error: \(error)") } } func testAccountSearchPreservesMissingAndBlankBios() async throws { let service = ATProtoBlueskyService() let accounts = try await service.accountSummaries(from: [ "actors": [ ["did": "missing-bio", "handle": "missing.example"], ["did": "blank-bio", "handle": "blank.example", "description": " \n "] ] ], key: "actors") XCTAssertEqual(accounts.map(\.id), ["missing-bio", "blank-bio"]) XCTAssertNil(accounts[0].bio) XCTAssertEqual(accounts[1].bio, " \n ") } private func searchResponse(_ request: URLRequest, token: String) -> Data { switch request.url?.path { case "/xrpc/com.atproto.identity.resolveHandle": return Data("{\"did\":\"did:plc:reader\"}".utf8) case "/did:plc:reader": return Data( ("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\"," + "\"type\":\"AtprotoPersonalDataServer\"," + "\"serviceEndpoint\":\"https://reader.example.test\"}]}") .utf8) case "/xrpc/com.atproto.server.createSession": return Data( ("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\"," + "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}") .utf8) case "/xrpc/app.bsky.actor.getProfile": return Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8) case "/xrpc/app.bsky.actor.searchActorsTypeahead": XCTAssertEqual(request.url?.host, "reader.example.test") XCTAssertEqual(request.value(forHTTPHeaderField: "atproto-proxy"), "did:web:api.bsky.app#bsky_appview") XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer \(token)") let items = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems XCTAssertEqual(items?.first { $0.name == "q" }?.value, "al") XCTAssertEqual(items?.first { $0.name == "limit" }?.value, "10") XCTAssertNil(items?.first { $0.name == "cursor" }) return typeaheadResponse() case "/xrpc/app.bsky.actor.searchActors", "/xrpc/app.bsky.feed.searchPosts": let items = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems XCTAssertEqual(items?.first { $0.name == "q" }?.value, "birds & trees") XCTAssertEqual(items?.first { $0.name == "cursor" }?.value, "next/+ cursor") if request.url!.path.hasSuffix("searchActors") { return Data( (#"{"actors":[{"did":"did:plc:visible","handle":"visible.test","# + #""description":"Birds, trees, and quiet walks."},"# + #"{"did":"did:plc:muted","handle":"muted.test","viewer":{"muted":true}},"# + #"{"did":"did:plc:blocked","handle":"blocked.test","viewer":{"blockedBy":true}}],"# + #""cursor":"server-next"}"#) .utf8) } XCTAssertEqual(items?.first { $0.name == "sort" }?.value, "latest") XCTAssertEqual(items?.first { $0.name == "author" }?.value, "did:plc:author") return Data("{\"posts\":[],\"cursor\":\"server-next\"}".utf8) default: XCTFail("Unexpected request: \(String(describing: request.url))") return Data("{}".utf8) } } private func typeaheadResponse() -> Data { let json = [ #"{"actors":[{"did":"did:plc:visible","handle":"visible.test","#, #""displayName":"Visible","associated":{"chat":{"allowIncoming":"all","#, #""allowGroupInvites":"all"},"#, #""activitySubscription":{"allowSubscriptions":"followers"}},"labels":[],"#, #""createdAt":"2024-09-10T21:35:42.823Z","indexedAt":"2026-10-27T21:00:26.812Z"},"#, #"{"did":"did:plc:muted","handle":"muted.test","viewer":{"muted":true}},"#, #"{"did":"did:plc:blocked","handle":"blocked.test","viewer":{"blockedBy":true}}]}"# ].joined() return Data(json.utf8) } }