Tests/Unit/AnswerSummaryTests.swift (12267B)
1import Foundation
2import Testing
3
4@testable import Reportage
5
6@Suite("AnswerSummary")
7struct AnswerSummaryTests {
8
9 private static func question(
10 _ id: String, _ kind: QuestionKind, order: Int, options: [String] = [], archived: Bool = false
11 ) -> Question {
12 Question(
13 id: id, prompt: "Prompt \(id)?", kind: kind, options: options, askOn: .random, order: order,
14 archivedAt: archived ? Date(timeIntervalSince1970: 0) : nil, modifiedAt: Date(timeIntervalSince1970: 0))
15 }
16
17 private static func row(_ questionID: String, _ value: ResponseValue, hour: Int = 0) -> AnswerRecord {
18 AnswerRecord(questionID: questionID, date: Date(timeIntervalSince1970: TimeInterval(hour) * 3600), value: value)
19 }
20
21 private static let lookup = SummaryLookup(
22 tokenTexts: ["lee": "Sam Lee", "sammy": "Sam Lee", "kai": "Kai", "home": "Home", "cafe": "Café"],
23 mergedIDs: ["sammy": "lee"])
24
25 @Test("Questions answered are summarised in survey order, archived last, and unanswered ones left out")
26 func order() {
27 let questions = [
28 Self.question("old", .number, order: 0, archived: true),
29 Self.question("people", .people, order: 2),
30 Self.question("working", .yesNo, order: 1),
31 Self.question("unanswered", .note, order: 3),
32 ].sorted { $0.order < $1.order }
33 let rows = [
34 Self.row("people", .tokens(["kai"])), Self.row("working", .options(["Yes"])),
35 Self.row("old", .number(2)),
36 ]
37 let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
38 #expect(summaries.map(\.id) == ["working", "people", "old"])
39 }
40
41 @Test("Tokens count once per answer after merges, most used first")
42 func tokens() throws {
43 let rows = [
44 Self.row("people", .tokens(["lee", "sammy"])),
45 Self.row("people", .tokens(["kai"])),
46 Self.row("people", .tokens(["sammy", "kai"])),
47 Self.row("people", .tokens(["lee"])),
48 Self.row("place", .place(PlaceAnswer(tokenID: "cafe"))),
49 Self.row("place", .place(PlaceAnswer(tokenID: "home"))),
50 ]
51 let questions = [Self.question("people", .people, order: 0), Self.question("place", .location, order: 1)]
52 let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
53 let people = try #require(summaries.first)
54 #expect(people.answered == 4)
55 #expect(people.tallies == [Tally(id: "lee", label: "Sam Lee", count: 3), Tally(id: "kai", label: "Kai", count: 2)])
56 #expect(people.share(of: people.tallies[0]) == 0.75)
57
58 #expect(summaries[1].tallies.map(\.label) == ["Café", "Home"])
59 }
60
61 @Test("Yes/no and choice answers keep the question's order, with others after")
62 func options() throws {
63 let rows = [
64 Self.row("working", .options(["No"])), Self.row("working", .options(["No"])),
65 Self.row("working", .options(["Yes"])),
66 Self.row("mood", .options(["Okay"])), Self.row("mood", .options(["Retired"])),
67 Self.row("mood", .options(["Great", "Great"])),
68 ]
69 let questions = [
70 Self.question("working", .yesNo, order: 0),
71 Self.question("mood", .choice, order: 1, options: ["Great", "Okay", "Poor"]),
72 ]
73 let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
74 #expect(summaries[0].tallies.map(\.id) == ["Yes", "No"])
75 #expect(summaries[0].tallies.map(\.count) == [1, 2])
76 #expect(summaries[1].tallies.map(\.label) == ["Great", "Okay", "Retired"])
77 #expect(summaries[1].tallies.map(\.count) == [1, 1, 1])
78 }
79
80 @Test("Numbers are averaged, and notes listed newest first without blank ones")
81 func numbersAndNotes() throws {
82 let rows = [
83 Self.row("coffee", .number(1)), Self.row("coffee", .number(2)), Self.row("coffee", .number(4.5)),
84 Self.row("note", .text("First"), hour: 1), Self.row("note", .text(" "), hour: 2),
85 Self.row("note", .text(" Second "), hour: 3),
86 ]
87 let questions = [Self.question("coffee", .number, order: 0), Self.question("note", .note, order: 1)]
88 let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
89 #expect(summaries[0].numbers == NumberSummary(mean: 2.5, lowest: 1, highest: 4.5))
90 #expect(summaries[1].notes.map(\.text) == ["Second", "First"])
91 }
92
93 private static var gmt: Calendar {
94 var calendar = Calendar(identifier: .gregorian)
95 calendar.timeZone = .gmt
96 return calendar
97 }
98
99 @Test("Trends give each span's share answering yes, average number, and count of each answer")
100 func trends() throws {
101 let day = { (hour: Int) in Date(timeIntervalSince1970: TimeInterval(hour) * 3600) }
102 let rows = [
103 Self.row("working", .options(["Yes"]), hour: 1), Self.row("working", .options(["No"]), hour: 2),
104 Self.row("working", .options(["Yes"]), hour: 25),
105 Self.row("coffee", .number(1), hour: 1), Self.row("coffee", .number(3), hour: 2),
106 Self.row("people", .tokens(["lee", "sammy"]), hour: 1), Self.row("people", .tokens(["kai"]), hour: 26),
107 Self.row("people", .tokens(["sammy"]), hour: 27),
108 ]
109 let questions = [
110 Self.question("working", .yesNo, order: 0), Self.question("coffee", .number, order: 1),
111 Self.question("people", .people, order: 2),
112 ]
113 let summaries = AnswerSummary.summarise(
114 rows, questions: questions, lookup: Self.lookup, bucket: .day, calendar: Self.gmt)
115 #expect(summaries[0].trend == [TrendPoint(date: day(0), value: 0.5), TrendPoint(date: day(24), value: 1)])
116 #expect(summaries[1].trend == [TrendPoint(date: day(0), value: 2, low: 1, high: 3)])
117 #expect(summaries[2].tallyTrends["lee"] == [TrendPoint(date: day(0), value: 1), TrendPoint(date: day(24), value: 1)])
118 #expect(summaries[2].tallyTrends["kai"] == [TrendPoint(date: day(24), value: 1)])
119 #expect(summaries[2].tallyTrends["sammy"] == nil)
120 }
121
122 @Test("A day's steps are its highest count in its own zone, averaged over each span")
123 func steps() throws {
124 let tokyo = try #require(TimeZone(identifier: "Asia/Tokyo"))
125
126 let base = Date(timeIntervalSince1970: 1_000_000_000)
127 let records = [
128 ContextRecord(date: base, timeZone: tokyo, steps: 1000),
129 ContextRecord(date: base.addingTimeInterval(3600), timeZone: tokyo, steps: 4000),
130 ContextRecord(date: base.addingTimeInterval(15 * 3600), timeZone: tokyo, steps: 100),
131 ContextRecord(date: base.addingTimeInterval(16 * 3600), timeZone: tokyo, steps: 0),
132 ContextRecord(date: base, timeZone: tokyo, temperature: 10),
133 ContextRecord(date: base.addingTimeInterval(3600), timeZone: tokyo, temperature: 20),
134 ]
135 let summary = ContextSummary.summarise(records, bucket: .month, calendar: Self.gmt)
136 let steps = try #require(summary.steps)
137 #expect(steps.days == 2)
138 #expect(steps.mean == 2050)
139 #expect(steps.trend.map(\.value) == [2050])
140 let temperature = try #require(summary.temperature)
141 #expect(temperature.mean == 15)
142 #expect(temperature.trend == [TrendPoint(date: Self.gmt.start(of: .month, for: base), value: 15, low: 10, high: 20)])
143 }
144
145 @Test("Places are counted after merges and shown at their own coordinate or their answers' centre")
146 func places() throws {
147 func place(_ id: String, _ latitude: Double? = nil) -> AnswerRecord {
148 Self.row(
149 "place",
150 .place(PlaceAnswer(tokenID: id, coordinate: latitude.map { Coordinate(latitude: $0, longitude: 0) })))
151 }
152 var lookup = Self.lookup
153 lookup.tokenTexts["office"] = "Office"
154 lookup.tokenTexts["old-office"] = "Office"
155 lookup.mergedIDs["old-office"] = "office"
156 lookup.tokenTexts["nowhere"] = "Nowhere"
157 let rows = [
158 place("home", 1), place("home", 3), place("home"),
159 place("office"), place("old-office", 50),
160 place("nowhere"),
161 Self.row("people", .tokens(["kai"])),
162 ]
163 let summary = try #require(
164 PlacesSummary.summarise(
165 rows, lookup: lookup, tokenCoordinates: ["office": Coordinate(latitude: 10, longitude: 10)]))
166 #expect(
167 summary.places == [
168 MapPlace(id: "home", name: "Home", coordinate: Coordinate(latitude: 2, longitude: 0), count: 3),
169 MapPlace(id: "office", name: "Office", coordinate: Coordinate(latitude: 10, longitude: 10), count: 2),
170 ])
171 #expect(summary.unplaced == 1)
172 #expect(PlacesSummary.summarise([], lookup: lookup, tokenCoordinates: [:]) == nil)
173 }
174
175 @Test("The calendar counts reports by day from the first whole day through today")
176 func calendar() throws {
177
178 let now = Date(timeIntervalSince1970: 1_000_000_000)
179 let today = Self.gmt.startOfDay(for: now)
180 let day: TimeInterval = 86400
181 let dates = [
182 now, today.addingTimeInterval(60), today.addingTimeInterval(-60),
183 today.addingTimeInterval(-6 * day), today.addingTimeInterval(-7 * day),
184 ]
185 let summary = try #require(
186 CalendarSummary.summarise(dates, from: now.addingTimeInterval(-6 * day), through: now, calendar: Self.gmt))
187 #expect(summary.first == today.addingTimeInterval(-6 * day))
188 #expect(summary.last == today)
189 #expect(summary.days == 7)
190 #expect(summary.reports == 4)
191 #expect(summary.daysWithReports == 3)
192 #expect(summary.counts[today] == 2)
193 #expect(CalendarSummary.summarise([], from: now, through: now, calendar: Self.gmt) == nil)
194 #expect([0, 1, 2, 3, 4, 5, 6, 20].map(CalendarSummary.level(of:)) == [0, 1, 2, 2, 3, 3, 4, 4])
195 }
196
197 @Test("Periods end now and reach back a week, a month or a year")
198 func periods() {
199 var calendar = Calendar(identifier: .gregorian)
200 calendar.timeZone = .gmt
201 let now = Date(timeIntervalSince1970: 1_000_000_000)
202 #expect(ChartPeriod.week.start(endingAt: now, calendar: calendar) == now.addingTimeInterval(-7 * 86400))
203 #expect(ChartPeriod.all.start(endingAt: now, calendar: calendar) == nil)
204 let year = calendar.date(byAdding: .year, value: -1, to: now)
205 #expect(ChartPeriod.year.start(endingAt: now, calendar: calendar) == year)
206 }
207
208 @Test("The store's answers leave out skipped questions and reports before the period")
209 func storeAnswers() async throws {
210 let store = ReportStore(persistence: makeTestPersistence())
211 func report(_ hour: Int, _ value: ResponseValue?) -> Report {
212 Report(
213 id: UUID(), date: Date(timeIntervalSince1970: TimeInterval(hour) * 3600), timeZone: "Asia/Tokyo",
214 kind: .manual, trigger: .app, state: .complete,
215 responses: [Response(questionID: "Q", prompt: "P", value: value)],
216 modifiedAt: Date(timeIntervalSince1970: 0))
217 }
218 try await store.insert(report(1, .number(1)))
219 try await store.insert(report(5, .number(5)))
220 try await store.insert(report(6, nil))
221 let all = try await store.answers(since: nil)
222 #expect(all.count == 2)
223 let recent = try await store.answers(since: Date(timeIntervalSince1970: 2 * 3600))
224 #expect(recent.map(\.value) == [.number(5)])
225
226
227 let now = Date(timeIntervalSince1970: 10 * 3600)
228 let data = try await store.chartData(for: .all, now: now, calendar: Self.gmt)
229 #expect(data.domain == Date(timeIntervalSince1970: 0)...now)
230 #expect(data.context.calendar?.reports == 3)
231 #expect(data.context.calendar?.days == 1)
232 #expect(data.summaries.isEmpty)
233 }
234}