← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/ReportDetailsTests.swift (8129B)

1import Foundation
2import Testing
3
4@testable import Reportage
5
6@MainActor
7@Suite("ReportDetails")
8struct ReportDetailsTests {
9
10    private static let locale = Locale(identifier: "en_AU")
11    private static let date = Date(timeIntervalSince1970: 1_792_200_000)
12
13    private static func report(
14        state: ReportState = .complete, context: Context = Context(), responses: [Response] = []
15    ) -> Report {
16        Report(
17            id: UUID(uuidString: "00000000-0000-4000-8000-000000000001")!,
18            date: date,
19            timeZone: "Asia/Tokyo",
20            kind: .random,
21            trigger: .notification,
22            state: state,
23            promptedAt: state == .complete ? date.addingTimeInterval(-125) : nil,
24            completedAt: state == .complete ? date.addingTimeInterval(60) : nil,
25            context: context,
26            responses: responses,
27            modifiedAt: date
28        )
29    }
30
31    private static func details(_ report: Report, lookup: SummaryLookup = SummaryLookup()) -> ReportDetails {
32        ReportDetails(report: report, lookup: lookup, locale: locale)
33    }
34
35    private static func value(_ label: String, in section: String, of details: ReportDetails) -> String? {
36        details.sections.first { $0.title == section }?.rows.first { $0.label == label }?.value
37    }
38
39    @Test("Answers keep their prompts and order, name tokens, and mark skipped questions")
40    func answers() {
41        var lookup = SummaryLookup()
42        lookup.tokenTexts = ["T1": "Reading", "T2": "Drinking coffee", "P1": "Library"]
43        let details = Self.details(
44            Self.report(responses: [
45                Response(questionID: "a", prompt: "Are you working?", value: .options([ResponseValue.noOption])),
46                Response(questionID: "b", prompt: "What are you doing?", value: .tokens(["T2", "T1"])),
47                Response(questionID: "c", prompt: "Where are you?", value: .place(PlaceAnswer(tokenID: "P1"))),
48                Response(questionID: "d", prompt: "Anything to add?", value: nil),
49            ]),
50            lookup: lookup)
51
52        #expect(details.answers.map(\.prompt) == [
53            "Are you working?", "What are you doing?", "Where are you?", "Anything to add?",
54        ])
55        #expect(details.answers.map(\.value) == [
56            .text("No"), .tokens(["Drinking coffee", "Reading"]), .text("Library"), .skipped,
57        ])
58    }
59
60    @Test("Times are shown in the report's own zone, with how long the prompt took")
61    func time() throws {
62        let details = Self.details(Self.report())
63        let reported = try #require(Self.value("Reported", in: "Time", of: details))
64        // 1_792_200_000 is 01:20 UTC, 10:20 in Tokyo.
65        #expect(reported.contains("10:20"))
66        #expect(Self.value("Time Zone", in: "Time", of: details)?.contains("Asia/Tokyo") == true)
67        #expect(Self.value("Source", in: "Time", of: details) == "Prompt")
68        let after = try #require(Self.value("Reported After", in: "Time", of: details))
69        #expect(after.hasPrefix("2 min") && after.contains("5 sec"))
70        #expect(Self.value("Answered", in: "Time", of: details) != nil)
71    }
72
73    @Test("An instant report says it hasn't been answered")
74    func instant() {
75        let details = Self.details(Self.report(state: .passive))
76        #expect(Self.value("Answered", in: "Time", of: details) == "Not yet")
77        #expect(Self.value("Prompted", in: "Time", of: details) == nil)
78    }
79
80    @Test("Sections with nothing recorded are left out")
81    func emptySections() {
82        let titles = Self.details(Self.report()).sections.map(\.title)
83        #expect(titles == ["Time", "Record"])
84    }
85
86    @Test("Every recorded context value appears, and invalid readings don't")
87    func context() {
88        var location = LocationContext(coordinate: Coordinate(latitude: 35.6812, longitude: 139.7671))
89        location.horizontalAccuracy = 12
90        location.altitude = 40
91        location.verticalAccuracy = -1
92        location.speed = -1
93        location.course = 90
94        location.placemark = Placemark(
95            locality: "Chiyoda", country: "Japan", language: "en", countryCode: "JP",
96            fullAddress: "1 Marunouchi, Chiyoda, Tokyo")
97        location.localisedPlacemarks = [
98            Placemark(language: "ja", countryCode: "JP", fullAddress: "東京都千代田区丸の内1丁目"),
99            // From a report made before local addresses: the user's second language.
100            Placemark(language: "fr", countryCode: "JP", fullAddress: "1 Marunouchi, Chiyoda, Tokyo, Japon"),
101        ]
102        var weather = WeatherContext(source: .darkSky)
103        weather.condition = "Cloudy"
104        weather.temperature = 18
105        weather.humidity = 0.65
106        weather.windSpeed = 10
107        weather.windDirection = 45
108        weather.backfilled = true
109        let context = Context(
110            location: location, weather: weather,
111            audio: AudioContext(source: .microphone, average: 42.5),
112            motion: MotionContext(steps: 1234),
113            device: DeviceContext(batteryLevel: 0.5, batteryState: .charging, connectivity: .wifi),
114            photos: PhotosContext(count: 2))
115        let details = Self.details(Self.report(context: context))
116
117        #expect(details.sections.map(\.title) == [
118            "Time", "Place", "Location", "Weather", "Device", "Motion", "Sound", "Photos", "Record",
119        ])
120        #expect(Self.value("Address", in: "Place", of: details) == "1 Marunouchi, Chiyoda, Tokyo")
121        #expect(Self.value("Endonymic Address", in: "Place", of: details) == "東京都千代田区丸の内1丁目")
122        #expect(Self.value("Address in French", in: "Place", of: details) == "1 Marunouchi, Chiyoda, Tokyo, Japon")
123        #expect(Self.value("Coordinates", in: "Location", of: details) == "35.68120, 139.76710")
124        #expect(Self.value("Accuracy", in: "Location", of: details) == "±12 m")
125        // An invalid vertical accuracy leaves the altitude without one.
126        #expect(Self.value("Altitude", in: "Location", of: details) == "40 m")
127        #expect(Self.value("Speed", in: "Location", of: details) == nil)
128        #expect(Self.value("Course", in: "Location", of: details) == "E (90°)")
129        #expect(Self.value("Humidity", in: "Weather", of: details) == "65%")
130        #expect(Self.value("Wind", in: "Weather", of: details)?.hasSuffix("from NE (45°)") == true)
131        #expect(Self.value("Source", in: "Weather", of: details) == "Dark Sky, filled in later")
132        #expect(Self.value("Battery", in: "Device", of: details) == "50%")
133        #expect(Self.value("Connection", in: "Device", of: details) == "Wi-Fi")
134        #expect(Self.value("Steps Today", in: "Motion", of: details) == "1,234")
135        #expect(Self.value("Average Level", in: "Sound", of: details) == "42.5 dB")
136        #expect(Self.value("Taken Since Last Report", in: "Photos", of: details) == "2")
137    }
138
139    @Test("Health from the cache appears after Sound, and missing values are left out")
140    func health() throws {
141        let health = HealthContext(
142            activity: ActivityHealth(steps: 4321, distance: 3200),
143            sleep: SleepHealth(
144                start: Self.date.addingTimeInterval(-8 * 3600), end: Self.date.addingTimeInterval(-3600),
145                asleep: 6.5 * 3600))
146        let context = Context(audio: AudioContext(source: .microphone, average: 40))
147        let details = ReportDetails(
148            report: Self.report(context: context), health: health, lookup: SummaryLookup(), locale: Self.locale)
149
150        #expect(details.sections.map(\.title) == ["Time", "Sound", "Health", "Record"])
151        #expect(Self.value("Steps Today", in: "Health", of: details) == "4,321")
152        #expect(Self.value("Distance Today", in: "Health", of: details) == "3.2 km")
153        #expect(Self.value("Flights Climbed Today", in: "Health", of: details) == nil)
154        let asleep = try #require(Self.value("Time Asleep", in: "Health", of: details))
155        #expect(asleep.hasPrefix("6 hr") && asleep.contains("30 min"))
156        #expect(Self.value("Deep Sleep", in: "Health", of: details) == nil)
157    }
158}