← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/HealthTests.swift (7536B)

1import CoreData
2import Foundation
3import Testing
4
5@testable import Reportage
6
7/// Health as a test sets it up, recording what it was asked for.
8private actor FakeHealthReader: HealthReading {
9    var activity = ActivityHealth(steps: 4321, distance: 3200, flightsClimbed: 5)
10    var sleep: [SleepSample] = []
11    private(set) var activityCalls: [Range<Date>] = []
12    private(set) var sleepCalls: [Range<Date>] = []
13
14    init(sleep: [SleepSample] = []) {
15        self.sleep = sleep
16    }
17
18    func activity(from start: Date, to end: Date) async throws -> ActivityHealth {
19        activityCalls.append(start..<end)
20        return activity
21    }
22
23    func sleepSamples(from start: Date, to end: Date) async throws -> [SleepSample] {
24        sleepCalls.append(start..<end)
25        return sleep
26    }
27}
28
29@Suite("Sleep summary")
30struct SleepSummaryTests {
31
32    /// 22:00 UTC on 1 October 2026.
33    private static let evening = Date(timeIntervalSince1970: 1_790_892_000)
34
35    private static func sample(
36        _ source: String, _ stage: SleepSample.Stage, from start: Double, to end: Double
37    ) -> SleepSample {
38        SleepSample(
39            source: source, stage: stage,
40            start: evening.addingTimeInterval(start * 3600), end: evening.addingTimeInterval(end * 3600))
41    }
42
43    @Test("The source with the most sleep is used alone, with its stages")
44    func bestSource() throws {
45        let sleep = try #require(
46            SleepHealth(samples: [
47                Self.sample("phone", .inBed, from: 0, to: 9),
48                Self.sample("phone", .asleep, from: 1, to: 6),
49                Self.sample("watch", .core, from: 1, to: 3),
50                Self.sample("watch", .awake, from: 3, to: 3.5),
51                Self.sample("watch", .deep, from: 3.5, to: 5),
52                Self.sample("watch", .rem, from: 5, to: 8),
53            ]))
54        #expect(sleep.start == Self.evening.addingTimeInterval(3600))
55        #expect(sleep.end == Self.evening.addingTimeInterval(8 * 3600))
56        #expect(sleep.asleep == 6.5 * 3600)
57        #expect(sleep.core == TimeInterval(2 * 3600))
58        #expect(sleep.deep == 1.5 * 3600)
59        #expect(sleep.rem == TimeInterval(3 * 3600))
60        #expect(sleep.awake == 0.5 * 3600)
61    }
62
63    @Test("A nap well before the night isn't joined to it")
64    func napLeftOut() throws {
65        let sleep = try #require(
66            SleepHealth(samples: [
67                Self.sample("watch", .core, from: -8, to: -7),
68                Self.sample("watch", .core, from: 1, to: 7),
69            ]))
70        #expect(sleep.start == Self.evening.addingTimeInterval(3600))
71        #expect(sleep.asleep == 6 * 3600)
72    }
73
74    @Test("A source without stages records time asleep only, and no sleep is nil")
75    func unstaged() throws {
76        let sleep = try #require(SleepHealth(samples: [Self.sample("phone", .asleep, from: 0, to: 7)]))
77        #expect(sleep.asleep == 7 * 3600)
78        #expect(sleep.core == nil && sleep.deep == nil && sleep.rem == nil && sleep.awake == nil)
79        #expect(SleepHealth(samples: [Self.sample("phone", .inBed, from: 0, to: 7)]) == nil)
80        #expect(SleepHealth(samples: []) == nil)
81    }
82}
83
84@Suite("Health cache")
85struct HealthCacheTests {
86
87    private let persistence = makeTestPersistence()
88
89    private var store: ReportStore { ReportStore(persistence: persistence) }
90
91    /// 09:00 in Tokyo on 2 October 2026.
92    private static let morning = Date(timeIntervalSince1970: 1_790_985_600)
93
94    private static func report(_ number: Int, hoursAgo: Double, kind: ReportKind = .random) -> Report {
95        Report(
96            id: Fixtures.reportID(number),
97            date: morning.addingTimeInterval(-hoursAgo * 3600),
98            timeZone: "Asia/Tokyo",
99            kind: kind,
100            trigger: .app,
101            state: .complete,
102            modifiedAt: Date(timeIntervalSince1970: 0))
103    }
104
105    private func fill(_ reader: FakeHealthReader) -> HealthFill {
106        HealthFill(store: store, reader: reader, batchSize: 2)
107    }
108
109    @Test("Activity is read from local midnight, and sleep only for wake reports")
110    func reads() async throws {
111        let reader = FakeHealthReader(sleep: [
112            SleepSample(
113                source: "watch", stage: .core,
114                start: Self.morning.addingTimeInterval(-8 * 3600), end: Self.morning.addingTimeInterval(-3600))
115        ])
116        try await store.insert(Self.report(1, hoursAgo: 0, kind: .wake))
117        try await store.insert(Self.report(2, hoursAgo: 1))
118        try await fill(reader).fill(before: .distantFuture, now: Self.morning)
119
120        let midnight = Date(timeIntervalSince1970: 1_790_953_200)
121        #expect(await reader.activityCalls.map(\.lowerBound) == [midnight, midnight])
122        #expect(await reader.sleepCalls == [Self.morning.addingTimeInterval(-18 * 3600)..<Self.morning])
123
124        let wake = try #require(try await store.health(for: Fixtures.reportID(1)))
125        #expect(wake.health.activity?.steps == 4321)
126        #expect(wake.health.sleep?.asleep == TimeInterval(7 * 3600))
127        #expect(wake.derivedAt == Self.morning)
128        let random = try #require(try await store.health(for: Fixtures.reportID(2)))
129        #expect(random.health.sleep == nil)
130    }
131
132    @Test("Entries settle a day after the report, and only unsettled ones are read again")
133    func settling() async throws {
134        let reader = FakeHealthReader()
135        try await store.insert(Self.report(1, hoursAgo: 2))
136        try await store.insert(Self.report(2, hoursAgo: 30))
137        try await store.insert(Self.report(3, hoursAgo: 50))
138        #expect(try await fill(reader).fill(before: .distantFuture, now: Self.morning) == 3)
139        #expect(try await store.health(for: Fixtures.reportID(1))?.isSettled == false)
140        #expect(try await store.health(for: Fixtures.reportID(2))?.isSettled == true)
141
142        let later = Self.morning.addingTimeInterval(3600)
143        #expect(try await fill(reader).fill(before: .distantFuture, now: later) == 1)
144        #expect(try await store.health(for: Fixtures.reportID(1))?.derivedAt == later)
145    }
146
147    @Test("A pass covers only the reports in its range")
148    func ranges() async throws {
149        let reader = FakeHealthReader()
150        let since = Self.morning.addingTimeInterval(-10 * 3600)
151        for (number, hours) in [(1, 1.0), (2, 5.0), (3, 20.0), (4, 40.0), (5, 60.0)] {
152            try await store.insert(Self.report(number, hoursAgo: hours))
153        }
154        #expect(try await fill(reader).fill(since: since, before: .distantFuture, now: Self.morning) == 2)
155        #expect(try await store.health(for: Fixtures.reportID(3)) == nil)
156        #expect(try await fill(reader).fill(before: since, now: Self.morning) == 3)
157        #expect(try await store.health(for: Fixtures.reportID(5)) != nil)
158    }
159
160    @Test("Health entries go with their reports")
161    func deletion() async throws {
162        let reader = FakeHealthReader()
163        try await store.insert(Self.report(1, hoursAgo: 30))
164        try await store.insert(Self.report(2, hoursAgo: 40))
165        try await fill(reader).fill(before: .distantFuture, now: Self.morning)
166        try await store.delete(id: Fixtures.reportID(1))
167        #expect(try await healthCount() == 1)
168        try await store.deleteAll()
169        #expect(try await healthCount() == 0)
170    }
171
172    private func healthCount() async throws -> Int {
173        let context = persistence.newBackgroundContext()
174        return try await context.perform {
175            try context.count(for: HealthEntity.fetchRequest())
176        }
177    }
178}