← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Tests/Unit/PlacePickerTests.swift (16510B)

1import Foundation
2import Testing
3
4@testable import Reportage
5
6/// A directory with fixed answers.
7private struct FakeDirectory: PlaceDirectory {
8    var nearby: [DirectoryPlace] = []
9    var results: [String: [DirectoryPlace]] = [:]
10
11    func places(near coordinate: Coordinate) async throws -> [DirectoryPlace] { nearby }
12
13    func search(_ query: String, near coordinate: Coordinate?) async throws -> [DirectoryPlace] {
14        results[query] ?? []
15    }
16}
17
18@MainActor
19@Suite("PlacePicker")
20struct PlacePickerTests {
21
22    /// The report's location.
23    private static let here = Coordinate(latitude: 35, longitude: 139)
24
25    /// A coordinate about `metres` north of `here`.
26    private static func north(_ metres: Double) -> Coordinate {
27        Coordinate(latitude: here.latitude + metres / 111_000, longitude: here.longitude)
28    }
29
30    private static func entry(
31        _ id: String, _ text: String, uses: Int, at coordinate: Coordinate?,
32        externalID: ExternalPlaceID? = nil
33    ) -> VocabularyEntry {
34        VocabularyEntry(
35            id: id, text: text, useCount: uses, coordinate: coordinate, externalID: externalID)
36    }
37
38    private static func directoryPlace(_ id: String, _ name: String, at coordinate: Coordinate)
39        -> DirectoryPlace
40    {
41        DirectoryPlace(id: id, name: name, coordinate: coordinate, detail: "1 Street", language: "en")
42    }
43
44    private static let entries = [
45        entry("home", "Home", uses: 900, at: north(350)),
46        entry("cafe", "Café", uses: 20, at: north(60)),
47        entry("bar", "Bar", uses: 40, at: north(120)),
48        entry("office", "Office", uses: 500, at: north(8_000)),
49        entry("unplaced", "Somewhere", uses: 5, at: nil),
50    ]
51
52    private func makePicker(
53        entries: [VocabularyEntry] = Self.entries,
54        directory: FakeDirectory = FakeDirectory()
55    ) -> PlacePicker {
56        PlacePicker(questionID: "Q", entries: entries, directory: directory, searchDelay: .zero)
57    }
58
59    private func ids(_ picker: PlacePicker) -> [PlaceSection.Kind: [String]] {
60        Dictionary(uniqueKeysWithValues: picker.sections.map { ($0.kind, $0.candidates.map(\.id)) })
61    }
62
63    @Test("Without a location, the user's places are listed by use")
64    func noLocation() {
65        let picker = makePicker()
66        #expect(picker.locationState == .locating)
67        #expect(ids(picker) == [.yours: ["home", "cafe", "bar", "office", "unplaced"]])
68
69        picker.setLocation(nil)
70        #expect(picker.locationState == .unavailable)
71        // A late fix doesn't reshuffle the list.
72        picker.setLocation(LocationContext(coordinate: Self.here))
73        #expect(picker.location == nil)
74    }
75
76    @Test("Only near places are listed, by distance band then use, before nearby directory places")
77    func ranking() async {
78        let directory = FakeDirectory(nearby: [
79            Self.directoryPlace("far", "Bakery", at: Self.north(200)),
80            Self.directoryPlace("close", "Kiosk", at: Self.north(30)),
81        ])
82        let picker = makePicker(directory: directory)
83        picker.setLocation(LocationContext(coordinate: Self.here))
84        await picker.settle()
85
86        // Bar and Café are both within the first band, so Bar's greater use
87        // puts it first. Home is in the next band. Office is too far away,
88        // and Somewhere's distance isn't known.
89        #expect(
90            ids(picker) == [
91                .yours: ["bar", "cafe", "home"],
92                .nearby: ["mapKit:close", "mapKit:far"],
93            ])
94        #expect(picker.sections.map(\.kind) == [.yours, .nearby])
95        let distance = try? #require(picker.candidate(id: "cafe")?.distance)
96        #expect(abs((distance ?? 0) - 60) < 1)
97
98        // Places further away are found by searching.
99        picker.query = "o"
100        #expect(ids(picker)[.yours] == ["home", "office", "unplaced"])
101        #expect(picker.candidate(id: "unplaced")?.distance == nil)
102    }
103
104    @Test("Directory places that are the user's are shown as theirs")
105    func merging() async throws {
106        let entries = [
107            Self.entry(
108                "saved", "My Café", uses: 3, at: Self.north(5_000),
109                externalID: ExternalPlaceID(source: .mapKit, value: "M1")),
110            Self.entry(
111                "old", "Library", uses: 2, at: Self.north(2_000),
112                externalID: ExternalPlaceID(source: .foursquare, value: "F1")),
113        ]
114        let directory = FakeDirectory(nearby: [
115            // The same MapKit ID, though named differently and far apart.
116            Self.directoryPlace("M1", "Café Lumière", at: Self.north(40)),
117            // The same name near a Foursquare-era place.
118            Self.directoryPlace("M2", "library", at: Self.north(1_900)),
119            // The same name, but too far away to be the same place.
120            Self.directoryPlace("M3", "Library", at: Self.north(100)),
121        ])
122        let picker = makePicker(entries: entries, directory: directory)
123        picker.setLocation(LocationContext(coordinate: Self.here))
124        await picker.settle()
125
126        // Both places are beyond the near distance, so they're listed only
127        // because the directory has them nearby.
128        #expect(ids(picker) == [.nearby: ["saved", "mapKit:M3", "old"]])
129        #expect(picker.candidate(id: "saved")?.source == .own)
130        let distance = try #require(picker.candidate(id: "saved")?.distance)
131        #expect(abs(distance - 40) < 1)
132    }
133
134    @Test("Choosing a directory place makes a token with its names, coordinate and ID")
135    func adoptDirectoryPlace() async throws {
136        let place = Self.directoryPlace("M1", "Kiosk", at: Self.north(30))
137        let picker = makePicker(directory: FakeDirectory(nearby: [place]))
138        picker.setLocation(LocationContext(coordinate: Self.here))
139        await picker.settle()
140
141        let candidate = try #require(picker.candidate(id: "mapKit:M1"))
142        picker.toggle(candidate)
143        let tokenID = try #require(picker.selectedTokenID)
144        let token = try #require(picker.usedNewTokens(now: Date(timeIntervalSince1970: 9)).first)
145        #expect(token.id == tokenID)
146        #expect(token.questionID == "Q")
147        #expect(token.text == "Kiosk")
148        #expect(token.modifiedAt == Date(timeIntervalSince1970: 9))
149        // The coordinate is the report's location, not the directory's.
150        #expect(
151            token.place
152                == PlaceDetails(
153                    coordinate: Self.here,
154                    names: [LocalisedName(language: "en", text: "Kiosk")],
155                    externalID: ExternalPlaceID(source: .mapKit, value: "M1")))
156
157        // Choosing another place leaves the directory place unsaved, and
158        // choosing it again reuses its token.
159        picker.toggle(try #require(picker.candidate(id: "home")))
160        #expect(picker.selectedTokenID == "home")
161        #expect(picker.usedNewTokens(now: Date()).isEmpty)
162        picker.toggle(candidate)
163        #expect(picker.selectedTokenID == tokenID)
164        picker.toggle(candidate)
165        #expect(picker.selection == nil)
166    }
167
168    @Test("A directory place chosen from far away gets no coordinate")
169    func adoptDistantPlace() async throws {
170        let far = Self.directoryPlace("M9", "Faraway Café", at: Self.north(3_000))
171        let picker = makePicker(directory: FakeDirectory(results: ["far": [far]]))
172        picker.setLocation(LocationContext(coordinate: Self.here))
173        picker.query = "far"
174        await picker.settle()
175
176        picker.toggle(try #require(picker.candidate(id: "mapKit:M9")))
177        let token = try #require(picker.usedNewTokens(now: Date()).first)
178        #expect(token.place?.coordinate == nil)
179        #expect(token.place?.externalID == ExternalPlaceID(source: .mapKit, value: "M9"))
180    }
181
182    @Test("A new place is added where the report is")
183    func addNewPlace() async throws {
184        let picker = makePicker()
185        picker.setLocation(LocationContext(coordinate: Self.here))
186        picker.query = "Park"
187        #expect(picker.canAddQuery)
188        picker.addQuery()
189
190        #expect(picker.query.isEmpty)
191        #expect(picker.selection?.name == "Park")
192        #expect(picker.selection?.distance == 0)
193        let token = try #require(picker.usedNewTokens(now: Date()).first)
194        #expect(token.text == "Park")
195        #expect(token.place == PlaceDetails(coordinate: Self.here))
196
197        // Typing an existing place's name chooses that place instead.
198        picker.query = "home"
199        #expect(!picker.canAddQuery)
200        picker.addQuery()
201        #expect(picker.selectedTokenID == "home")
202        #expect(picker.usedNewTokens(now: Date()).isEmpty)
203    }
204
205    @Test("A search looks through the user's places and the directory")
206    func search() async {
207        let directory = FakeDirectory(
208            nearby: [Self.directoryPlace("N1", "Kiosk", at: Self.north(30))],
209            results: [
210                "ba": [
211                    Self.directoryPlace("R1", "Bakery", at: Self.north(900)),
212                    Self.directoryPlace("R2", "Bank", at: Self.north(300)),
213                ]
214            ])
215        let picker = makePicker(directory: directory)
216        picker.setLocation(LocationContext(coordinate: Self.here))
217        await picker.settle()
218
219        picker.query = "ba"
220        #expect(picker.isSearching)
221        await picker.settle()
222        #expect(!picker.isSearching)
223        // Directory results keep the directory's order.
224        #expect(ids(picker) == [.yours: ["bar"], .results: ["mapKit:R1", "mapKit:R2"]])
225
226        picker.query = ""
227        #expect(picker.sections.map(\.kind) == [.yours, .nearby])
228    }
229
230    @Test("Venues are listed only when the directory has them or they're searched for")
231    func venues() async {
232        let entries = Self.entries + [
233            Self.entry(
234                "venue", "Ramen Shop", uses: 50, at: Self.north(20),
235                externalID: ExternalPlaceID(source: .foursquare, value: "F1")),
236            Self.entry(
237                "picked", "Bookshop", uses: 2, at: Self.north(40),
238                externalID: ExternalPlaceID(source: .mapKit, value: "M1")),
239        ]
240        let directory = FakeDirectory(nearby: [
241            Self.directoryPlace("M1", "Books & Co", at: Self.north(40))
242        ])
243        let picker = makePicker(entries: entries, directory: directory)
244        #expect(picker.candidate(id: "venue") == nil)
245        #expect(picker.candidate(id: "picked") == nil)
246
247        picker.setLocation(LocationContext(coordinate: Self.here))
248        await picker.settle()
249        #expect(ids(picker) == [.yours: ["bar", "cafe", "home"], .nearby: ["picked"]])
250
251        picker.query = "ramen"
252        #expect(ids(picker)[.yours] == ["venue"])
253    }
254
255    @Test("Venues the user has renamed or given a narrative form are listed as theirs")
256    func customisedVenues() async {
257        func venue(_ id: String, uses: Int, at metres: Double) -> VocabularyEntry {
258            Self.entry(
259                id, id.capitalized, uses: uses, at: Self.north(metres),
260                externalID: ExternalPlaceID(source: .mapKit, value: id))
261        }
262        var renamed = venue("renamed", uses: 30, at: 100)
263        renamed.isRenamed = true
264        var described = venue("described", uses: 10, at: 200)
265        described.narrativeForm = "the office"
266        let plain = venue("plain", uses: 60, at: 50)
267        let picker = makePicker(entries: Self.entries + [renamed, described, plain])
268
269        // Without a location, they're listed with the saved places.
270        #expect(ids(picker)[.yours] == ["home", "cafe", "bar", "office", "unplaced", "renamed", "described"])
271
272        picker.setLocation(LocationContext(coordinate: Self.here))
273        await picker.settle()
274        // Home and the described venue share a band, and Home is used more.
275        #expect(ids(picker) == [.yours: ["bar", "renamed", "cafe", "home", "described"]])
276    }
277
278    @Test("Typing a place's name outside its region adds a new place with that name")
279    func regions() throws {
280        let entries = [
281            Self.entry("home", "Home", uses: 900, at: Self.north(5_000)),
282            Self.entry("work", "Work", uses: 100, at: Self.north(200)),
283            Self.entry("car", "Car", uses: 10, at: nil),
284        ]
285        let picker = makePicker(entries: entries)
286        picker.setLocation(LocationContext(coordinate: Self.here))
287
288        picker.query = "work"
289        #expect(!picker.canAddQuery)
290        picker.addQuery()
291        #expect(picker.selectedTokenID == "work")
292
293        // A place with no coordinate has no region.
294        picker.query = "Car"
295        #expect(!picker.canAddQuery)
296
297        picker.query = "Home"
298        #expect(picker.canAddQuery)
299        picker.addQuery()
300        let token = try #require(picker.usedNewTokens(now: Date()).first)
301        #expect(token.id != "home")
302        #expect(token.text == "Home")
303        #expect(token.place?.coordinate == Self.here)
304
305        // Without a location, the name alone decides.
306        let unplaced = makePicker(entries: entries)
307        unplaced.setLocation(nil)
308        unplaced.query = "home"
309        #expect(!unplaced.canAddQuery)
310    }
311
312    @Test("Places sharing a name show their locality")
313    func sharedNames() {
314        var home = Self.entry("home", "Home", uses: 900, at: Self.north(100))
315        home.locality = "Musashino"
316        var oldHome = Self.entry("old", "home", uses: 300, at: Self.north(9_000))
317        oldHome.locality = "Suginami"
318        var cafe = Self.entry("cafe", "Café", uses: 20, at: Self.north(60))
319        cafe.locality = "Musashino"
320        let picker = makePicker(entries: [home, oldHome, cafe])
321
322        #expect(picker.candidate(id: "home")?.detail == "Musashino")
323        #expect(picker.candidate(id: "old")?.detail == "Suginami")
324        #expect(picker.candidate(id: "cafe")?.detail == nil)
325    }
326
327    private static func fix(accuracy: Double?) -> LocationContext {
328        LocationContext(coordinate: here, horizontalAccuracy: accuracy)
329    }
330
331    @Test("The only place within 50 m of an accurate fix is chosen")
332    func prefill() {
333        let near = [
334            Self.entry("home", "Home", uses: 900, at: Self.north(30)),
335            Self.entry("park", "Park", uses: 10, at: Self.north(300)),
336        ]
337        let picker = makePicker(entries: near)
338        picker.setLocation(Self.fix(accuracy: 20))
339        #expect(picker.selection?.id == "home")
340        #expect(picker.selectedTokenID == "home")
341    }
342
343    @Test("Nothing is chosen for a rough fix, two close places, or none within 50 m")
344    func noPrefill() {
345        let close = [
346            Self.entry("home", "Home", uses: 900, at: Self.north(20)),
347            Self.entry("cafe", "Café", uses: 5, at: Self.north(45)),
348        ]
349        let cases: [(entries: [VocabularyEntry], accuracy: Double?)] = [
350            ([close[0]], 80),
351            ([close[0]], nil),
352            ([close[0]], -1),
353            (close, 10),
354            (Self.entries, 10),
355        ]
356        for (entries, accuracy) in cases {
357            let picker = makePicker(entries: entries)
358            picker.setLocation(Self.fix(accuracy: accuracy))
359            #expect(picker.selection == nil)
360        }
361    }
362
363    @Test("Nothing is chosen when pre-filling is off or a search is under way")
364    func prefillOff() {
365        let home = [Self.entry("home", "Home", uses: 900, at: Self.north(10))]
366        let off = makePicker(entries: home)
367        off.prefills = false
368        off.setLocation(Self.fix(accuracy: 10))
369        #expect(off.selection == nil)
370
371        let searching = makePicker(entries: home)
372        searching.query = "Ho"
373        searching.setLocation(Self.fix(accuracy: 10))
374        #expect(searching.selection == nil)
375    }
376
377    @Test("Clearing removes the choice and the search")
378    func clear() throws {
379        let picker = makePicker()
380        picker.toggle(try #require(picker.candidate(id: "cafe")))
381        picker.query = "x"
382        picker.clear()
383        #expect(picker.selection == nil)
384        #expect(picker.query.isEmpty)
385    }
386}
387
388@Suite("PlaceRanking")
389struct PlaceRankingTests {
390
391    @Test("Distances fall into bands, with unknown distances last")
392    func bands() {
393        #expect(PlaceRanking.band(for: 0) == 0)
394        #expect(PlaceRanking.band(for: 150) == 0)
395        #expect(PlaceRanking.band(for: 151) == 1)
396        #expect(PlaceRanking.band(for: 1_000_000) == PlaceRanking.bands.count)
397        #expect(PlaceRanking.band(for: nil) == PlaceRanking.bands.count + 1)
398    }
399}