← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/ReportageImporterTests.swift (8198B)

1import CoreData
2import Foundation
3import Testing
4
5@testable import Reportage
6
7@Suite("ReportageImporter")
8struct ReportageImporterTests {
9
10    private static let report = Report(
11        id: UUID(uuidString: "E0000002-0000-4000-8000-000000000000")!,
12        date: Date(timeIntervalSince1970: 1_736_893_800),
13        timeZone: "Australia/Sydney",
14        kind: .manual,
15        trigger: .app,
16        state: .complete,
17        completedAt: Date(timeIntervalSince1970: 1_736_893_860),
18        responses: [Response(questionID: "Q1", prompt: "How many?", value: .number(2))],
19        modifiedAt: Date(timeIntervalSince1970: 1_736_893_860)
20    )
21
22    private static func edited(_ report: Report, value: Decimal, at seconds: TimeInterval) -> Report {
23        var report = report
24        report.responses = [Response(questionID: "Q1", prompt: "How many?", value: .number(value))]
25        report.modifiedAt = report.modifiedAt.addingTimeInterval(seconds)
26        return report
27    }
28
29    private static func export(_ persistence: PersistenceController) async throws -> Data {
30        let url = FileManager.default.temporaryDirectory
31            .appendingPathComponent("reportage-import-\(UUID().uuidString).json")
32        defer { try? FileManager.default.removeItem(at: url) }
33        _ = try await ReportageExporter(persistence: persistence).export(to: url)
34        return try Data(contentsOf: url)
35    }
36
37    private static func insert(_ report: Report, into persistence: PersistenceController) async throws {
38        let context = persistence.newBackgroundContext()
39        try await context.perform {
40            try ReportEntity(context: context).update(from: report)
41            try context.save()
42        }
43    }
44
45    private static func stored(
46        _ persistence: PersistenceController
47    ) async throws -> (questions: Set<Question>, tokens: Set<Token>, reports: [Report]) {
48        let context = persistence.newBackgroundContext()
49        return try await context.perform {
50            let reports = ReportEntity.fetchRequest()
51            reports.sortDescriptors = [
52                NSSortDescriptor(key: "date", ascending: true),
53                NSSortDescriptor(key: "id", ascending: true),
54            ]
55            return (
56                Set(try context.fetch(QuestionEntity.fetchRequest()).map { try $0.question() }),
57                Set(try context.fetch(TokenEntity.fetchRequest()).map { try $0.token() }),
58                try context.fetch(reports).map { try $0.report() }
59            )
60        }
61    }
62
63    /// An export of the Reporter fixture, as made by another store.
64    private static func fixtureExport() async throws -> (data: Data, source: PersistenceController) {
65        let source = makeTestPersistence()
66        _ = try await ReporterImporter(persistence: source)
67            .importArchive(try Fixtures.reporterExport(), now: Date(timeIntervalSince1970: 0))
68        return (try await export(source), source)
69    }
70
71    @Test("Importing an export into an empty store restores it exactly")
72    func restore() async throws {
73        let (data, source) = try await Self.fixtureExport()
74        let target = makeTestPersistence()
75        let summary = try await ReportageImporter(persistence: target).importArchive(data)
76
77        #expect(summary.questions == .init(inserted: 9))
78        #expect(summary.tokens == .init(inserted: 11))
79        #expect(summary.reports == .init(inserted: 14))
80        #expect(summary.failures.isEmpty)
81        let expected = try await Self.stored(source)
82        let restored = try await Self.stored(target)
83        #expect(restored.questions == expected.questions)
84        #expect(restored.tokens == expected.tokens)
85        #expect(restored.reports == expected.reports)
86    }
87
88    @Test("Importing the same export again changes nothing")
89    func idempotent() async throws {
90        let (data, _) = try await Self.fixtureExport()
91        let target = makeTestPersistence()
92        let importer = ReportageImporter(persistence: target)
93        _ = try await importer.importArchive(data)
94        let before = try await Self.stored(target)
95
96        let again = try await importer.importArchive(data)
97        #expect(again.questions == .init(unchanged: 9))
98        #expect(again.tokens == .init(unchanged: 11))
99        #expect(again.reports == .init(unchanged: 14))
100        let after = try await Self.stored(target)
101        #expect(after.questions == before.questions)
102        #expect(after.reports == before.reports)
103    }
104
105    @Test("A record is replaced only when the export's copy is newer")
106    func newerWins() async throws {
107        let source = makeTestPersistence()
108        try await Self.insert(Self.report, into: source)
109        let data = try await Self.export(source)
110
111        let newer = makeTestPersistence()
112        let edited = Self.edited(Self.report, value: 3, at: 60)
113        try await Self.insert(edited, into: newer)
114        let kept = try await ReportageImporter(persistence: newer).importArchive(data)
115        #expect(kept.reports == .init(unchanged: 1))
116        #expect(try await Self.stored(newer).reports == [edited])
117
118        let older = makeTestPersistence()
119        try await Self.insert(Self.edited(Self.report, value: 3, at: -60), into: older)
120        let replaced = try await ReportageImporter(persistence: older).importArchive(data)
121        #expect(replaced.reports == .init(updated: 1))
122        #expect(try await Self.stored(older).reports == [Self.report])
123        let context = older.newBackgroundContext()
124        let responses = try await context.perform {
125            try context.count(for: ResponseEntity.fetchRequest())
126        }
127        #expect(responses == 1)
128    }
129
130    @Test("Edits to default questions win over a fresh install's defaults")
131    func editedDefaults() async throws {
132        let source = makeTestPersistence()
133        let store = ReportStore(persistence: source)
134        try await store.seedDefaultQuestionsIfNeeded()
135        var question = try #require(try await store.allQuestions().first)
136        question.prompt = "Reworded?"
137        question.archivedAt = Date(timeIntervalSince1970: 100)
138        question.modifiedAt = Date(timeIntervalSince1970: 100)
139        try await store.save([question])
140        let data = try await Self.export(source)
141
142        let fresh = makeTestPersistence()
143        try await ReportStore(persistence: fresh).seedDefaultQuestionsIfNeeded()
144        let summary = try await ReportageImporter(persistence: fresh).importArchive(data)
145        #expect(summary.questions.updated == 1)
146        #expect(summary.questions.unchanged == DefaultQuestions.make().count - 1)
147        #expect(try await Self.stored(fresh).questions.contains(question))
148    }
149
150    @Test("A report that can't be read is skipped and the rest are imported")
151    func unreadableReport() async throws {
152        let (data, _) = try await Self.fixtureExport()
153        var lines = String(decoding: data, as: UTF8.self).components(separatedBy: "\n")
154        let first = try #require(lines.firstIndex(of: "\"reports\":[")) + 1
155        lines[first] = #"{"id":"not a report"},"#
156        let damaged = Data(lines.joined(separator: "\n").utf8)
157
158        let summary = try await ReportageImporter(persistence: makeTestPersistence())
159            .importArchive(damaged)
160        #expect(summary.reports == .init(inserted: 13))
161        #expect(summary.failures.map(\.index) == [0])
162    }
163
164    @Test("Newer versions of the format are rejected")
165    func newerVersion() async throws {
166        let data = Data(#"{"format":"reportage","version":2,"questions":[],"tokens":[],"reports":[]}"#.utf8)
167        await #expect(throws: ReportageExportError.unsupportedVersion(2)) {
168            try await ReportageImporter(persistence: makeTestPersistence()).importArchive(data)
169        }
170    }
171
172    @Test("Reporter and Reportage exports are told apart")
173    func format() async throws {
174        #expect(try ArchiveFormat(data: Fixtures.reporterExport()) == .reporter)
175        let export = try await Self.fixtureExport().data
176        #expect(try ArchiveFormat(data: export) == .reportage)
177        #expect(throws: ArchiveFormat.Error.noJSONObject) {
178            try ArchiveFormat(data: Data("[]".utf8))
179        }
180    }
181}