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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
@testable import Grain
import XCTest
/// Records requests made through `URLSession.shared`.
private final class SharedSessionLog: @unchecked Sendable {
private let lock = NSLock()
private var requests: [URLRequest] = []
func record(_ request: URLRequest) {
lock.withLock { requests.append(request) }
}
var count: Int {
lock.withLock { requests.count }
}
var paths: [String] {
lock.withLock { requests.compactMap(\.url?.path) }
}
var last: URLRequest? {
lock.withLock { requests.last }
}
func queryValue(_ name: String) -> String? {
guard let url = last?.url,
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems
else { return nil }
return items.first { $0.name == name }?.value
}
var lastBody: [String: Any]? {
guard let request = last else { return nil }
var data = request.httpBody
if data == nil, let stream = request.httpBodyStream {
stream.open()
defer { stream.close() }
var collected = Data()
let size = 4096
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
defer { buffer.deallocate() }
while stream.hasBytesAvailable {
let read = stream.read(buffer, maxLength: size)
guard read > 0 else { break }
collected.append(buffer, count: read)
}
data = collected
}
guard let data else { return nil }
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
}
}
/// The calls the app makes outside its injected `XRPCClient` — the geocoder,
/// the Bluesky handle resolver, and push token registration. They reach for
/// `URLSession.shared` directly, so nothing else in the suite exercises them.
///
/// `GrainTestCase` binds `NetworkEnvironment.session` to a mocked session for
/// every test, so these requests are served locally without anything being
/// registered against `URLSession.shared` process-wide.
@MainActor
final class NetworkSideEffectTests: GrainTestCase {
private var log: SharedSessionLog!
private var account: TestAccount!
override func setUp() async throws {
try await super.setUp()
log = SharedSessionLog()
account = TestAccount()
}
override func tearDown() async throws {
MockURLProtocol.handler = nil
account.restore()
try await super.tearDown()
}
private func respond(_ body: String, status: Int = 200) {
let log = log!
MockURLProtocol.handler = { request in
log.record(request)
let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!
return (Data(body.utf8), response)
}
}
// MARK: - Reverse geocoding
private static let nominatimPlace = """
{
"place_id": 1,
"lat": "38.7223",
"lon": "-9.1393",
"name": "Miradouro de Santa Catarina",
"display_name": "Miradouro de Santa Catarina, Lisboa, Portugal",
"address": {"city": "Lisboa", "country": "Portugal", "country_code": "pt", "road": "Rua Marechal Saldanha"}
}
"""
/// A photo's GPS is turned into a place name before it goes on a gallery.
func testReverseGeocodingAPhotoLocation() async {
respond(Self.nominatimPlace)
let result = await LocationServices.reverseGeocode(latitude: 38.7223, longitude: -9.1393)
XCTAssertEqual(log.last?.url?.host, "nominatim.openstreetmap.org")
XCTAssertEqual(log.last?.url?.path, "/reverse")
XCTAssertEqual(log.queryValue("lat"), "38.7223")
XCTAssertEqual(log.queryValue("lon"), "-9.1393")
XCTAssertEqual(log.queryValue("format"), "json")
XCTAssertEqual(result?.name, "Miradouro de Santa Catarina")
}
/// Nominatim asks for a User-Agent and blocks anonymous traffic.
func testGeocodingIdentifiesTheApp() async {
respond(Self.nominatimPlace)
_ = await LocationServices.reverseGeocode(latitude: 0, longitude: 0)
XCTAssertEqual(log.last?.value(forHTTPHeaderField: "User-Agent"), "grain-app/1.0")
}
/// The location row is optional chrome; a geocoder that's down or rate
/// limiting must leave the post-in-progress alone.
func testAFailedGeocodeReturnsNothing() async {
respond("nope", status: 500)
let failed = await LocationServices.reverseGeocode(latitude: 0, longitude: 0)
XCTAssertNil(failed)
respond("not json at all")
let garbage = await LocationServices.reverseGeocode(latitude: 0, longitude: 0)
XCTAssertNil(garbage)
}
// MARK: - Location search
func testSearchingForALocation() async {
respond("[\(Self.nominatimPlace)]")
let results = await LocationServices.searchLocation(query: "Miradouro")
XCTAssertEqual(log.last?.url?.path, "/search")
XCTAssertEqual(log.queryValue("q"), "Miradouro")
XCTAssertEqual(log.queryValue("limit"), "5")
XCTAssertEqual(results.map(\.name), ["Miradouro de Santa Catarina"])
}
/// Typing is debounced into this, so a half-typed query would otherwise
/// send a request per keystroke.
func testATooShortQueryNeverLeavesTheDevice() async {
respond("[]")
let results = await LocationServices.searchLocation(query: " a ")
XCTAssertEqual(log.count, 0)
XCTAssertTrue(results.isEmpty)
}
func testAFailedSearchReturnsNothing() async {
respond("nope", status: 503)
let results = await LocationServices.searchLocation(query: "Lisboa")
XCTAssertTrue(results.isEmpty)
}
/// A result the parser can't make sense of is dropped rather than shown as
/// a blank row.
func testUnparseableSearchResultsAreDropped() async {
respond(#"[{"no_place_id": true}, \#(Self.nominatimPlace)]"#)
let results = await LocationServices.searchLocation(query: "Lisboa")
XCTAssertEqual(results.count, 1)
}
// MARK: - Bluesky handle resolution
/// A mention in a cross-post has to become a DID; Bluesky renders an
/// unresolved one as plain text.
func testAMentionIsResolvedToADID() async {
respond(#"{"did": "did:plc:resolved"}"#)
let facets = await BlueskyPost.parseTextToFacets("Thanks @alice.bsky.social!")
XCTAssertEqual(log.last?.url?.host, "public.api.bsky.app")
XCTAssertEqual(log.queryValue("handle"), "alice.bsky.social")
guard case let .mention(did) = facets.first?.features.first else {
return XCTFail("Expected a mention facet, got \(facets)")
}
XCTAssertEqual(did, "did:plc:resolved")
}
/// A handle that doesn't resolve is left as plain text rather than posted
/// as a link to nobody.
func testAnUnresolvableMentionIsLeftAsPlainText() async {
respond("not found", status: 404)
let facets = await BlueskyPost.parseTextToFacets("Thanks @nobody.bsky.social!")
XCTAssertTrue(facets.isEmpty)
}
func testAResolverThatAnswersWithGarbageIsIgnored() async {
respond("<html>rate limited</html>")
let facets = await BlueskyPost.parseTextToFacets("Thanks @alice.bsky.social!")
XCTAssertTrue(facets.isEmpty)
}
// MARK: - Push token registration
/// APNs hands back a token as raw bytes; the server wants it hex-encoded.
func testTheAPNsTokenIsSentToTheServerAsHex() async {
respond("{}")
let manager = PushManager()
// Held in a local: `PushManager.authManager` is weak, so an inline
// `AuthManager()` would be gone before the token task reads it.
let auth = AuthManager()
manager.configure(authManager: auth)
manager.didRegisterForRemoteNotifications(deviceToken: Data([0xDE, 0xAD, 0xBE, 0xEF]))
await waitForRequest()
XCTAssertEqual(log.paths.last, "/xrpc/social.grain.notification.registerPush")
XCTAssertEqual(log.lastBody?["token"] as? String, "deadbeef")
XCTAssertEqual(log.lastBody?["platform"] as? String, "ios")
XCTAssertEqual(log.lastBody?["serviceDid"] as? String, AuthManager.appviewDID)
XCTAssertEqual(log.lastBody?["appId"] as? String, Bundle.main.bundleIdentifier)
}
/// Signing out has to withdraw the token, or the device keeps getting the
/// previous account's notifications.
func testSigningOutUnregistersTheToken() async {
respond("{}")
let manager = PushManager()
let auth = AuthManager()
manager.configure(authManager: auth)
manager.didRegisterForRemoteNotifications(deviceToken: Data([0x01, 0x02]))
await waitForRequest()
// Deliberately not `try XCTUnwrap(await …)`: swiftformat's hoistAwait
// rule rewrites that into an autoclosure, which can't be async.
guard let context = await auth.authContext() else {
return XCTFail("The signed-in account should have an auth context")
}
await manager.unregisterToken(auth: context)
XCTAssertEqual(log.paths.last, "/xrpc/social.grain.notification.unregisterPush")
XCTAssertEqual(log.lastBody?["token"] as? String, "0102")
XCTAssertEqual(log.lastBody?["platform"] as? String, "ios")
}
/// A registration the server rejects is swallowed — there is nothing the
/// user can do, and it must not take the launch down with it.
func testAFailedRegistrationIsSwallowed() async {
respond("nope", status: 500)
let manager = PushManager()
let auth = AuthManager()
manager.configure(authManager: auth)
manager.didRegisterForRemoteNotifications(deviceToken: Data([0x01]))
await waitForRequest()
XCTAssertEqual(log.paths.last, "/xrpc/social.grain.notification.registerPush")
}
/// The manager only holds its `AuthManager` weakly, so a token arriving
/// after the session has gone must be dropped rather than trapping.
func testATokenArrivingAfterTheSessionIsGoneIsDropped() async {
respond("{}")
let manager = PushManager()
manager.configure(authManager: AuthManager())
manager.didRegisterForRemoteNotifications(deviceToken: Data([0x01]))
await waitForRequest(expecting: 0)
XCTAssertEqual(log.count, 0)
}
/// Without an account there is nobody to register the token for.
func testATokenIsNotRegisteredWithoutASession() async {
respond("{}")
let manager = PushManager()
let auth = AuthManager()
auth.userDID = nil
manager.configure(authManager: auth)
manager.didRegisterForRemoteNotifications(deviceToken: Data([0x01]))
await waitForRequest(expecting: 0)
XCTAssertEqual(log.count, 0)
}
/// `didRegisterForRemoteNotifications` hands off to a detached task, so the
/// request lands a beat after the call returns.
private func waitForRequest(expecting minimum: Int = 1, timeout: TimeInterval = 5) async {
let deadline = Date().addingTimeInterval(timeout)
while log.count < minimum, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
if minimum == 0 {
try? await Task.sleep(for: .milliseconds(200))
}
}
}