← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/ReporterImportPlanTests.swift (17658B)

1import Foundation
2import Testing
3
4@testable import Reportage
5
6@Suite("ReporterImportPlan")
7struct ReporterImportPlanTests {
8
9    private let plan: ReporterImportPlan
10
11    init() throws {
12        plan = ReporterImportPlan(
13            archive: try Fixtures.reporterArchive(), now: Date(timeIntervalSince1970: 0))
14    }
15
16    private func report(_ number: Int) throws -> Report {
17        try #require(plan.reports.first { $0.id == Fixtures.reportID(number) })
18    }
19
20    private func question(_ id: String) throws -> Question {
21        try #require(plan.questions.first { $0.id == id })
22    }
23
24    private func fallbacks(_ number: Int) -> [ReporterImportSummary.FallbackReason] {
25        plan.summary.fallbacks.filter { $0.reportID == Fixtures.reportID(number).uuidString }.map(
26            \.reason)
27    }
28
29    private static let customQuestionID = "9F3E1C2A-5B6D-4E7F-8A9B-0C1D2E3F4A5B"
30
31    // MARK: Reports
32
33    @Test("Every snapshot becomes a report, sorted by date")
34    func reportsSorted() {
35        #expect(plan.reports.count == 14)
36        #expect(plan.summary.failures.isEmpty)
37        #expect(plan.reports.map(\.date) == plan.reports.map(\.date).sorted())
38    }
39
40    @Test("Imported reports are complete, keep their dates and say they were imported")
41    func reportBasics() throws {
42        let first = try report(1)
43        #expect(first.date == Date(timeIntervalSince1970: 1_425_168_900))  // 2015-03-01T00:15:00Z
44        #expect(first.trigger == .imported)
45        #expect(first.state == .complete)
46        #expect(first.promptedAt == nil)
47        #expect(first.modifiedAt == first.date)
48    }
49
50    // MARK: Time zones
51
52    @Test(
53        "Zones come from the placemark, in either language",
54        arguments: [
55            (1, "Asia/Tokyo"),  // 日本
56            (3, "Asia/Tokyo"),  // Japan
57            (4, "Australia/Sydney"),  // オーストラリア, NSW
58            (6, "Asia/Ho_Chi_Minh"),
59            (7, "Asia/Hong_Kong"),
60            (10, "Asia/Taipei"),
61            (11, "Asia/Shanghai"),
62        ]
63    )
64    func zoneFromPlacemark(number: Int, zone: String) throws {
65        #expect(try report(number).timeZone == zone)
66        #expect(
67            !fallbacks(number).contains {
68                if case .timeZoneFromNeighbour = $0 { true } else { false }
69            })
70    }
71
72    @Test("Reports without a usable placemark take the nearest report's zone")
73    func zoneFromNeighbour() throws {
74        // Empty placemark, three hours after a report in Sydney.
75        #expect(try report(5).timeZone == "Australia/Sydney")
76        #expect(fallbacks(5).contains(.timeZoneFromNeighbour(country: nil)))
77        // An unknown country is logged with its name.
78        #expect(try report(8).timeZone == "Asia/Hong_Kong")
79        #expect(fallbacks(8).contains(.timeZoneFromNeighbour(country: "France")))
80        // No location at all.
81        #expect(try report(9).timeZone == "Asia/Hong_Kong")
82        #expect(fallbacks(9).contains(.timeZoneFromNeighbour(country: nil)))
83    }
84
85    @Test("Years are counted in each report's own zone")
86    func yearsInLocalZone() {
87        // Report 4 is 2019-12-31T23:30+0900, which is already 2020 in Sydney.
88        #expect(plan.summary.reportsByYear == [2015: 3, 2020: 6, 2023: 2, 2024: 3])
89    }
90
91    @Test("Without any placemark, the zone is the timestamp's fixed offset")
92    func zoneFromOffset() throws {
93        let json =
94            #"{"questions":[],"snapshots":[{"uniqueIdentifier":"00000000-0000-4000-8000-000000000001","date":"2016-01-01T12:00:00+0900"}]}"#
95        let plan = ReporterImportPlan(archive: try ReporterArchive(data: Data(json.utf8)))
96        #expect(plan.reports.first?.timeZone == "GMT+0900")
97        #expect(
98            plan.summary.fallbacks.map(\.reason) == [
99                .timeZoneFromOffset, .kindInferred(impetus: nil),
100            ])
101    }
102
103    @Test("Fixed offsets parse from Reporter timestamps")
104    func offsetZones() {
105        #expect(ReporterDates.offsetZone("2016-01-01T12:00:00+0900") == "GMT+0900")
106        #expect(ReporterDates.offsetZone("2016-01-01T12:00:00-0530") == "GMT-0530")
107        #expect(ReporterDates.offsetZone("garbage") == "GMT")
108    }
109
110    // MARK: Kinds
111
112    @Test("Report kinds follow reportImpetus")
113    func kindsFromImpetus() throws {
114        #expect(try report(1).kind == .random)
115        #expect(try report(2).kind == .bedtime)
116        #expect(try report(3).kind == .wake)
117        #expect(try report(4).kind == .manual)
118        #expect(plan.summary.reportsByKind == [.random: 7, .manual: 2, .bedtime: 2, .wake: 3])
119    }
120
121    @Test("Missing and unknown impetus values are inferred from the questions")
122    func inferredKinds() throws {
123        // Random-survey questions with no impetus: manual, since nothing shows
124        // a prompt fired.
125        #expect(try report(8).kind == .manual)
126        #expect(fallbacks(8).contains(.kindInferred(impetus: nil)))
127        // Impetus 1 with wake questions.
128        #expect(try report(9).kind == .wake)
129        #expect(fallbacks(9).contains(.kindInferred(impetus: 1)))
130    }
131
132    // MARK: Questions
133
134    @Test("Question types map to kinds")
135    func questionKinds() throws {
136        #expect(try question("default-question-1").kind == .choice)
137        #expect(try question("default-question-2").kind == .yesNo)
138        #expect(try question("default-question-3").kind == .tokens)
139        #expect(try question("default-question-4").kind == .location)
140        #expect(try question("default-question-5").kind == .people)
141        #expect(try question("default-question-6").kind == .number)
142        #expect(try question("default-question-7").kind == .note)
143        let custom = try question(Self.customQuestionID)
144        #expect(custom.kind == .number)
145        #expect(custom.placeholder == "Hours")
146    }
147
148    @Test("Questions keep the export's order")
149    func questionOrder() {
150        #expect(plan.questions.prefix(8).map(\.order) == Array(0..<8))
151        #expect(plan.questions.first?.id == "default-question-2")
152    }
153
154    @Test("Surveys are inferred from the latest report of each kind")
155    func askOn() throws {
156        for id in [
157            "default-question-2", "default-question-3", "default-question-4", "default-question-5",
158        ] {
159            #expect(try question(id).askOn == .random)
160        }
161        #expect(try question("default-question-1").askOn == .wake)
162        #expect(try question("default-question-7").askOn == .bedtime)
163        #expect(try question(Self.customQuestionID).askOn == [.wake, .bedtime])
164        #expect(try question("default-question-6").askOn == [])
165    }
166
167    @Test("Choice options are rebuilt from the answers, most common first")
168    func choiceOptions() throws {
169        #expect(try question("default-question-1").options == ["Well", "Poorly"])
170        #expect(try question("default-question-2").options.isEmpty)
171    }
172
173    @Test("A prompt matching no question gets an archived question of its own")
174    func unmatchedPrompt() throws {
175        let synthesised = try #require(plan.questions.first { $0.prompt == "What did you eat?" })
176        #expect(synthesised.id.hasPrefix("reporter-prompt-"))
177        #expect(synthesised.kind == .tokens)
178        #expect(synthesised.archivedAt == (try report(11)).date)
179        #expect(synthesised.askOn == .random)
180        #expect(fallbacks(11) == [.unmatchedPrompt(questionID: synthesised.id)])
181        #expect(try report(11).responses[1].questionID == synthesised.id)
182    }
183
184    // MARK: Responses
185
186    @Test("Responses keep their prompts and map each answer shape")
187    func responseValues() throws {
188        let first = try report(1)
189        #expect(
190            first.responses.map(\.questionID) == [
191                "default-question-2", "default-question-3", "default-question-4",
192                "default-question-5",
193            ])
194        #expect(first.responses[0].prompt == "Are you outside?")
195        #expect(first.responses[0].value == .options(["Yes"]))
196        #expect(first.responses[1].value == .tokens([Self.tokenID(1), Self.tokenID(2)]))
197        #expect(first.responses[3].value == .tokens([Self.tokenID(5)]))
198        #expect(
199            first.responses[2].value
200                == .place(
201                    // Where the answer was given is the report's location,
202                    // not the place's.
203                    PlaceAnswer(
204                        tokenID: Self.tokenID(3),
205                        coordinate: Coordinate(latitude: 35.6581, longitude: 139.7017),
206                        accuracy: 65
207                    ))
208        )
209        #expect(try report(2).responses[0].value == .text("Long day."))
210        #expect(try report(3).responses[1].value == .number(Decimal(string: "6.5")!))
211    }
212
213    // MARK: Tokens
214
215    /// Token IDs in the fixture, which follow Reporter in sharing one ID
216    /// between every answer using a token.
217    private static func tokenID(_ number: Int) -> String {
218        String(format: "C%07X-0000-4000-8000-000000000000", number)
219    }
220
221    private func token(_ id: String) throws -> Token {
222        try #require(plan.tokens.first { $0.id == id })
223    }
224
225    @Test("Tokens keep Reporter's IDs and are shared between answers")
226    func sharedTokens() throws {
227        // 'Walking' in reports 1 and 5, 'Alex' in reports 1 and 4.
228        #expect(try report(5).responses[1].value == .tokens([Self.tokenID(1)]))
229        #expect(try report(4).responses[3].value == .tokens([Self.tokenID(5), Self.tokenID(9)]))
230
231        let walking = try token(Self.tokenID(1))
232        #expect(walking.text == "Walking")
233        #expect(walking.questionID == "default-question-3")
234        #expect(walking.place == nil)
235        #expect(try token(Self.tokenID(5)).questionID == "default-question-5")
236
237        // Six activities, two people, two places and one token of the
238        // synthesised question.
239        #expect(plan.tokens.count == 11)
240        #expect(plan.summary.tokenCount == 11)
241        #expect(plan.summary.warnings.isEmpty)
242    }
243
244    @Test("Place tokens carry the venue ID and the centre of their answers")
245    func placeTokens() throws {
246        let cafe = try token(Self.tokenID(3))
247        #expect(cafe.text == "Corner Café")
248        #expect(cafe.questionID == "default-question-4")
249        #expect(
250            cafe.place
251                == PlaceDetails(
252                    coordinate: Coordinate(latitude: 35.6582, longitude: 139.7016),
253                    externalID: ExternalPlaceID(
254                        source: .foursquare, value: "4b0000000000000000000001")
255                ))
256    }
257
258    @Test("Places with an invalid accuracy and no venue ID")
259    func placeWithoutExtras() throws {
260        guard case .place(let answer) = try report(14).responses[2].value else {
261            Issue.record("Expected a place")
262            return
263        }
264        // The place's own accuracy is invalid; the report's fix isn't.
265        #expect(answer.accuracy == 10)
266        let office = try token(answer.tokenID)
267        #expect(office.text == "Office")
268        #expect(office.place?.externalID == nil)
269        #expect(office.place?.coordinate == Coordinate(latitude: 35.66, longitude: 139.7))
270    }
271
272    @Test("A place answer in a report without a location records no coordinate")
273    func placeWithoutReportLocation() throws {
274        let json = #"""
275            {"questions":[{"uniqueIdentifier":"q","prompt":"Where?","questionType":3}],"snapshots":[
276            {"uniqueIdentifier":"00000000-0000-4000-8000-000000000001","date":"2016-01-01T12:00:00+0900","reportImpetus":2,"responses":[{"questionPrompt":"Where?","locationResponse":{"text":"Home","uniqueIdentifier":"H","location":{"latitude":35.1,"longitude":139.1,"horizontalAccuracy":5}}}]}]}
277            """#
278        let plan = ReporterImportPlan(archive: try ReporterArchive(data: Data(json.utf8)))
279        #expect(plan.reports.first?.responses.first?.value == .place(PlaceAnswer(tokenID: "H")))
280        #expect(
281            plan.tokens.first?.place?.coordinate == Coordinate(latitude: 35.1, longitude: 139.1))
282    }
283
284    @Test("A token's latest text wins, and the conflict is reported")
285    func conflictingTokenTexts() throws {
286        let json = #"""
287            {"questions":[{"uniqueIdentifier":"q","prompt":"Doing?","questionType":0}],"snapshots":[
288            {"uniqueIdentifier":"00000000-0000-4000-8000-000000000002","date":"2016-01-02T12:00:00+0900","reportImpetus":2,"responses":[{"questionPrompt":"Doing?","tokens":[{"text":"Driving a car","uniqueIdentifier":"T"}]}]},
289            {"uniqueIdentifier":"00000000-0000-4000-8000-000000000001","date":"2016-01-01T12:00:00+0900","reportImpetus":2,"responses":[{"questionPrompt":"Doing?","tokens":[{"text":"Driving","uniqueIdentifier":"T"},{"text":"Reading"}]}]}]}
290            """#
291        let plan = ReporterImportPlan(archive: try ReporterArchive(data: Data(json.utf8)))
292        #expect(plan.tokens.first { $0.id == "T" }?.text == "Driving a car")
293        #expect(plan.summary.warnings.count == 1)
294        // A token without an ID gets a stable one derived from its text.
295        let reading = try #require(plan.tokens.first { $0.text == "Reading" })
296        #expect(reading.id.hasPrefix("reporter-token-"))
297    }
298
299    @Test("Skipped questions are kept with no value")
300    func skippedQuestions() throws {
301        let response = try report(4).responses[2]
302        #expect(response.questionID == "default-question-4")
303        #expect(response.value == nil)
304        #expect(plan.summary.answersByQuestion["default-question-4"] == 2)
305    }
306
307    @Test("An answer in an unexpected extra field is ignored and logged")
308    func extraAnswer() throws {
309        #expect(try report(7).responses[0].value == .options(["No"]))
310        #expect(fallbacks(7) == [.extraAnswerIgnored(questionID: "default-question-2")])
311        // The ignored field's token reuses an activity's ID, as one does in
312        // the real export, without moving the token to this question.
313        #expect(try token(Self.tokenID(1)).questionID == "default-question-3")
314    }
315
316    // MARK: Context
317
318    @Test("Weather Underground records are normalised")
319    func wundergroundWeather() throws {
320        let weather = try #require(try report(1).context.weather)
321        #expect(weather.source == .wunderground)
322        #expect(weather.condition == "Partly Cloudy")
323        #expect(weather.temperature == 12)
324        #expect(weather.feelsLike == 11)
325        #expect(weather.humidity == 0.62)
326        #expect(weather.pressure == 1016)
327        #expect(weather.windSpeed == 9.7)
328        #expect(weather.windDirection == 270)
329        #expect(weather.visibility == 10)
330        #expect(weather.uvIndex == 2)
331        #expect(weather.precipitationToday == 0)
332        #expect(weather.cloudCover == nil)
333    }
334
335    @Test("Dark Sky records are normalised")
336    func darkSkyWeather() throws {
337        let weather = try #require(try report(4).context.weather)
338        #expect(weather.source == .darkSky)
339        #expect(weather.condition == "Clear")
340        #expect(weather.temperature == 24.4)
341        #expect(weather.humidity == 0.55)
342        #expect(weather.cloudCover == 0.12)
343        #expect(weather.precipitationChance == 0.05)
344    }
345
346    @Test("Placeholder and empty weather records count as no weather")
347    func noWeather() throws {
348        #expect(try report(10).context.weather == nil)
349        #expect(try report(11).context.weather == nil)
350        #expect(try report(2).context.weather == nil)
351    }
352
353    @Test("Invalid location readings are dropped")
354    func location() throws {
355        let first = try #require(try report(1).context.location)
356        #expect(first.coordinate == Coordinate(latitude: 35.6581, longitude: 139.7017))
357        #expect(first.altitude == 38)
358        #expect(first.horizontalAccuracy == 65)
359        #expect(first.speed == nil)
360        #expect(first.course == nil)
361        #expect(first.timestamp == Date(timeIntervalSince1970: 1_425_168_891))
362        #expect(first.placemark?.country == "日本")
363        #expect(first.placemark?.postalCode == "150-0000")
364
365        // A negative vertical accuracy means the altitude is invalid too.
366        let wake = try #require(try report(3).context.location)
367        #expect(wake.verticalAccuracy == nil)
368        #expect(wake.altitude == nil)
369
370        #expect(try report(6).context.location?.course == 180)
371        #expect(try report(5).context.location?.placemark == nil)
372        #expect(try report(9).context.location == nil)
373    }
374
375    @Test("Audio, motion and device context")
376    func otherContext() throws {
377        let first = try report(1).context
378        #expect(first.audio == AudioContext(source: .microphone, average: -42, peak: -20.5))
379        #expect(first.motion == MotionContext(steps: 2048, floorsAscended: 3, floorsDescended: 1))
380        #expect(first.device == DeviceContext(batteryLevel: 1, connectivity: .wifi))
381
382        #expect(try report(4).context.motion?.pressure == 101.2)
383        #expect(try report(3).context.device?.connectivity == .cellular)
384        #expect(try report(5).context.device?.connectivity == DeviceContext.Connectivity.none)
385    }
386
387    @Test("Photos keep lightweight metadata with signed coordinates")
388    func photos() throws {
389        let photos = try #require(try report(4).context.photos)
390        #expect(photos.count == 2)
391        #expect(photos.photos[0].coordinate == Coordinate(latitude: -33.8688, longitude: 151.2093))
392        #expect(photos.photos[0].make == "Apple")
393        #expect(photos.photos[0].pixelWidth == 4032)
394        #expect(photos.photos[1].coordinate == nil)
395        // 2019-12-31T13:45:00Z
396        #expect(photos.photos[1].date == Date(timeIntervalSince1970: 1_577_799_900))
397        #expect(try report(1).context.photos == nil)
398    }
399}