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
@testable import Grain
import XCTest
/// Off the test class on purpose: the mock's handler runs on the URL loading
/// thread, and a `static let` on a main-actor class is main-actor state.
private enum PlaceFixtures {
static let tiles = """
{"locations": [{"name": "Lisboa", "h3Index": "8a2a1072b59ffff", "galleryCount": 12, "thumbs": ["https://test.local/1.jpg"]}]}
"""
static let pins = """
{"locations": [
{"name": "Lisboa", "h3Index": "8a2a1072b59ffff", "galleryCount": 12},
{"name": "Porto", "h3Index": "8a2a1072b58ffff", "galleryCount": 4}
]}
"""
static let firstPage = """
{"items": [\(Fixtures.gallery)], "cursor": "c1"}
"""
static let secondPage = """
{"items": [{"uri": "at://did:plc:test/social.grain.gallery/2", "cid": "b2", "title": "Second", "creator": \(Fixtures.profile), "indexedAt": "2025-01-03T00:00:00Z"}], "cursor": null}
"""
static let empty = #"{"items": [], "cursor": null}"#
/// Tiles and pins come from one endpoint told apart by a query parameter,
/// so the answer has to depend on the request. Everything else is the feed.
static func respond(
feed: String = firstPage,
feedStatus: Int = 200,
log: RequestCapture? = nil
) -> (URLRequest) throws -> (Data, HTTPURLResponse) {
{ request in
log?.record(request)
let url = request.url!
if url.path.contains("getLocations") {
let wantsPins = url.query?.contains("pins=true") == true
return (Data((wantsPins ? pins : tiles).utf8), HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
if url.path.contains("getCameras") {
return (Data(Fixtures.cameras.utf8), HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
return (Data(feed.utf8), HTTPURLResponse(url: url, statusCode: feedStatus, httpVersion: nil, headerFields: nil)!)
}
}
}
/// What the handler saw, readable back on the main actor. Locked because the
/// handler runs on the URL loading thread.
private final class RequestCapture: @unchecked Sendable {
private let lock = NSLock()
private var urls: [URL] = []
func record(_ request: URLRequest) {
lock.withLock { urls.append(request.url!) }
}
var count: Int {
lock.withLock { urls.count }
}
func lastQueryValue(_ name: String, onPathContaining fragment: String? = nil) -> String? {
lock.withLock {
guard let url = urls.last(where: { fragment.map($0.path.contains) ?? true }) else { return nil }
return URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == name }?.value
}
}
}
/// The two index screens behind explore's "See all": the cameras grid, and
/// the map whose sheet swaps to a picked place's galleries.
@MainActor
final class BrowseIndexViewModelsTests: GrainTestCase {
private var client: XRPCClient!
override func setUp() async throws {
try await super.setUp()
client = XRPCClient(baseURL: URL(string: "https://test.local")!, session: MockURLProtocol.mockSession())
}
override func tearDown() async throws {
MockURLProtocol.handler = nil
try await super.tearDown()
}
// MARK: - Cameras
func testCamerasArriveWithTheirThumbnails() async {
MockURLProtocol.respondWithJSON(#"{"cameras": [{"camera": "Leica M6", "photoCount": 120, "thumbs": ["https://test.local/1.jpg"]}]}"#)
let vm = CamerasViewModel(client: client)
await vm.load()
XCTAssertEqual(vm.cameras.map(\.camera), ["Leica M6"])
XCTAssertEqual(vm.cameras.first?.thumbs?.count, 1)
XCTAssertFalse(vm.isLoading)
XCTAssertFalse(vm.failed)
}
func testAFailedCamerasLoadSaysSo() async {
MockURLProtocol.respondWithError(statusCode: 500)
let vm = CamerasViewModel(client: client)
await vm.load()
XCTAssertTrue(vm.cameras.isEmpty)
XCTAssertTrue(vm.failed)
XCTAssertFalse(vm.isLoading)
}
// MARK: - Locations
func testLocationsAskForTilesAndPinsSeparately() async {
MockURLProtocol.handler = PlaceFixtures.respond()
let vm = LocationsViewModel(client: client)
await vm.load()
XCTAssertEqual(vm.places.map(\.name), ["Lisboa"])
XCTAssertEqual(vm.places.first?.thumbs?.count, 1)
XCTAssertEqual(vm.pins.map(\.name), ["Lisboa", "Porto"])
XCTAssertEqual(vm.pins.first?.galleryCount, 12)
XCTAssertFalse(vm.isLoading)
}
func testPickingAPlaceLoadsItsGalleriesWithoutLeavingTheIndex() async {
MockURLProtocol.handler = PlaceFixtures.respond()
let vm = LocationsViewModel(client: client)
await vm.load()
let log = RequestCapture()
MockURLProtocol.handler = PlaceFixtures.respond(log: log)
vm.select(cell: "8a2a1072b59ffff", name: "Lisboa", galleryCount: 12)
XCTAssertEqual(vm.selected?.name, "Lisboa")
XCTAssertEqual(vm.selected?.isLoading, true)
await waitUntil { vm.selected?.isLoading == false }
XCTAssertEqual(vm.selected?.galleries.map(\.title), ["A test gallery"])
XCTAssertEqual(vm.selected?.galleryCount, 12)
XCTAssertNotNil(vm.selected?.coordinate)
XCTAssertEqual(log.lastQueryValue("feed", onPathContaining: "getFeed"), "location")
XCTAssertEqual(log.lastQueryValue("location", onPathContaining: "getFeed"), "8a2a1072b59ffff")
// The index counts a place across every cell it folded in; the name
// is what makes the feed cover the same ground.
XCTAssertEqual(log.lastQueryValue("name", onPathContaining: "getFeed"), "Lisboa")
// The index is still there underneath.
XCTAssertEqual(vm.places.count, 1)
}
func testPickingThePlaceAlreadyShownDoesNotReload() async {
MockURLProtocol.handler = PlaceFixtures.respond()
let vm = LocationsViewModel(client: client)
vm.select(cell: "8a2a1072b59ffff", name: "Lisboa", galleryCount: 12)
await waitUntil { vm.selected?.isLoading == false }
let log = RequestCapture()
MockURLProtocol.handler = PlaceFixtures.respond(log: log)
vm.select(cell: "8a2a1072b59ffff", name: "Lisboa", galleryCount: 12)
try? await Task.sleep(for: .milliseconds(100))
XCTAssertEqual(log.count, 0)
}
func testMoreOfAPlacesGalleriesAppendBehindTheCursor() async {
MockURLProtocol.handler = PlaceFixtures.respond()
let vm = LocationsViewModel(client: client)
vm.select(cell: "8a2a1072b59ffff", name: "Lisboa", galleryCount: 12)
await waitUntil { vm.selected?.isLoading == false }
let log = RequestCapture()
MockURLProtocol.handler = PlaceFixtures.respond(feed: PlaceFixtures.secondPage, log: log)
await vm.loadMoreGalleries()
XCTAssertEqual(log.lastQueryValue("cursor"), "c1")
XCTAssertEqual(vm.selected?.galleries.map(\.title), ["A test gallery", "Second"])
XCTAssertEqual(vm.selected?.isLoadingMore, false)
}
func testClearingTheSelectionBringsTheIndexBack() async {
MockURLProtocol.handler = PlaceFixtures.respond(feed: PlaceFixtures.empty)
let vm = LocationsViewModel(client: client)
vm.select(cell: "8a2a1072b59ffff", name: "Lisboa", galleryCount: 12)
await waitUntil { vm.selected?.isLoading == false }
XCTAssertEqual(vm.selected?.isEmpty, true)
vm.clearSelection()
XCTAssertNil(vm.selected)
}
func testAFailedGalleryLoadLeavesThePlaceEmptyRatherThanStuck() async {
MockURLProtocol.handler = PlaceFixtures.respond(feedStatus: 500)
let vm = LocationsViewModel(client: client)
vm.select(cell: "8a2a1072b59ffff", name: "Lisboa", galleryCount: 12)
await waitUntil { vm.selected?.isLoading == false }
XCTAssertEqual(vm.selected?.isEmpty, true)
}
// MARK: - Helpers
/// Block until `condition` holds, or fail after a second. The galleries
/// land on a task the view model owns, which nothing here can await.
private func waitUntil(_ condition: @MainActor () -> Bool, file: StaticString = #filePath, line: UInt = #line) async {
let deadline = Date().addingTimeInterval(1)
while !condition(), Date() < deadline {
try? await Task.sleep(for: .milliseconds(10))
}
XCTAssertTrue(condition(), "Timed out waiting", file: file, line: line)
}
}