← All repositories

reportage

A life-logging app for iPhone

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


Tests/Support/TestHelpers.swift (2071B)

1import Foundation
2import Testing
3
4@testable import Reportage
5
6/// Creates a fresh PersistenceController with in-memory storage for isolated testing.
7func makeTestPersistence() -> PersistenceController {
8    PersistenceController(inMemory: true)
9}
10
11enum Fixtures {
12    /// A hand-made Reporter export with invented data that mirrors the real
13    /// export's quirks: the junk prefix, +0900 timestamps for reports made
14    /// elsewhere, three weather eras, mixed number types, missing and unknown
15    /// `reportImpetus` values, skipped questions and so on.
16    static func reporterExport() throws -> Data {
17        let url = try #require(
18            Bundle(for: BundleToken.self).url(
19                forResource: "reporter-fixture", withExtension: "json")
20        )
21        return try Data(contentsOf: url)
22    }
23
24    static func reporterArchive() throws -> ReporterArchive {
25        try ReporterArchive(data: reporterExport())
26    }
27
28    /// Report IDs in the fixture, by the order they were made.
29    static func reportID(_ number: Int) -> UUID {
30        let hex = String(number, radix: 16, uppercase: true)
31        let short = String(repeating: "0", count: 4 - hex.count) + hex
32        let long = String(repeating: "0", count: 12 - hex.count) + hex
33        return UUID(uuidString: "0A1B2C3D-\(short)-4000-8000-\(long)")!
34    }
35
36    /// The fixture with its last `count` snapshots removed, as an older export
37    /// would be. The remaining bytes are untouched.
38    static func reporterExport(droppingLast count: Int) throws -> Data {
39        let data = try reporterExport()
40        let start = try #require(data.firstIndex(of: UInt8(ascii: "{")))
41        let members = try JSONSlicer.objectMembers(in: data, at: start)
42        let array = try #require(members.first { $0.key == "snapshots" }).range
43        let elements = try JSONSlicer.arrayElements(in: data, range: array)
44        let keptEnd = elements[elements.count - count - 1].upperBound
45        return data[..<keptEnd] + Data("]".utf8) + data[array.upperBound...]
46    }
47}
48
49private final class BundleToken {}