← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/ReporterImporterTests.swift (7268B)

1import CoreData
2import Foundation
3import Testing
4
5@testable import Reportage
6
7@Suite("ReporterImporter")
8struct ReporterImporterTests {
9
10    private let persistence = makeTestPersistence()
11
12    private var importer: ReporterImporter { ReporterImporter(persistence: persistence) }
13
14    private func storedReports() async throws -> [Report] {
15        let context = persistence.newBackgroundContext()
16        return try await context.perform {
17            let request = ReportEntity.fetchRequest()
18            request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
19            return try context.fetch(request).map { try $0.report() }
20        }
21    }
22
23    private func storedQuestions() async throws -> [Question] {
24        let context = persistence.newBackgroundContext()
25        return try await context.perform {
26            let request = QuestionEntity.fetchRequest()
27            request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
28            return try context.fetch(request).map { try $0.question() }
29        }
30    }
31
32    @Test("The store holds exactly what the plan describes")
33    func roundTrip() async throws {
34        let now = Date(timeIntervalSince1970: 0)
35        let summary = try await importer.importArchive(try Fixtures.reporterExport(), now: now)
36        let plan = ReporterImportPlan(archive: try Fixtures.reporterArchive(), now: now)
37
38        #expect(summary.questionsInserted == 9)
39        #expect(summary.tokensInserted == 11)
40        #expect(summary.reportsInserted == 14)
41        #expect(summary.reportsAlreadyPresent == 0)
42        #expect(try await storedReports() == plan.reports)
43        #expect(Set(try await storedQuestions()) == Set(plan.questions))
44        #expect(Set(try await storedTokens()) == Set(plan.tokens))
45    }
46
47    private func storedTokens() async throws -> [Token] {
48        let context = persistence.newBackgroundContext()
49        return try await context.perform {
50            try context.fetch(TokenEntity.fetchRequest()).map { try $0.token() }
51        }
52    }
53
54    @Test("Re-importing keeps renamed tokens renamed")
55    func tokenRenamesSurvive() async throws {
56        _ = try await importer.importArchive(try Fixtures.reporterExport())
57        let walkingID = "C0000001-0000-4000-8000-000000000000"
58
59        let context = persistence.newBackgroundContext()
60        try await context.perform {
61            let request = TokenEntity.fetchRequest()
62            request.predicate = NSPredicate(format: "id == %@", walkingID)
63            let entity = try #require(try context.fetch(request).first)
64            var token = try entity.token()
65            token.text = "Walking outside"
66            try entity.update(from: token)
67            try context.save()
68        }
69
70        let summary = try await importer.importArchive(try Fixtures.reporterExport())
71        #expect(summary.tokensInserted == 0)
72        #expect(summary.tokensAlreadyPresent == 11)
73        #expect(try await storedTokens().first { $0.id == walkingID }?.text == "Walking outside")
74    }
75
76    @Test("Re-importing the same export changes nothing")
77    func idempotent() async throws {
78        let data = try Fixtures.reporterExport()
79        _ = try await importer.importArchive(data)
80        let before = try await storedReports()
81
82        let summary = try await importer.importArchive(data)
83        #expect(summary.questionsInserted == 0)
84        #expect(summary.questionsUpdated == 0)
85        #expect(summary.reportsInserted == 0)
86        #expect(summary.reportsAlreadyPresent == 14)
87        #expect(try await storedReports() == before)
88        #expect(try await storedQuestions().count == 9)
89    }
90
91    @Test("Importing a newer export adds only the new reports")
92    func incremental() async throws {
93        let older = try await importer.importArchive(try Fixtures.reporterExport(droppingLast: 2))
94        #expect(older.reportsInserted == 12)
95
96        let newer = try await importer.importArchive(try Fixtures.reporterExport())
97        #expect(newer.reportsInserted == 2)
98        #expect(newer.reportsAlreadyPresent == 12)
99        #expect(try await storedReports().count == 14)
100    }
101
102    @Test("Re-importing keeps question edits and only adds new choice options")
103    func questionEditsSurvive() async throws {
104        _ = try await importer.importArchive(try Fixtures.reporterExport())
105
106        let context = persistence.newBackgroundContext()
107        try await context.perform {
108            let request = QuestionEntity.fetchRequest()
109            for entity in try context.fetch(request) where entity.id == "default-question-1" {
110                var question = try entity.question()
111                question.prompt = "Slept well?"
112                question.options = ["Poorly"]
113                try entity.update(from: question)
114            }
115            try context.save()
116        }
117
118        let summary = try await importer.importArchive(try Fixtures.reporterExport())
119        #expect(summary.questionsUpdated == 1)
120        let question = try #require(
121            try await storedQuestions().first { $0.id == "default-question-1" })
122        #expect(question.prompt == "Slept well?")
123        #expect(question.options == ["Poorly", "Well"])
124    }
125
126    @Test("Importing archives the default questions, so the surveys ask Reporter's")
127    func defaultsArchived() async throws {
128        let now = Date(timeIntervalSince1970: 0)
129        try await ReportStore(persistence: persistence).seedDefaultQuestionsIfNeeded()
130        let defaults = DefaultQuestions.make().count
131
132        let summary = try await importer.importArchive(try Fixtures.reporterExport(), now: now)
133        #expect(summary.defaultQuestionsArchived == defaults)
134        let questions = try await storedQuestions()
135        #expect(questions.count == 9 + defaults)
136        #expect(
137            questions.filter { $0.id.hasPrefix(DefaultQuestions.idPrefix) }.allSatisfy { $0.archivedAt == now })
138        let plan = ReporterImportPlan(archive: try Fixtures.reporterArchive(), now: now)
139        #expect(Set(questions.filter { !$0.id.hasPrefix(DefaultQuestions.idPrefix) }) == Set(plan.questions))
140
141        let again = try await importer.importArchive(try Fixtures.reporterExport(), now: now)
142        #expect(again.defaultQuestionsArchived == 0)
143    }
144
145    @Test("The verifier finds no differences after an import")
146    func verifierPasses() async throws {
147        let data = try Fixtures.reporterExport()
148        _ = try await importer.importArchive(data)
149        let archive = try ReporterArchive(data: data)
150
151        let context = persistence.newBackgroundContext()
152        let mismatches = try await context.perform {
153            try ReporterImportVerifier.verify(archive, in: context)
154        }
155        #expect(mismatches.isEmpty)
156    }
157
158    @Test("The verifier reports a missing report")
159    func verifierCatchesMissing() async throws {
160        _ = try await importer.importArchive(try Fixtures.reporterExport(droppingLast: 1))
161        let archive = try Fixtures.reporterArchive()
162
163        let context = persistence.newBackgroundContext()
164        let mismatches = try await context.perform {
165            try ReporterImportVerifier.verify(archive, in: context)
166        }
167        #expect(mismatches.map(\.problem) == ["not in store"])
168    }
169}