← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/RealExportVerificationTests.swift (7661B)

1import Foundation
2import Testing
3
4@testable import Reportage
5
6/// Imports the real Reporter export and verifies the store against it, report
7/// by report. Opt-in, because the export is personal data that only exists on
8/// the developer's machine:
9///
10///     TEST_RUNNER_REPORTAGE_REAL_EXPORT="$PWD/reporter-export.json" bash Scripts/test-unit.sh
11///
12/// Only aggregate findings are printed, never individual entries.
13@Suite("Real export verification")
14struct RealExportVerificationTests {
15
16    private static let exportPath = ProcessInfo.processInfo.environment["REPORTAGE_REAL_EXPORT"]
17
18    @Test(
19        "The real export imports without failures or mismatches",
20        .enabled(
21            if: exportPath != nil, "Set TEST_RUNNER_REPORTAGE_REAL_EXPORT to the export's path"),
22        .timeLimit(.minutes(10))
23    )
24    func realExport() async throws {
25        let url = URL(fileURLWithPath: try #require(Self.exportPath))
26        let data = try Data(contentsOf: url, options: .mappedIfSafe)
27        let persistence = makeTestPersistence()
28        let importer = ReporterImporter(persistence: persistence)
29
30        let clock = ContinuousClock()
31        let start = clock.now
32        let summary = try await importer.importArchive(data)
33        let importDuration = clock.now - start
34
35        let archive = try ReporterArchive(data: data)
36        let context = persistence.newBackgroundContext()
37        let mismatches = try await context.perform {
38            try ReporterImportVerifier.verify(archive, in: context)
39        }
40
41        let reimport = try await importer.importArchive(data)
42
43        var fallbackCounts: [String: Int] = [:]
44        for fallback in summary.fallbacks {
45            let label: String
46            switch fallback.reason {
47            case .timeZoneFromNeighbour(let country):
48                label = "zone from neighbour (country: \(country ?? "none"))"
49            case .timeZoneFromOffset: label = "zone from offset"
50            case .kindInferred(let impetus):
51                label = "kind inferred (impetus: \(impetus.map(String.init) ?? "none"))"
52            case .extraAnswerIgnored: label = "extra answer ignored"
53            case .unmatchedPrompt: label = "unmatched prompt"
54            }
55            fallbackCounts[label, default: 0] += 1
56        }
57        var mismatchCounts: [String: Int] = [:]
58        for mismatch in mismatches {
59            mismatchCounts[mismatch.problem, default: 0] += 1
60        }
61        let questions = try await context.perform {
62            try context.fetch(QuestionEntity.fetchRequest()).map { try $0.question() }
63        }
64
65        print(
66            """
67            REAL EXPORT SUMMARY
68              import time: \(importDuration)
69              questions: \(summary.questionCount), tokens: \(summary.tokenCount), reports: \(summary.reportCount), failures: \(summary.failures.count)
70              by kind: \(summary.reportsByKind.sorted { $0.key.rawValue < $1.key.rawValue })
71              by year: \(summary.reportsByYear.sorted { $0.key < $1.key })
72              by zone: \(summary.reportsByTimeZone.sorted { $0.key < $1.key })
73              answers by question: \(summary.answersByQuestion.sorted { $0.key < $1.key })
74              question kinds/askOn/option count: \(questions.sorted { $0.order < $1.order }.map { "\($0.id): \($0.kind) \($0.askOn.rawValue) \($0.options.count)" })
75              fallbacks: \(fallbackCounts.sorted { $0.key < $1.key })
76              warnings: \(summary.warnings.count)
77              mismatches: \(mismatchCounts.sorted { $0.key < $1.key })
78              re-import: inserted \(reimport.reportsInserted), already present \(reimport.reportsAlreadyPresent), tokens inserted \(reimport.tokensInserted)
79            """
80        )
81
82        #expect(summary.failures.isEmpty)
83        #expect(mismatches.isEmpty)
84        #expect(reimport.reportsInserted == 0)
85        #expect(reimport.tokensInserted == 0)
86        #expect(reimport.reportsAlreadyPresent == summary.reportCount)
87    }
88
89    @Test(
90        "The real archive exports and reads back as the store holds it",
91        .enabled(
92            if: exportPath != nil, "Set TEST_RUNNER_REPORTAGE_REAL_EXPORT to the export's path"),
93        .timeLimit(.minutes(10))
94    )
95    func reportageExport() async throws {
96        let url = URL(fileURLWithPath: try #require(Self.exportPath))
97        let persistence = makeTestPersistence()
98        _ = try await ReporterImporter(persistence: persistence).importArchive(at: url)
99
100        // The importer stamps questions and tokens with the time of the
101        // import, and the format keeps dates to the millisecond.
102        func exportable(_ date: Date) -> Date {
103            ExportDates.date(from: ExportDates.string(from: date, in: .gmt)) ?? date
104        }
105
106        let context = persistence.newBackgroundContext()
107        var (questions, tokens, reports) = try await context.perform {
108            let request = ReportEntity.fetchRequest()
109            request.sortDescriptors = [
110                NSSortDescriptor(key: "date", ascending: true),
111                NSSortDescriptor(key: "id", ascending: true),
112            ]
113            return (
114                Set(try context.fetch(QuestionEntity.fetchRequest()).map { try $0.question() }),
115                Set(try context.fetch(TokenEntity.fetchRequest()).map { try $0.token() }),
116                try context.fetch(request).map { try $0.report() }
117            )
118        }
119
120        questions = Set(
121            questions.map {
122                var question = $0
123                question.modifiedAt = exportable(question.modifiedAt)
124                return question
125            })
126        tokens = Set(
127            tokens.map {
128                var token = $0
129                token.modifiedAt = exportable(token.modifiedAt)
130                return token
131            })
132
133        let exporter = ReportageExporter(persistence: persistence)
134        let directory = FileManager.default.temporaryDirectory
135        let clock = ContinuousClock()
136        let file = directory.appendingPathComponent("reportage-real-\(UUID().uuidString).json")
137        defer { try? FileManager.default.removeItem(at: file) }
138
139        let start = clock.now
140        let summary = try await exporter.export(to: file)
141        let exportDuration = clock.now - start
142        let data = try Data(contentsOf: file)
143
144        let readStart = clock.now
145        let export = try ReportageExport.decode(data)
146        let readDuration = clock.now - readStart
147
148        // Counted rather than compared with #expect, which would print
149        // the records themselves on a failure.
150        let questionsMatch = Set(try export.questions.map { try $0.question() }) == questions
151        let tokensMatch = Set(export.tokens.map { $0.token() }) == tokens
152        var reportMismatches = 0
153        for (exported, stored) in zip(export.reports, reports) where try exported.report() != stored {
154            reportMismatches += 1
155        }
156        let countsMatch = export.reports.count == reports.count
157
158        print(
159            """
160            REAL ARCHIVE EXPORT SUMMARY
161              size: \(ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: .file)), export time: \(exportDuration), read time: \(readDuration)
162              questions: \(summary.questions), tokens: \(summary.tokens), reports: \(summary.reports)
163              questions match: \(questionsMatch), tokens match: \(tokensMatch), report counts match: \(countsMatch)
164              report mismatches: \(reportMismatches)
165            """
166        )
167
168        #expect(questionsMatch)
169        #expect(tokensMatch)
170        #expect(countsMatch)
171        #expect(reportMismatches == 0)
172    }
173}