← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/SurveyModelTests.swift (20691B)

1import Foundation
2import Testing
3
4@testable import Reportage
5
6@MainActor
7@Suite("SurveyModel")
8struct SurveyModelTests {
9
10    private static func question(_ id: String, _ kind: QuestionKind, order: Int) -> Question {
11        Question(
12            id: id, prompt: "Prompt \(id)", kind: kind, askOn: .random, order: order,
13            modifiedAt: Date(timeIntervalSince1970: 0))
14    }
15
16    private static let questions = [
17        question("yes", .yesNo, order: 0),
18        question("choice", .choice, order: 1),
19        question("tokens", .tokens, order: 2),
20        question("place", .location, order: 3),
21        question("number", .number, order: 4),
22        question("note", .note, order: 5),
23    ]
24
25    private static func entry(_ id: String, _ text: String) -> VocabularyEntry {
26        VocabularyEntry(id: id, text: text, useCount: 1)
27    }
28
29    private func makeModel() -> SurveyModel {
30        SurveyModel(
31            kind: .manual,
32            date: Date(timeIntervalSince1970: 100),
33            timeZone: TimeZone(identifier: "Asia/Tokyo")!,
34            questions: Self.questions,
35            vocabulary: [
36                "tokens": [Self.entry("T1", "Reading"), Self.entry("T2", "Cooking")],
37                "place": [Self.entry("P1", "Home"), Self.entry("P2", "Café")],
38            ]
39        )
40    }
41
42    @Test("Every question gets a response, with no value when skipped")
43    func skippedResponses() {
44        let model = makeModel()
45        let (report, newTokens) = model.makeReport(now: Date(timeIntervalSince1970: 200))
46
47        #expect(report.responses.map(\.questionID) == Self.questions.map(\.id))
48        #expect(report.responses.map(\.prompt) == Self.questions.map(\.prompt))
49        #expect(report.responses.allSatisfy { $0.value == nil })
50        #expect(newTokens.isEmpty)
51        #expect(report.date == Date(timeIntervalSince1970: 100))
52        #expect(report.completedAt == Date(timeIntervalSince1970: 200))
53        #expect(report.timeZone == "Asia/Tokyo")
54        #expect(report.kind == .manual)
55        #expect(report.trigger == .app)
56        #expect(report.state == .complete)
57        #expect(!model.hasAnswers)
58    }
59
60    @Test("A survey opened from a prompt records its trigger and when the prompt came")
61    func prompted() {
62        let promptedAt = Date(timeIntervalSince1970: 50)
63        let model = SurveyModel(
64            kind: .random, date: Date(timeIntervalSince1970: 100), trigger: .notification,
65            promptedAt: promptedAt, questions: Self.questions, vocabulary: [:])
66        let report = model.makeReport(now: Date(timeIntervalSince1970: 200)).report
67        #expect(report.kind == .random)
68        #expect(report.trigger == .notification)
69        #expect(report.promptedAt == promptedAt)
70        #expect(report.date == Date(timeIntervalSince1970: 100))
71    }
72
73    @Test("Answers of every kind become response values")
74    func answers() throws {
75        let model = makeModel()
76        model[optionFor: "yes"] = ResponseValue.yesOption
77        model[optionFor: "choice"] = "Good"
78        model.pickers["tokens"]?.toggle("T2")
79        model.pickers["tokens"]?.toggle("T1")
80        let places = try #require(model.placePickers["place"])
81        places.toggle(try #require(places.candidate(id: "P1")))
82        places.toggle(try #require(places.candidate(id: "P2")))
83        model[numberFor: "number"] = Decimal(string: "2.5")
84        model[textFor: "note"] = "A note"
85
86        let values = model.makeReport(now: Date()).report.responses.map(\.value)
87        #expect(
88            values == [
89                .options(["Yes"]),
90                .options(["Good"]),
91                .tokens(["T2", "T1"]),
92                .place(PlaceAnswer(tokenID: "P2")),
93                .number(Decimal(string: "2.5")!),
94                .text("A note"),
95            ])
96        #expect(model.hasAnswers)
97    }
98
99    @Test("A note of only whitespace counts as skipped")
100    func blankNote() {
101        let model = makeModel()
102        model[textFor: "note"] = "  \n"
103        #expect(model.makeReport(now: Date()).report.responses.last?.value == nil)
104    }
105
106    @Test("Paging stops at both ends, and a repeated advance is ignored")
107    func paging() {
108        let model = makeModel()
109        model.goBack()
110        #expect(model.index == 0)
111
112        model.advance(from: 0)
113        model.advance(from: 0)
114        #expect(model.index == 1)
115
116        model.goBack()
117        #expect(model.index == 0)
118
119        model.show(3)
120        #expect(model.index == 3)
121        model.show(Self.questions.count)
122        #expect(model.index == 3)
123
124        for _ in Self.questions { model.advance() }
125        #expect(model.index == Self.questions.count - 1)
126        #expect(model.isLastQuestion)
127        #expect(!model.advance())
128    }
129
130    @Test("Clearing the current question removes its answer")
131    func clearCurrent() {
132        let model = makeModel()
133        model[optionFor: "yes"] = ResponseValue.noOption
134        model.clearCurrent()
135        #expect(model[optionFor: "yes"] == nil)
136
137        model.advance()
138        model.advance()
139        model.pickers["tokens"]?.toggle("T1")
140        model.clearCurrent()
141        #expect(model.pickers["tokens"]?.selection == [])
142    }
143
144    @Test("Only new tokens that are still selected are saved")
145    func newTokens() throws {
146        let model = makeModel()
147        let picker = try #require(model.pickers["tokens"])
148        picker.query = "Walking"
149        picker.addQuery()
150        picker.query = "Swimming"
151        picker.addQuery()
152        let swimming = try #require(picker.selection.last)
153        picker.toggle(swimming)
154
155        let newTokens = model.makeReport(now: Date(timeIntervalSince1970: 5)).newTokens
156        #expect(newTokens.map(\.text) == ["Walking"])
157        #expect(newTokens.first?.questionID == "tokens")
158        #expect(newTokens.first?.place == nil)
159        #expect(newTokens.first?.modifiedAt == Date(timeIntervalSince1970: 5))
160    }
161
162    @Test("Filling in a logged report keeps its moment, trigger and context")
163    func fillIn() throws {
164        var context = Context()
165        context.location = LocationContext(
166            coordinate: Coordinate(latitude: 1.5, longitude: 2.5), horizontalAccuracy: 20)
167        let logged = Report(
168            id: Fixtures.reportID(7),
169            date: Date(timeIntervalSince1970: 50),
170            timeZone: "Australia/Sydney",
171            kind: .random,
172            trigger: .notification,
173            state: .passive,
174            promptedAt: Date(timeIntervalSince1970: 40),
175            context: context,
176            modifiedAt: Date(timeIntervalSince1970: 50)
177        )
178        let model = SurveyModel(
179            editing: logged, questions: Self.questions,
180            vocabulary: [
181                "place": [
182                    VocabularyEntry(
183                        id: "P1", text: "Home", useCount: 1,
184                        coordinate: Coordinate(latitude: 1.5, longitude: 2.5))
185                ]
186            ])
187        #expect(model.date == logged.date)
188        #expect(model.timeZone == "Australia/Sydney")
189        #expect(model.kind == .random)
190        // The place picker uses the logged location, and nothing is captured.
191        let places = try #require(model.placePickers["place"])
192        #expect(places.location == context.location)
193        model.startCapture()
194
195        // The logged location is at Home, but a logged report isn't pre-filled.
196        #expect(places.selection == nil)
197        places.toggle(try #require(places.candidate(id: "P1")))
198        model[optionFor: "yes"] = ResponseValue.yesOption
199        let report = model.makeReport(now: Date(timeIntervalSince1970: 300), context: context).report
200
201        #expect(report.id == logged.id)
202        #expect(report.trigger == .notification)
203        #expect(report.promptedAt == logged.promptedAt)
204        #expect(report.date == logged.date)
205        #expect(report.context == context)
206        #expect(report.state == .complete)
207        #expect(report.completedAt == Date(timeIntervalSince1970: 300))
208        #expect(report.modifiedAt == Date(timeIntervalSince1970: 300))
209        #expect(report.responses.first?.value == .options(["Yes"]))
210        #expect(
211            report.responses[3].value
212                == .place(PlaceAnswer(tokenID: "P1", coordinate: context.location?.coordinate, accuracy: 20)))
213    }
214
215    @Test("Editing starts from the report's answers and keeps those left alone")
216    func editing() throws {
217        let given = PlaceAnswer(
218            tokenID: "P1", coordinate: Coordinate(latitude: 9, longitude: 9), accuracy: 5)
219        let original = Report(
220            id: Fixtures.reportID(8),
221            date: Date(timeIntervalSince1970: 50),
222            timeZone: "Asia/Tokyo",
223            kind: .manual,
224            trigger: .app,
225            state: .complete,
226            completedAt: Date(timeIntervalSince1970: 60),
227            responses: [
228                Response(questionID: "yes", prompt: "Old wording?", value: .options(["Yes"])),
229                Response(questionID: "tokens", prompt: "Doing?", value: .tokens(["T1", "OLD"])),
230                Response(questionID: "place", prompt: "Where?", value: .place(given)),
231                Response(questionID: "note", prompt: "Note?", value: .text("Before")),
232                // A response to a question the survey doesn't show.
233                Response(questionID: "gone", prompt: "Gone?", value: .number(1)),
234            ],
235            modifiedAt: Date(timeIntervalSince1970: 60)
236        )
237        let questions = Self.questions.filter { ["yes", "tokens", "place", "note"].contains($0.id) }
238        let model = SurveyModel(
239            editing: original, questions: questions,
240            vocabulary: [
241                "tokens": [Self.entry("T1", "Reading")],
242                "place": [Self.entry("P1", "Home")],
243            ],
244            // An archived token the suggestions leave out.
245            tokens: ["OLD": Self.entry("OLD", "Knitting")]
246        )
247
248        #expect(model[optionFor: "yes"] == "Yes")
249        #expect(model.pickers["tokens"]?.selectedEntries.map(\.text) == ["Reading", "Knitting"])
250        #expect(model.placePickers["place"]?.selectedTokenID == "P1")
251        #expect(model.placePickers["place"]?.selection?.name == "Home")
252        #expect(model[textFor: "note"] == "Before")
253        #expect(!model.hasChanges)
254
255        // Saving without changes keeps every response exactly.
256        let unchanged = model.makeReport(now: Date(timeIntervalSince1970: 300)).report
257        #expect(unchanged.responses == original.responses)
258        #expect(unchanged.completedAt == original.completedAt)
259        #expect(unchanged.modifiedAt == Date(timeIntervalSince1970: 300))
260
261        model[textFor: "note"] = "After"
262        #expect(model.hasChanges)
263        let changed = model.makeReport(now: Date(timeIntervalSince1970: 300)).report
264        #expect(changed.responses.map(\.questionID) == original.responses.map(\.questionID))
265        // The changed answer keeps the prompt it was first given under.
266        #expect(changed.responses[3] == Response(questionID: "note", prompt: "Note?", value: .text("After")))
267        #expect(Array(changed.responses[0..<3]) == Array(original.responses[0..<3]))
268        #expect(changed.responses[4] == original.responses[4])
269    }
270
271    @Test("New place tokens carry place details")
272    func newPlace() throws {
273        let model = makeModel()
274        let picker = try #require(model.placePickers["place"])
275        picker.query = "Library"
276        picker.addQuery()
277        let newTokens = model.makeReport(now: Date(timeIntervalSince1970: 5)).newTokens
278        #expect(newTokens.map(\.text) == ["Library"])
279        #expect(newTokens.first?.questionID == "place")
280        #expect(newTokens.first?.place == PlaceDetails())
281        #expect(newTokens.first?.modifiedAt == Date(timeIntervalSince1970: 5))
282    }
283
284    // MARK: Carrying people forward
285
286    private static let carryQuestions = [
287        question("place", .location, order: 0),
288        question("people", .people, order: 1),
289        question("tokens", .tokens, order: 2),
290    ]
291
292    private static let home = Coordinate(latitude: 35, longitude: 139)
293
294    /// The previous report: at Home with Sam and Kai, reading.
295    private static func previous(people: [String] = ["S", "K"]) -> Report {
296        Report(
297            id: Fixtures.reportID(9),
298            date: Date(timeIntervalSince1970: 0),
299            timeZone: "Asia/Tokyo",
300            kind: .random,
301            trigger: .notification,
302            state: .complete,
303            responses: [
304                Response(questionID: "place", prompt: "Where?", value: .place(PlaceAnswer(tokenID: "P1"))),
305                Response(questionID: "people", prompt: "With?", value: .tokens(people)),
306                Response(questionID: "tokens", prompt: "Doing?", value: .tokens(["T1"])),
307            ],
308            modifiedAt: Date(timeIntervalSince1970: 0)
309        )
310    }
311
312    private func makeCarryingModel(
313        previous: Report = previous(), people: [VocabularyEntry]? = nil
314    ) -> SurveyModel {
315        SurveyModel(
316            kind: .random,
317            date: Date(timeIntervalSince1970: 100),
318            questions: Self.carryQuestions,
319            vocabulary: [
320                "place": [
321                    VocabularyEntry(id: "P1", text: "Home", useCount: 5, coordinate: Self.home),
322                    Self.entry("P2", "Café"),
323                ],
324                "people": people ?? [Self.entry("S", "Sam"), Self.entry("K", "Kai"), Self.entry("A", "Ada")],
325                "tokens": [Self.entry("T1", "Reading")],
326            ],
327            previous: previous,
328            directory: EmptyDirectory()
329        )
330    }
331
332    @Test("The previous report's people are chosen while the place is the same")
333    func carriesPeople() throws {
334        let model = makeCarryingModel()
335        let places = try #require(model.placePickers["place"])
336        let people = try #require(model.pickers["people"])
337        #expect(people.selection.isEmpty)
338
339        places.toggle(try #require(places.candidate(id: "P1")))
340        #expect(people.selection == ["S", "K"])
341        #expect(people.isPrefilled)
342        // Activities aren't carried.
343        #expect(model.pickers["tokens"]?.selection.isEmpty == true)
344
345        // A different place takes them away, and the same place brings them back.
346        places.toggle(try #require(places.candidate(id: "P2")))
347        #expect(people.selection.isEmpty)
348        places.toggle(try #require(places.candidate(id: "P1")))
349        #expect(people.selection == ["S", "K"])
350        places.toggle(try #require(places.candidate(id: "P1")))
351        #expect(people.selection.isEmpty)
352    }
353
354    @Test("The place pre-filled from the location carries the people too")
355    func carriesWithPrefilledPlace() throws {
356        let model = makeCarryingModel()
357        model.placePickers["place"]?.setLocation(LocationContext(coordinate: Self.home, horizontalAccuracy: 10))
358        #expect(model.placePickers["place"]?.selectedTokenID == "P1")
359        #expect(model.pickers["people"]?.selection == ["S", "K"])
360    }
361
362    @Test("People the user has changed are left alone when the place changes")
363    func userChangesWin() throws {
364        let model = makeCarryingModel()
365        let places = try #require(model.placePickers["place"])
366        let people = try #require(model.pickers["people"])
367
368        places.toggle(try #require(places.candidate(id: "P1")))
369        people.toggle("A")
370        places.toggle(try #require(places.candidate(id: "P2")))
371        #expect(people.selection == ["S", "K", "A"])
372
373        // Clearing the people before the place is chosen counts as a change.
374        let other = makeCarryingModel()
375        let otherPeople = try #require(other.pickers["people"])
376        otherPeople.toggle("A")
377        otherPeople.toggle("A")
378        let otherPlaces = try #require(other.placePickers["place"])
379        otherPlaces.toggle(try #require(otherPlaces.candidate(id: "P1")))
380        #expect(otherPeople.selection.isEmpty)
381    }
382
383    @Test("Carried people read as the tokens they were merged into, without those no longer suggested")
384    func carriesMergedPeople() throws {
385        let model = makeCarryingModel(
386            previous: Self.previous(people: ["OLD", "S", "GONE"]),
387            people: [
388                VocabularyEntry(
389                    id: "S", text: "Sam", useCount: 2,
390                    merged: [MergedToken(id: "OLD", text: "Samuel", useCount: 1)])
391            ])
392        let places = try #require(model.placePickers["place"])
393        places.toggle(try #require(places.candidate(id: "P1")))
394        #expect(model.pickers["people"]?.selection == ["S"])
395    }
396}
397
398/// A directory with no places.
399private struct EmptyDirectory: PlaceDirectory {
400    func places(near coordinate: Coordinate) async throws -> [DirectoryPlace] { [] }
401    func search(_ query: String, near coordinate: Coordinate?) async throws -> [DirectoryPlace] { [] }
402}
403
404@MainActor
405@Suite("TokenPicker")
406struct TokenPickerTests {
407
408    private func makePicker(allowsMultiple: Bool = true) -> TokenPicker {
409        TokenPicker(
410            questionID: "Q",
411            allowsMultiple: allowsMultiple,
412            entries: [
413                VocabularyEntry(id: "1", text: "Reading", useCount: 3),
414                VocabularyEntry(id: "2", text: "Cooking", useCount: 2),
415                VocabularyEntry(id: "3", text: "Café work", useCount: 1),
416            ]
417        )
418    }
419
420    @Test("Searching filters entries and offers to add unknown text")
421    func search() {
422        let picker = makePicker()
423        #expect(picker.visibleEntries.map(\.id) == ["1", "2", "3"])
424        #expect(!picker.canAddQuery)
425
426        picker.query = "cafe"
427        #expect(picker.visibleEntries.map(\.id) == ["3"])
428        #expect(picker.canAddQuery)
429
430        picker.query = " reading "
431        #expect(picker.visibleEntries.map(\.id) == ["1"])
432        #expect(!picker.canAddQuery)
433    }
434
435    @Test("Text naming a token merged into an entry finds and selects the entry")
436    func mergedName() {
437        var cooking = VocabularyEntry(id: "2", text: "Cooking", useCount: 2)
438        cooking.merged = [MergedToken(id: "4", text: "Making dinner", useCount: 1)]
439        let picker = TokenPicker(questionID: "Q", allowsMultiple: true, entries: [cooking])
440        picker.query = "dinner"
441        #expect(picker.visibleEntries.map(\.id) == ["2"])
442        #expect(picker.canAddQuery)
443        picker.query = "making DINNER"
444        #expect(!picker.canAddQuery)
445        picker.addQuery()
446        #expect(picker.selection == ["2"])
447    }
448
449    @Test("Searching finds an entry by its narrative form")
450    func narrativeForm() {
451        var person = VocabularyEntry(id: "1", text: "山田花子", useCount: 1)
452        person.narrativeForm = "Hanako"
453        let picker = TokenPicker(questionID: "Q", allowsMultiple: true, entries: [person])
454        picker.query = "hana"
455        #expect(picker.visibleEntries.map(\.id) == ["1"])
456    }
457
458    @Test("Adding text that names an entry selects the entry")
459    func addExisting() {
460        let picker = makePicker()
461        picker.query = "COOKING"
462        picker.addQuery()
463        #expect(picker.selection == ["2"])
464        #expect(picker.query.isEmpty)
465        #expect(picker.usedNewTokens(now: Date()).isEmpty)
466    }
467
468    @Test("A new token is listed first and selected")
469    func addNew() {
470        let picker = makePicker(allowsMultiple: false)
471        picker.query = "Walking"
472        picker.addQuery()
473        #expect(picker.visibleEntries.first?.text == "Walking")
474        #expect(picker.selectedEntries.map(\.text) == ["Walking"])
475    }
476
477    @Test("Multiple selection leaves selected entries out of the list")
478    func multipleSelectionHidesSelected() {
479        let picker = makePicker()
480        picker.toggle("2")
481        #expect(picker.visibleEntries.map(\.id) == ["1", "3"])
482        picker.query = "Walking"
483        picker.addQuery()
484        #expect(picker.visibleEntries.map(\.id) == ["1", "3"])
485        picker.toggle("2")
486        #expect(picker.visibleEntries.map(\.id) == ["1", "2", "3"])
487    }
488
489    @Test("Selecting an entry clears the query")
490    func selectClearsQuery() {
491        let picker = makePicker()
492        picker.query = "read"
493        picker.toggle("1")
494        #expect(picker.query.isEmpty)
495        picker.query = "cook"
496        picker.toggle("1")
497        #expect(picker.query == "cook")
498    }
499
500    @Test("Single selection replaces the selected entry")
501    func singleSelection() {
502        let picker = makePicker(allowsMultiple: false)
503        picker.toggle("1")
504        picker.toggle("2")
505        #expect(picker.selection == ["2"])
506        picker.toggle("2")
507        #expect(picker.selection.isEmpty)
508    }
509}