← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/ReportageExportTests.swift (7338B)

1import CoreData
2import Foundation
3import Testing
4
5@testable import Reportage
6
7@Suite("ReportageExport")
8struct ReportageExportTests {
9
10    private let persistence = makeTestPersistence()
11
12    private var exporter: ReportageExporter { ReportageExporter(persistence: persistence) }
13
14    private func exportData(
15        now: Date = Date(timeIntervalSince1970: 0)
16    ) async throws -> (summary: ReportageExportSummary, data: Data) {
17        let url = FileManager.default.temporaryDirectory
18            .appendingPathComponent("reportage-export-\(UUID().uuidString).json")
19        defer { try? FileManager.default.removeItem(at: url) }
20        let summary = try await exporter.export(to: url, now: now)
21        return (summary, try Data(contentsOf: url))
22    }
23
24    private func stored() async throws -> (questions: [Question], tokens: [Token], reports: [Report]) {
25        let context = persistence.newBackgroundContext()
26        return try await context.perform {
27            let reports = ReportEntity.fetchRequest()
28            reports.sortDescriptors = [
29                NSSortDescriptor(key: "date", ascending: true),
30                NSSortDescriptor(key: "id", ascending: true),
31            ]
32            return (
33                try context.fetch(QuestionEntity.fetchRequest()).map { try $0.question() },
34                try context.fetch(TokenEntity.fetchRequest()).map { try $0.token() },
35                try context.fetch(reports).map { try $0.report() }
36            )
37        }
38    }
39
40    private func insert(_ report: Report) async throws {
41        let context = persistence.newBackgroundContext()
42        try await context.perform {
43            try ReportEntity(context: context).update(from: report)
44            try context.save()
45        }
46    }
47
48    private func importFixture() async throws {
49        _ = try await ReporterImporter(persistence: persistence)
50            .importArchive(try Fixtures.reporterExport(), now: Date(timeIntervalSince1970: 0))
51    }
52
53    private static let sydneyReport = Report(
54        id: UUID(uuidString: "E0000001-0000-4000-8000-000000000000")!,
55        // 2025-01-15 09:30:00 in Sydney, which is +11:00 in January.
56        date: Date(timeIntervalSince1970: 1_736_893_800),
57        timeZone: "Australia/Sydney",
58        kind: .manual,
59        trigger: .app,
60        state: .complete,
61        completedAt: Date(timeIntervalSince1970: 1_736_893_860.25),
62        context: Context(
63            location: LocationContext(
64                coordinate: Coordinate(latitude: -33.87, longitude: 151.21),
65                timestamp: Date(timeIntervalSince1970: 1_736_893_790)
66            )
67        ),
68        responses: [
69            Response(questionID: "Q1", prompt: "How many?", value: .number(Decimal(string: "2.5")!)),
70            Response(questionID: "Q2", prompt: "Skipped?", value: nil),
71        ],
72        modifiedAt: Date(timeIntervalSince1970: 1_736_893_860)
73    )
74
75    @Test("An export of the imported fixture decodes to what the store holds")
76    func roundTrip() async throws {
77        try await importFixture()
78        let (summary, data) = try await exportData()
79        let export = try ReportageExport.decode(data)
80        let expected = try await stored()
81
82        #expect(summary == ReportageExportSummary(questions: 9, tokens: 11, reports: 14))
83        #expect(export.format == "reportage")
84        #expect(export.version == 1)
85        #expect(export.exportedAt == Date(timeIntervalSince1970: 0))
86        #expect(Set(try export.questions.map { try $0.question() }) == Set(expected.questions))
87        #expect(Set(export.tokens.map { $0.token() }) == Set(expected.tokens))
88        #expect(try export.reports.map { try $0.report() } == expected.reports)
89    }
90
91    @Test("The export is valid JSON with one record per line")
92    func layout() async throws {
93        try await importFixture()
94        let (_, data) = try await exportData()
95        let object = try JSONSerialization.jsonObject(with: data) as? [String: Any]
96        #expect((object?["reports"] as? [Any])?.count == 14)
97
98        let lines = String(decoding: data, as: UTF8.self).split(separator: "\n")
99        // The header, three array openings, three closings and one record per line.
100        let records = 9 + 11 + 14
101        #expect(lines.count == 7 + records)
102    }
103
104    @Test("Dates in a report use its time zone and others use UTC")
105    func dates() async throws {
106        try await insert(Self.sydneyReport)
107        let (_, data) = try await exportData(now: Date(timeIntervalSince1970: 1_800_000_000.5))
108        let text = String(decoding: data, as: UTF8.self)
109
110        #expect(text.contains(#""exportedAt":"2027-01-15T08:00:00.500Z""#))
111        #expect(text.contains(#""date":"2025-01-15T09:30:00+11:00""#))
112        #expect(text.contains(#""completedAt":"2025-01-15T09:31:00.250+11:00""#))
113        #expect(text.contains(#""timestamp":"2025-01-15T09:29:50+11:00""#))
114        #expect(text.contains(#""timeZone":"Australia/Sydney""#))
115        #expect(try ReportageExport.decode(data).reports.map { try $0.report() } == [Self.sydneyReport])
116    }
117
118    @Test("Response values keep their shape and skipped answers have no value")
119    func responses() async throws {
120        try await insert(Self.sydneyReport)
121        let text = String(decoding: try await exportData().data, as: UTF8.self)
122        #expect(text.contains(#"{"prompt":"How many?","questionID":"Q1","value":{"number":2.5}}"#))
123        #expect(text.contains(#"{"prompt":"Skipped?","questionID":"Q2"}"#))
124    }
125
126    @Test("Question surveys are written as names")
127    func askOn() throws {
128        let question = Question(
129            id: "Q", prompt: "P", kind: .yesNo, askOn: [.random, .bedtime], order: 0,
130            modifiedAt: Date(timeIntervalSince1970: 0))
131        let exported = ExportedQuestion(question)
132        #expect(exported.askOn == ["random", "bedtime"])
133        #expect(exported.options == nil)
134        #expect(try exported.question() == question)
135    }
136
137    @Test("Whether a question shows in the timeline is exported, and shown when missing")
138    func showsInTimeline() throws {
139        var question = Question(
140            id: "Q", prompt: "P", kind: .yesNo, askOn: [.random], order: 0,
141            modifiedAt: Date(timeIntervalSince1970: 0))
142        question.showsInTimeline = false
143        let exported = ExportedQuestion(question)
144        #expect(try exported.question() == question)
145
146        var older = exported
147        older.showsInTimeline = nil
148        #expect(try older.question().showsInTimeline)
149    }
150
151    @Test("An empty store exports empty arrays")
152    func empty() async throws {
153        let (summary, data) = try await exportData()
154        let export = try ReportageExport.decode(data)
155        #expect(summary == ReportageExportSummary())
156        #expect(export.questions.isEmpty && export.tokens.isEmpty && export.reports.isEmpty)
157    }
158
159    @Test("Other formats and newer versions are rejected")
160    func rejects() {
161        let other = Data(#"{"format":"reporter","version":1}"#.utf8)
162        #expect(throws: ReportageExportError.unknownFormat("reporter")) {
163            try ReportageExport.decode(other)
164        }
165        let newer = Data(#"{"format":"reportage","version":2}"#.utf8)
166        #expect(throws: ReportageExportError.unsupportedVersion(2)) {
167            try ReportageExport.decode(newer)
168        }
169    }
170}