← All repositories

reportage

A life-logging app for iPhone

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


Tests/Unit/SchemaMigrationTests.swift (7248B)

1import CoreData
2import Foundation
3import SQLite3
4import Testing
5
6@testable import Reportage
7
8/// The model has a single version. Changes that lightweight migration can
9/// infer still open existing stores, because a SQLite store keeps a copy of
10/// the model it was made with, which migration uses when the app no longer
11/// has that model.
12@Suite("Schema migration")
13struct SchemaMigrationTests {
14
15    private static var model: NSManagedObjectModel {
16        PersistenceController(inMemory: true).container.managedObjectModel
17    }
18
19    private static func attribute(
20        _ name: String, _ type: NSAttributeDescription.AttributeType, optional: Bool
21    ) -> NSAttributeDescription {
22        let attribute = NSAttributeDescription()
23        attribute.name = name
24        attribute.type = type
25        attribute.isOptional = optional
26        return attribute
27    }
28
29    /// The model as it was while imported reports kept their Reporter
30    /// originals. Its entities use plain managed objects, so it doesn't
31    /// claim the app's entity classes.
32    private static func legacyModel() -> NSManagedObjectModel {
33        let copy = model.copy() as! NSManagedObjectModel
34        for entity in copy.entities {
35            entity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
36        }
37        copy.entitiesByName["ReportEntity"]?.properties += [attribute("legacy", .binaryData, optional: true)]
38        return copy
39    }
40
41    /// The model as it was while reports had narrative attributes, before
42    /// the Health cache.
43    private static func narrativeModel() -> NSManagedObjectModel {
44        let copy = legacyModel()
45        copy.entities.removeAll { $0.name == "HealthEntity" }
46        copy.entitiesByName["ReportEntity"]?.properties.removeAll { $0.name == "health" }
47        let version = attribute("narrativeVersion", .integer16, optional: false)
48        version.defaultValue = 0
49        copy.entitiesByName["ReportEntity"]?.properties += [
50            attribute("narrative", .string, optional: true),
51            attribute("narrativeDraft", .string, optional: true),
52            version,
53        ]
54        return copy
55    }
56
57    /// Makes a store with `model` holding a report for each of `values`.
58    /// Everything that opened it is released on return, so migration can
59    /// replace it.
60    private static func makeStore(
61        at url: URL, model: NSManagedObjectModel, reports values: [[String: any Sendable]]
62    ) throws {
63        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
64        let store = try coordinator.addPersistentStore(type: .sqlite, at: url)
65        let context = NSManagedObjectContext(.privateQueue)
66        context.persistentStoreCoordinator = coordinator
67        try context.performAndWait {
68            let entity = try #require(coordinator.managedObjectModel.entitiesByName["ReportEntity"])
69            for values in values {
70                let report = NSManagedObject(entity: entity, insertInto: context)
71                report.setValuesForKeys(
72                    [
73                        "id": UUID(), "date": Date(), "modifiedAt": Date(), "kind": "manual",
74                        "state": "complete", "timeZone": "Asia/Tokyo", "trigger": "app",
75                    ].merging(values) { $1 })
76            }
77            try context.save()
78            context.reset()
79        }
80        try coordinator.remove(store)
81    }
82
83    /// Opens the store at `url` with the app's model, migrating it, and
84    /// returns its reports' IDs, closing it again so its file is complete.
85    private static func openMigrating(_ url: URL) throws -> [UUID?] {
86        let persistence = PersistenceController(storeURL: url)
87        let ids = try persistence.viewContext.fetch(ReportEntity.fetchRequest()).map(\.id)
88        let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(type: .sqlite, at: url)
89        #expect(model.isConfiguration(withName: nil, compatibleWithStoreMetadata: metadata))
90        let coordinator = persistence.container.persistentStoreCoordinator
91        for store in coordinator.persistentStores {
92            try coordinator.remove(store)
93        }
94        return ids
95    }
96
97    /// How many pages the database at `url` has, counting those still in
98    /// its write-ahead log, which the file's size doesn't.
99    private static func pageCount(_ url: URL) throws -> Int {
100        var database: OpaquePointer?
101        defer { sqlite3_close(database) }
102        try #require(sqlite3_open_v2(url.path, &database, SQLITE_OPEN_READONLY, nil) == SQLITE_OK)
103        var statement: OpaquePointer?
104        defer { sqlite3_finalize(statement) }
105        try #require(sqlite3_prepare_v2(database, "PRAGMA page_count", -1, &statement, nil) == SQLITE_OK)
106        try #require(sqlite3_step(statement) == SQLITE_ROW)
107        return Int(sqlite3_column_int64(statement, 0))
108    }
109
110    private static func temporaryStoreURL() throws -> URL {
111        let directory = URL.temporaryDirectory.appending(path: UUID().uuidString)
112        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
113        return directory.appending(path: "Store.sqlite")
114    }
115
116    @Test("The rebuilt legacy model matches the one stores were made with")
117    func legacyModelHash() {
118        // ReportEntity's version hash in builds with Reporter originals.
119        let hash = Data(base64Encoded: "RJN+/VCeLQPP68SRtVSZQBkDTecnABs7F4UQ6Xp0fBA=")
120        #expect(Self.legacyModel().entityVersionHashesByName["ReportEntity"] == hash)
121    }
122
123    @Test("A store with Reporter originals opens with its reports, and is rebuilt smaller")
124    func removedLegacy() throws {
125        let storeURL = try Self.temporaryStoreURL()
126        defer { try? FileManager.default.removeItem(at: storeURL.deletingLastPathComponent()) }
127        let ids = (0..<200).map { _ in UUID() }
128        try Self.makeStore(
129            at: storeURL, model: Self.legacyModel(),
130            reports: ids.map { ["id": $0, "legacy": Data((0..<3000).map { _ in UInt8.random(in: 0...255) })] })
131        let before = try Self.pageCount(storeURL)
132
133        #expect(Set(try Self.openMigrating(storeURL)) == Set(ids))
134        // 200 originals of 3 KB took at least 600 KB, about 150 pages.
135        #expect(try Self.pageCount(storeURL) < before - 120)
136    }
137
138    @Test("The rebuilt narrative model matches the one stores were made with")
139    func narrativeModelHash() {
140        // ReportEntity's version hash in builds with the narrative attributes.
141        let hash = Data(base64Encoded: "N1hJI1x585Fi2rRj1X/VbR984fbK4ewKwfzcEPOUFKE=")
142        #expect(Self.narrativeModel().entityVersionHashesByName["ReportEntity"] == hash)
143    }
144
145    @Test("A store made with the narrative attributes opens with its reports")
146    func removedAttributes() throws {
147        let storeURL = try Self.temporaryStoreURL()
148        defer { try? FileManager.default.removeItem(at: storeURL.deletingLastPathComponent()) }
149        let id = UUID()
150        try Self.makeStore(
151            at: storeURL, model: Self.narrativeModel(),
152            reports: [["id": id, "narrative": "Reading at the library.", "narrativeDraft": "Reading at Library."]])
153
154        #expect(try Self.openMigrating(storeURL) == [id])
155    }
156}