DomainDigTests/DataMigrationServiceTests.swift

122 lines · 5819 bytes

  1import XCTest
  2@testable import DomainDig
  3
  4/// Characterization tests for the versioned store-migration runner. They drive
  5/// `migrateIfNeeded` against legacy on-disk fixtures in an ephemeral
  6/// `UserDefaults` suite and pin the policy: forward-only, idempotent, and
  7/// non-destructive to a store written by a newer build.
  8///
  9/// The raw storage-key strings ("trackedDomains", "watchedDomains", the legacy
 10/// marker) are duplicated here on purpose — they are the on-disk contract, and
 11/// hard-coding them means an accidental rename shows up as a failing migration.
 12final class DataMigrationServiceTests: XCTestCase {
 13    private let suiteName = "DomainDigTests.migration"
 14    private var defaults: UserDefaults!
 15    private let base = Date(timeIntervalSince1970: 1_700_000_000)
 16
 17    /// v2 moves history into a directory, so an ephemeral `UserDefaults` suite
 18    /// is no longer enough to keep these off the real store.
 19    private var historyLocation = HistoryFileStore.Location.default
 20
 21    override func setUp() {
 22        super.setUp()
 23        defaults = UserDefaults(suiteName: suiteName)
 24        defaults.removePersistentDomain(forName: suiteName)
 25        historyLocation = HistoryFileStore.Location(
 26            root: URL(fileURLWithPath: NSTemporaryDirectory())
 27                .appendingPathComponent("DomainDigMigrationTest-\(UUID().uuidString)", isDirectory: true)
 28        )
 29    }
 30
 31    override func tearDown() {
 32        defaults.removePersistentDomain(forName: suiteName)
 33        defaults = nil
 34        HistoryFileStore.removeAll(at: historyLocation)
 35        super.tearDown()
 36    }
 37
 38    func testFreshStoreIsStampedAtCurrentVersion() {
 39        XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), 0)
 40
 41        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
 42
 43        XCTAssertEqual(
 44            DataMigrationService.storeSchemaVersion(defaults: defaults),
 45            DataMigrationService.currentStoreSchemaVersion
 46        )
 47    }
 48
 49    func testLegacyWatchedDomainsAreMigratedAndTheOldKeyIsDropped() throws {
 50        let legacy = [WatchedDomain(domain: "legacy.example", createdAt: base, lastKnownAvailability: .registered)]
 51        defaults.set(try JSONEncoder().encode(legacy), forKey: "watchedDomains")
 52
 53        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
 54
 55        let tracked = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
 56        XCTAssertEqual(tracked.map(\.domain), ["legacy.example"])
 57        XCTAssertNil(defaults.data(forKey: "watchedDomains"), "legacy key is dropped after migration")
 58        XCTAssertNotNil(defaults.data(forKey: "trackedDomains"), "data is rewritten under the current key")
 59        XCTAssertEqual(
 60            DataMigrationService.storeSchemaVersion(defaults: defaults),
 61            DataMigrationService.currentStoreSchemaVersion,
 62            "the runner stops short of this build's version"
 63        )
 64    }
 65
 66    func testMigrationDeduplicatesTheStoredBlobInPlace() throws {
 67        let dupes = [
 68            TrackedDomain(domain: "dupe.example", updatedAt: base.addingTimeInterval(-10)),
 69            TrackedDomain(domain: "DUPE.example", updatedAt: base)
 70        ]
 71        defaults.set(try JSONEncoder().encode(dupes), forKey: "trackedDomains")
 72
 73        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
 74
 75        let data = try XCTUnwrap(defaults.data(forKey: "trackedDomains"))
 76        let stored = try JSONDecoder().decode([TrackedDomain].self, from: data)
 77        XCTAssertEqual(stored.count, 1, "the persisted blob is deduplicated, not just the load result")
 78    }
 79
 80    func testMigrationIsIdempotent() throws {
 81        defaults.set(
 82            try JSONEncoder().encode([TrackedDomain(domain: "a.example", updatedAt: base)]),
 83            forKey: "trackedDomains"
 84        )
 85
 86        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
 87        let afterFirst = defaults.data(forKey: "trackedDomains")
 88
 89        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
 90        let afterSecond = defaults.data(forKey: "trackedDomains")
 91
 92        XCTAssertEqual(afterFirst, afterSecond, "a second run makes no further changes")
 93        XCTAssertEqual(
 94            DataMigrationService.storeSchemaVersion(defaults: defaults),
 95            DataMigrationService.currentStoreSchemaVersion
 96        )
 97    }
 98
 99    func testLegacyBooleanMarkerCountsAsVersionOne() {
100        defaults.set(true, forKey: "data.migrations.v3_4_0")
101
102        XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), 1)
103
104        // Already at v1, so the v1 step must not re-run: a leftover legacy blob
105        // is left exactly as found.
106        defaults.set(Data("x".utf8), forKey: "watchedDomains")
107        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
108        XCTAssertNotNil(defaults.data(forKey: "watchedDomains"), "v1 is treated as already applied; no re-run")
109    }
110
111    func testNewerStoreVersionIsNeverDowngradedOrRewritten() throws {
112        let future = DataMigrationService.currentStoreSchemaVersion + 1
113        defaults.set(future, forKey: DataMigrationService.storeSchemaVersionKey)
114        let blob = try JSONEncoder().encode([TrackedDomain(domain: "keep.example", updatedAt: base)])
115        defaults.set(blob, forKey: "trackedDomains")
116
117        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
118
119        XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), future, "must never downgrade")
120        XCTAssertEqual(defaults.data(forKey: "trackedDomains"), blob, "future-version data is left byte-for-byte")
121    }
122}