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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
@testable import Grain
import XCTest
/// File scope, not a static member: `MockURLProtocol.handler` runs outside the
/// main actor, so anything it reads has to live outside a @MainActor class.
private func galleryJSON(
_ id: Int,
creator: String = "did:plc:someone",
photos: Int = 1,
thumb: String = "https://test.local/thumb.jpg"
) -> String {
let items = (0 ..< photos).map { index in
"""
{
"uri": "at://\(creator)/social.grain.photo/\(id)-\(index)",
"cid": "bafyp\(id)\(index)",
"thumb": "\(thumb)",
"fullsize": "https://test.local/full.jpg",
"aspectRatio": {"width": 3, "height": 2}
}
"""
}.joined(separator: ",")
return """
{
"uri": "at://\(creator)/social.grain.gallery/\(id)",
"cid": "bafyg\(id)",
"title": "Gallery \(id)",
"creator": {"cid": "c1", "did": "\(creator)", "handle": "someone.test"},
"items": [\(items)],
"indexedAt": "2025-01-02T00:00:00Z"
}
"""
}
private func feedJSON(_ galleries: [String], cursor: String?) -> String {
let cursorJSON = cursor.map { "\"\($0)\"" } ?? "null"
return "{\"items\": [\(galleries.joined(separator: ","))], \"cursor\": \(cursorJSON)}"
}
private func profileJSON(viewer: String = "{}") -> String {
"""
{
"cid": "bafycid",
"did": "did:plc:someone",
"handle": "someone.test",
"displayName": "Someone",
"followersCount": 10,
"followsCount": 5,
"galleryCount": 2,
"viewer": \(viewer)
}
"""
}
/// The favorites tab and the block/mute actions on a profile. Favorites are the
/// fiddly half: they're cached to disk, paged, and filtered — a gallery whose
/// thumbnail can't load would otherwise sit as a permanent blank tile.
@MainActor
final class ProfileFavoritesAndModerationTests: GrainTestCase {
private var client: XRPCClient!
private var vm: ProfileDetailViewModel!
private var auth: AuthContext!
private var did = ""
private var savedAccount: String?
override func setUp() async throws {
try await super.setUp()
did = "did:plc:profilevm-\(UUID().uuidString)"
// The favorites cache files entries under the active account; pointing
// that at a synthetic DID keeps this out of the installed app's cache.
savedAccount = AccountScopedStorage.activeAccountID
AccountScopedStorage.activeAccountID = did
client = XRPCClient(baseURL: URL(string: "https://test.local")!, session: MockURLProtocol.mockSession())
vm = ProfileDetailViewModel(client: client)
auth = try AuthContext(accessToken: "token", dpop: DPoP.loadOrCreate(for: did), did: did, pds: URL(string: "https://test.local")!)
}
override func tearDown() async throws {
MockURLProtocol.handler = nil
FeedCache.shared.purge(did: did)
AccountScopedStorage.activeAccountID = savedAccount
try? DPoP.clearKey(for: did)
try await super.tearDown()
}
// MARK: - Favorites hydration
/// A favorited gallery whose photos are gone renders as a blank tile
/// forever, because there is no image for the loader to even attempt.
func testFavoritesWithNoPhotosAreDropped() async {
MockURLProtocol.respondWithJSON(feedJSON([
galleryJSON(1),
galleryJSON(2, photos: 0),
], cursor: nil))
await vm.loadFavorites(did: "did:plc:someone")
XCTAssertEqual(vm.favoriteGalleries.map(\.title), ["Gallery 1"])
}
/// Same for a thumbnail URL that's empty or that `URL` won't parse — the
/// loader can't start, so the tile never fills in.
func testFavoritesWithAnUnusableThumbnailAreDropped() async {
MockURLProtocol.respondWithJSON(feedJSON([
galleryJSON(1),
galleryJSON(2, thumb: ""),
], cursor: nil))
await vm.loadFavorites(did: "did:plc:someone")
XCTAssertEqual(vm.favoriteGalleries.map(\.title), ["Gallery 1"])
}
/// A thumbnail confirmed broken while scrolling shouldn't come back on the
/// next load.
func testAFavoriteKnownToBeBrokenIsDroppedOnReload() async {
vm.brokenFavoriteUris = ["at://did:plc:someone/social.grain.gallery/1"]
MockURLProtocol.respondWithJSON(feedJSON([galleryJSON(1), galleryJSON(2)], cursor: nil))
await vm.loadFavorites(did: "did:plc:someone")
XCTAssertEqual(vm.favoriteGalleries.map(\.title), ["Gallery 2"])
}
/// Marking one broken mid-scroll takes it off screen without a reload.
func testMarkingAFavoriteBrokenHidesItImmediately() async {
MockURLProtocol.respondWithJSON(feedJSON([galleryJSON(1), galleryJSON(2)], cursor: nil))
await vm.loadFavorites(did: "did:plc:someone")
XCTAssertEqual(vm.visibleFavorites.count, 2)
vm.brokenFavoriteUris.insert("at://did:plc:someone/social.grain.gallery/1")
XCTAssertEqual(vm.visibleFavorites.map(\.title), ["Gallery 2"])
XCTAssertEqual(vm.favoriteGalleries.count, 2, "The list itself is untouched; only what's shown changes")
}
// MARK: - Favorites loading
func testFavoritesOnlyLoadOnce() async {
var requests = 0
MockURLProtocol.handler = { request in
requests += 1
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (Data(feedJSON([galleryJSON(1)], cursor: nil).utf8), response)
}
await vm.loadFavorites(did: "did:plc:someone")
await vm.loadFavorites(did: "did:plc:someone")
XCTAssertEqual(requests, 1)
XCTAssertTrue(vm.favoritesLoaded)
XCTAssertFalse(vm.isLoadingFavorites)
}
func testAFailedFavoritesLoadRecordsItsOwnError() async {
MockURLProtocol.respondWithError(statusCode: 500)
await vm.loadFavorites(did: "did:plc:someone")
XCTAssertNotNil(vm.favoritesError)
XCTAssertTrue(vm.favoriteGalleries.isEmpty)
XCTAssertTrue(vm.favoritesLoaded, "A failure still counts as having tried")
XCTAssertNil(vm.error, "A favorites failure must not blank the whole profile")
}
func testPagingFavoritesAppendsAndFilters() async {
MockURLProtocol.respondWithJSON(feedJSON([galleryJSON(1)], cursor: "page2"))
await vm.loadFavorites(did: "did:plc:someone")
XCTAssertTrue(vm.hasMoreFavorites)
MockURLProtocol.respondWithJSON(feedJSON([galleryJSON(2), galleryJSON(3, photos: 0)], cursor: nil))
await vm.loadMoreFavorites(did: "did:plc:someone")
XCTAssertEqual(vm.favoriteGalleries.map(\.title), ["Gallery 1", "Gallery 2"])
XCTAssertFalse(vm.hasMoreFavorites)
}
/// Scrolling to the bottom fires this repeatedly.
func testPagingFavoritesStopsWhenTheServerRunsOut() async {
MockURLProtocol.respondWithJSON(feedJSON([galleryJSON(1)], cursor: nil))
await vm.loadFavorites(did: "did:plc:someone")
var requests = 0
MockURLProtocol.handler = { request in
requests += 1
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (Data(feedJSON([galleryJSON(9)], cursor: nil).utf8), response)
}
await vm.loadMoreFavorites(did: "did:plc:someone")
XCTAssertEqual(requests, 0)
}
// MARK: - Story archive
func testTheStoryArchiveOnlyLoadsOnce() async {
var requests = 0
MockURLProtocol.handler = { request in
requests += 1
let body = #"{"stories": [], "cursor": null}"#
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (Data(body.utf8), response)
}
await vm.loadStoryArchive(did: "did:plc:someone")
await vm.loadStoryArchive(did: "did:plc:someone")
XCTAssertEqual(requests, 1)
}
/// The archive is a secondary tab; a failure there must not surface as a
/// profile-level error.
func testAFailedArchiveLoadIsSwallowed() async {
MockURLProtocol.respondWithError(statusCode: 500)
await vm.loadStoryArchive(did: "did:plc:someone")
XCTAssertTrue(vm.archivedStories.isEmpty)
XCTAssertNil(vm.error)
}
func testPagingTheArchiveAppends() async {
let page1 = """
{"stories": [{
"uri": "at://did:plc:someone/social.grain.story/1", "cid": "c1",
"creator": {"cid": "p1", "did": "did:plc:someone", "handle": "someone.test"},
"thumb": "https://test.local/t.jpg", "fullsize": "https://test.local/f.jpg",
"aspectRatio": {"width": 3, "height": 4}, "createdAt": "2025-01-02T00:00:00Z"
}], "cursor": "page2"}
"""
MockURLProtocol.respondWithJSON(page1)
await vm.loadStoryArchive(did: "did:plc:someone")
XCTAssertEqual(vm.archivedStories.count, 1)
let page2 = """
{"stories": [{
"uri": "at://did:plc:someone/social.grain.story/2", "cid": "c2",
"creator": {"cid": "p1", "did": "did:plc:someone", "handle": "someone.test"},
"thumb": "https://test.local/t2.jpg", "fullsize": "https://test.local/f2.jpg",
"aspectRatio": {"width": 3, "height": 4}, "createdAt": "2025-01-02T00:00:00Z"
}], "cursor": null}
"""
MockURLProtocol.respondWithJSON(page2)
await vm.loadMoreArchive(did: "did:plc:someone")
XCTAssertEqual(vm.archivedStories.count, 2)
}
// MARK: - Gallery paging
func testPagingGalleriesAppendsUntilTheServerRunsOut() async {
MockURLProtocol.respondByPath([
"actor.getProfile": profileJSON(),
"getFeed": feedJSON([galleryJSON(1)], cursor: "page2"),
])
await vm.load(did: "did:plc:someone")
XCTAssertTrue(vm.hasMoreGalleries)
MockURLProtocol.respondWithJSON(feedJSON([galleryJSON(2)], cursor: nil))
await vm.loadMoreGalleries(did: "did:plc:someone")
XCTAssertEqual(vm.galleries.map(\.title), ["Gallery 1", "Gallery 2"])
XCTAssertFalse(vm.hasMoreGalleries)
var requests = 0
MockURLProtocol.handler = { request in
requests += 1
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (Data(feedJSON([], cursor: nil).utf8), response)
}
await vm.loadMoreGalleries(did: "did:plc:someone")
XCTAssertEqual(requests, 0)
}
// MARK: - Blocking
func testAProfileIsHiddenInEitherDirectionOfABlock() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON(viewer: #"{"blocking": "at://b/1"}"#)])
await vm.load(did: "did:plc:someone")
XCTAssertTrue(vm.isBlockHidden)
let other = ProfileDetailViewModel(client: client)
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON(viewer: #"{"blockedBy": true}"#)])
await other.load(did: "did:plc:someone")
XCTAssertTrue(other.isBlockHidden)
}
func testAnUnblockedProfileIsNotHidden() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON()])
await vm.load(did: "did:plc:someone")
XCTAssertFalse(vm.isBlockHidden)
}
/// Blocking is applied optimistically so the content disappears on tap.
func testBlockingHidesTheProfileImmediately() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON()])
await vm.load(did: "did:plc:someone")
MockURLProtocol.respondWithJSON(#"{"uri": "at://did:plc:test/social.grain.graph.block/1", "cid": "b"}"#)
await vm.toggleBlock(auth: auth)
XCTAssertNotNil(vm.profile?.viewer?.blocking)
XCTAssertTrue(vm.isBlockHidden)
}
/// If the write fails the block has to come back off, or the profile stays
/// blank for someone who isn't actually blocked.
func testAFailedBlockIsRolledBack() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON()])
await vm.load(did: "did:plc:someone")
MockURLProtocol.respondWithError(statusCode: 500)
await vm.toggleBlock(auth: auth)
XCTAssertNil(vm.profile?.viewer?.blocking)
XCTAssertFalse(vm.isBlockHidden)
}
func testUnblockingRestoresTheProfile() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON(viewer: #"{"blocking": "at://did:plc:test/social.grain.graph.block/1"}"#)])
await vm.load(did: "did:plc:someone")
XCTAssertTrue(vm.isBlockHidden)
MockURLProtocol.respondWithJSON("{}")
await vm.toggleBlock(auth: auth)
XCTAssertNil(vm.profile?.viewer?.blocking)
XCTAssertFalse(vm.isBlockHidden)
}
func testAFailedUnblockLeavesTheBlockInPlace() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON(viewer: #"{"blocking": "at://did:plc:test/social.grain.graph.block/1"}"#)])
await vm.load(did: "did:plc:someone")
MockURLProtocol.respondWithError(statusCode: 500)
await vm.toggleBlock(auth: auth)
XCTAssertNotNil(vm.profile?.viewer?.blocking)
}
/// Signed out there is nobody to block on behalf of.
func testBlockingBailsWithoutAuth() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON()])
await vm.load(did: "did:plc:someone")
var requestMade = false
MockURLProtocol.handler = { request in
requestMade = true
return (Data("{}".utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
await vm.toggleBlock(auth: nil)
XCTAssertFalse(requestMade)
}
func testBlockingBailsBeforeTheProfileHasLoaded() async {
var requestMade = false
MockURLProtocol.handler = { request in
requestMade = true
return (Data("{}".utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
await vm.toggleBlock(auth: auth)
XCTAssertFalse(requestMade)
}
// MARK: - Muting
func testMutingAndUnmutingFlipTheViewerState() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON()])
await vm.load(did: "did:plc:someone")
MockURLProtocol.respondWithJSON("{}")
await vm.toggleMute(auth: auth)
XCTAssertEqual(vm.profile?.viewer?.muted, true)
MockURLProtocol.respondWithJSON("{}")
await vm.toggleMute(auth: auth)
XCTAssertNotEqual(vm.profile?.viewer?.muted, true)
}
func testAFailedMuteIsRolledBack() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON()])
await vm.load(did: "did:plc:someone")
MockURLProtocol.respondWithError(statusCode: 500)
await vm.toggleMute(auth: auth)
XCTAssertNotEqual(vm.profile?.viewer?.muted, true)
}
func testMutingBailsWithoutAuth() async {
MockURLProtocol.respondByPath(["actor.getProfile": profileJSON()])
await vm.load(did: "did:plc:someone")
var requestMade = false
MockURLProtocol.handler = { request in
requestMade = true
return (Data("{}".utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
await vm.toggleMute(auth: nil)
XCTAssertFalse(requestMade)
}
}