1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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)
}
}