← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/ContextCaptureTests.swift (7224B)

1import CoreLocation
2import Foundation
3import MapKit
4import Testing
5
6@testable import Reportage
7
8@Suite("ContextCapture")
9struct ContextCaptureTests {
10
11    @Test("A fix becomes location context, with invalid readings left out")
12    func locationContext() {
13        let location = CLLocation(
14            coordinate: CLLocationCoordinate2D(latitude: 35.703, longitude: 139.580),
15            altitude: 60, horizontalAccuracy: 8, verticalAccuracy: -1, course: -1, speed: 1.5,
16            timestamp: Date(timeIntervalSince1970: 100))
17        let context = LocationContext(location)
18        #expect(context.coordinate == Coordinate(latitude: 35.703, longitude: 139.580))
19        #expect(context.horizontalAccuracy == 8)
20        #expect(context.altitude == nil)
21        #expect(context.verticalAccuracy == nil)
22        #expect(context.course == nil)
23        #expect(context.speed == 1.5)
24        #expect(context.timestamp == Date(timeIntervalSince1970: 100))
25    }
26
27    @Test("A map item's address becomes a placemark in the language it was asked for")
28    func placemark() throws {
29        let address = try #require(MKAddress(fullAddress: "1-2-3 Kichijoji, Musashino, Tokyo", shortAddress: "Kichijoji"))
30        let item = MKMapItem(location: CLLocation(latitude: 35.7, longitude: 139.58), address: address)
31        item.name = "Kichijoji Station"
32        let placemark = Placemark(item, language: "en")
33        #expect(placemark.name == "Kichijoji Station")
34        #expect(placemark.language == "en")
35        #expect(placemark.fullAddress == "1-2-3 Kichijoji, Musashino, Tokyo")
36        #expect(placemark.shortAddress == "Kichijoji")
37    }
38
39    @Test("Older contexts without the new fields still decode")
40    func backwardCompatible() throws {
41        let json = #"{"location":{"coordinate":{"latitude":1,"longitude":2},"placemark":{"name":"Home"}}}"#
42        let context = try ModelCoding.decode(Context.self, from: Data(json.utf8))
43        #expect(context.location?.placemark?.name == "Home")
44        #expect(context.location?.localisedPlacemarks == nil)
45    }
46
47    @Test("Preferred languages are distinct codes, in order")
48    func languages() {
49        let languages = ContextCapture.preferredLanguages(limit: 2)
50        #expect(languages.count <= 2)
51        #expect(Set(languages).count == languages.count)
52    }
53
54    @Test("A region's local language is its main one, with the script for Chinese")
55    func localLanguage() {
56        #expect(ContextCapture.localLanguage(ofRegion: "JP") == "ja")
57        #expect(ContextCapture.localLanguage(ofRegion: "AU") == "en")
58        #expect(ContextCapture.localLanguage(ofRegion: "VN") == "vi")
59        #expect(ContextCapture.localLanguage(ofRegion: "TW") == "zh-Hant")
60        #expect(ContextCapture.localLanguage(ofRegion: "HK") == "zh-Hant")
61        #expect(ContextCapture.localLanguage(ofRegion: "CN") == "zh-Hans")
62    }
63
64    // MARK: Choosing a fix
65
66    private static let now = Date(timeIntervalSince1970: 10_000)
67
68    private static func fix(accuracy: CLLocationAccuracy, age: TimeInterval) -> CLLocation {
69        CLLocation(
70            coordinate: CLLocationCoordinate2D(latitude: 35.7, longitude: 139.58),
71            altitude: 0, horizontalAccuracy: accuracy, verticalAccuracy: -1,
72            timestamp: now.addingTimeInterval(-age))
73    }
74
75    @Test("A recent, accurate fix ends the search")
76    func recentAccurateFix() {
77        var choice = ContextCapture.FixChoice(goodAccuracy: 50)
78        let ended = choice.consider(Self.fix(accuracy: 10, age: 5), now: Self.now)
79        #expect(ended)
80        #expect(choice.isRecent)
81    }
82
83    @Test("An old fix doesn't end the search however accurate, but is kept")
84    func oldFixKept() {
85        var choice = ContextCapture.FixChoice(goodAccuracy: 50)
86        let old = Self.fix(accuracy: 5, age: 600)
87        let ended = choice.consider(old, now: Self.now)
88        #expect(!ended)
89        #expect(choice.best === old)
90        #expect(!choice.isRecent)
91    }
92
93    @Test("A recent fix beats an older, more accurate one")
94    func recentBeatsOld() {
95        var choice = ContextCapture.FixChoice(goodAccuracy: 50)
96        _ = choice.consider(Self.fix(accuracy: 5, age: 600), now: Self.now)
97        let recent = Self.fix(accuracy: 200, age: 1)
98        let endedOnRecent = choice.consider(recent, now: Self.now)
99        #expect(!endedOnRecent)
100        #expect(choice.best === recent)
101        // An older fix doesn't take its place again.
102        let endedOnOld = choice.consider(Self.fix(accuracy: 3, age: 300), now: Self.now)
103        #expect(!endedOnOld)
104        #expect(choice.best === recent)
105    }
106
107    @Test("Between recent fixes the more accurate wins")
108    func moreAccurateWins() {
109        var choice = ContextCapture.FixChoice(goodAccuracy: 50)
110        _ = choice.consider(Self.fix(accuracy: 200, age: 2), now: Self.now)
111        let better = Self.fix(accuracy: 80, age: 1)
112        _ = choice.consider(better, now: Self.now)
113        _ = choice.consider(Self.fix(accuracy: 120, age: 0), now: Self.now)
114        #expect(choice.best === better)
115    }
116
117    @Test("An old fix from a stationary update counts as recent")
118    func stationaryIsRecent() {
119        var choice = ContextCapture.FixChoice(goodAccuracy: 50)
120        let ended = choice.consider(Self.fix(accuracy: 10, age: 600), stationary: true, now: Self.now)
121        #expect(ended)
122    }
123
124    @Test("A fix with invalid accuracy is ignored")
125    func invalidFixIgnored() {
126        var choice = ContextCapture.FixChoice(goodAccuracy: 50)
127        let ended = choice.consider(Self.fix(accuracy: -1, age: 0), now: Self.now)
128        #expect(!ended)
129        #expect(choice.best == nil)
130    }
131
132    @Test("A timeout gives up with nil, and a quick result comes through")
133    func timeout() async {
134        let slow = await withTimeout(.milliseconds(50)) { () async -> Int? in
135            try? await Task.sleep(for: .seconds(5))
136            return 1
137        }
138        #expect(slow == nil)
139        let quick = await withTimeout(.seconds(5)) { () async -> Int? in 2 }
140        #expect(quick == 2)
141    }
142}
143
144@MainActor
145@Suite("SurveyModel context")
146struct SurveyModelContextTests {
147
148    @Test("The captured context is saved, and place answers record where they were given")
149    func placeCoordinate() throws {
150        let question = Question(
151            id: "place", prompt: "Where?", kind: .location, askOn: .random, order: 0,
152            modifiedAt: Date(timeIntervalSince1970: 0))
153        let model = SurveyModel(
154            kind: .manual, date: Date(), questions: [question],
155            vocabulary: ["place": [VocabularyEntry(id: "P1", text: "Home", useCount: 1)]])
156        let picker = try #require(model.placePickers["place"])
157        picker.toggle(try #require(picker.candidate(id: "P1")))
158
159        var context = Context()
160        context.location = LocationContext(
161            coordinate: Coordinate(latitude: 1.5, longitude: 2.5), horizontalAccuracy: 12)
162        let report = model.makeReport(now: Date(), context: context).report
163
164        #expect(report.context == context)
165        #expect(
166            report.responses.first?.value
167                == .place(PlaceAnswer(tokenID: "P1", coordinate: Coordinate(latitude: 1.5, longitude: 2.5), accuracy: 12)))
168    }
169}