DomainDigTests/DomainViewModelStoreTests.swift

410 lines · 16862 bytes

  1import XCTest
  2@testable import DomainDig
  3
  4/// Every persisted property on the view model used to read from and write to
  5/// `UserDefaults.standard`, so no test could drive its lifecycle without
  6/// writing into the store the app on the same simulator is using. The store is
  7/// injected now. These cover the seam itself and the lifecycle rules that sit
  8/// on top of it: history pruning, recent-search truncation, tracking, and the
  9/// lookup generation that keeps a stale section result off a new snapshot.
 10@MainActor
 11final class DomainViewModelStoreTests: XCTestCase {
 12
 13    private var suiteName = ""
 14    private var scratch = UserDefaults.standard
 15
 16    /// History lives in a directory now, so the scratch store has two halves.
 17    private var historyLocation = HistoryFileStore.Location.default
 18
 19    override func setUpWithError() throws {
 20        try super.setUpWithError()
 21        suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
 22        scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
 23        historyLocation = HistoryFileStore.Location(
 24            root: URL(fileURLWithPath: NSTemporaryDirectory())
 25                .appendingPathComponent("DomainDigVMTest-\(UUID().uuidString)", isDirectory: true)
 26        )
 27    }
 28
 29    override func tearDown() {
 30        UserDefaults.standard.removePersistentDomain(forName: suiteName)
 31        HistoryFileStore.removeAll(at: historyLocation)
 32        super.tearDown()
 33    }
 34
 35    /// Releasing a main-actor-isolated object aborts the test runner on iOS
 36    /// 18.6 — finding E1, a Swift runtime bug in `MarkerItem::create` fixed by
 37    /// iOS 26.5. `Scripts/test.sh` runs the floor tier, so a view model that
 38    /// went out of scope would kill the whole run there. Holding every instance
 39    /// for the life of the process avoids the release and needs no app change.
 40    private static var retained: [DomainViewModel] = []
 41
 42    private func makeViewModel() -> DomainViewModel {
 43        let viewModel = DomainViewModel(defaults: scratch, historyLocation: historyLocation)
 44        Self.retained.append(viewModel)
 45        return viewModel
 46    }
 47
 48    private func makeEntry(domain: String, at timestamp: Date) -> HistoryEntry {
 49        HistoryEntry(
 50            identity: .init(domain: domain, timestamp: timestamp),
 51            inspection: .init(
 52                dnsSections: [],
 53                sslInfo: nil,
 54                httpHeaders: [],
 55                reachabilityResults: [],
 56                ipGeolocation: nil
 57            ),
 58            provenance: .init(resolverDisplayName: "Test Resolver", resolverURLString: "")
 59        )
 60    }
 61
 62    private func makeEntries(_ count: Int) -> [HistoryEntry] {
 63        (0..<count).map {
 64            makeEntry(
 65                domain: "domain\($0).example",
 66                at: Date(timeIntervalSince1970: 1_700_000_000 - Double($0))
 67            )
 68        }
 69    }
 70
 71    // MARK: The seam
 72
 73    func testTheViewModelReadsTheStoreItWasGiven() {
 74        DomainDataPortabilityService.saveRecentSearches(["a.example", "b.example"], defaults: scratch)
 75        DomainDataPortabilityService.saveTrackedDomains(
 76            [TrackedDomain(domain: "tracked.example", createdAt: Date(), updatedAt: Date())],
 77            defaults: scratch
 78        )
 79        DomainDataPortabilityService.saveHistoryEntries(makeEntries(3), defaults: scratch, historyLocation: historyLocation)
 80
 81        let viewModel = makeViewModel()
 82
 83        XCTAssertEqual(viewModel.recentSearches, ["a.example", "b.example"])
 84        XCTAssertEqual(viewModel.trackedDomains.map(\.domain), ["tracked.example"])
 85        XCTAssertEqual(viewModel.history.count, 3)
 86    }
 87
 88    /// The point of the seam: a test may drive the whole lifecycle without the
 89    /// app's own store on the same simulator changing underneath it.
 90    func testWritesLandInTheInjectedStoreAndNotTheDefaultOne() {
 91        let marker = "seam-\(UUID().uuidString).example"
 92        let viewModel = makeViewModel()
 93
 94        viewModel.addRecentSearch(marker)
 95
 96        XCTAssertEqual(DomainDataPortabilityService.loadRecentSearches(defaults: scratch).first, marker)
 97        XCTAssertFalse(
 98            DomainDataPortabilityService.loadRecentSearches(defaults: .standard).contains(marker),
 99            "a view model write reached UserDefaults.standard"
100        )
101    }
102
103    func testTwoViewModelsOnSeparateStoresDoNotSeeEachOther() throws {
104        let otherName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
105        defer { UserDefaults.standard.removePersistentDomain(forName: otherName) }
106        let other = try XCTUnwrap(UserDefaults(suiteName: otherName))
107
108        let first = makeViewModel()
109        let second = DomainViewModel(defaults: other, historyLocation: historyLocation)
110        Self.retained.append(second)
111
112        first.addRecentSearch("first.example")
113        second.addRecentSearch("second.example")
114
115        XCTAssertEqual(DomainDataPortabilityService.loadRecentSearches(defaults: scratch), ["first.example"])
116        XCTAssertEqual(DomainDataPortabilityService.loadRecentSearches(defaults: other), ["second.example"])
117    }
118
119    // MARK: Recent searches
120
121    func testRecentSearchesTruncateAtTheCap() {
122        let viewModel = makeViewModel()
123
124        for index in 0..<40 {
125            viewModel.addRecentSearch("domain\(index).example")
126        }
127
128        XCTAssertEqual(viewModel.recentSearches.count, 20)
129        XCTAssertEqual(viewModel.recentSearches.first, "domain39.example")
130        XCTAssertEqual(viewModel.recentSearches.last, "domain20.example")
131        XCTAssertEqual(DomainDataPortabilityService.loadRecentSearches(defaults: scratch).count, 20)
132    }
133
134    func testARepeatedSearchMovesToTheFrontWithoutDuplicating() {
135        let viewModel = makeViewModel()
136
137        viewModel.addRecentSearch("one.example")
138        viewModel.addRecentSearch("two.example")
139        viewModel.addRecentSearch("ONE.EXAMPLE")
140
141        XCTAssertEqual(viewModel.recentSearches, ["ONE.EXAMPLE", "two.example"])
142    }
143
144    // MARK: History pruning
145
146    func testTheAutoPruneOptionTrimsHistoryAndPersistsTheResult() {
147        let viewModel = makeViewModel()
148        viewModel.history = makeEntries(120)
149
150        viewModel.setHistoryAutoPruneOption(.keep50)
151
152        XCTAssertEqual(viewModel.history.count, 50)
153        XCTAssertEqual(DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation).count, 50)
154    }
155
156    /// Pruning trims from the front, so the rows kept must be the newest ones.
157    /// A trim that dropped the head would silently discard the only snapshots
158    /// the dashboard and the diff view read.
159    func testPruningKeepsTheNewestRows() {
160        let viewModel = makeViewModel()
161        let seeded = makeEntries(120)
162        viewModel.history = seeded
163
164        viewModel.setHistoryAutoPruneOption(.keep50)
165
166        XCTAssertEqual(viewModel.history.map(\.id), seeded.prefix(50).map(\.id))
167    }
168
169    /// A store already over the cap must still be readable. Pruning happens on
170    /// a write, not on a read, so loading must not drop rows.
171    func testAStoreAlreadyOverTheCapLoadsEveryRow() {
172        DomainDataPortabilityService.saveHistoryEntries(makeEntries(300), defaults: scratch, historyLocation: historyLocation)
173
174        XCTAssertEqual(makeViewModel().history.count, 300)
175    }
176
177    // MARK: Retention
178
179    /// At or under the tier's limit, the ceiling a new snapshot is stored
180    /// under is simply that limit.
181    func testTheGrowthLimitIsTheTierLimitWhenUnderIt() {
182        let limit = FeatureAccessService.historyRetentionLimit
183        let viewModel = makeViewModel()
184
185        viewModel.history = []
186        XCTAssertEqual(viewModel.growthHistoryLimit, limit)
187
188        viewModel.history = makeEntries(limit)
189        XCTAssertEqual(viewModel.growthHistoryLimit, limit)
190    }
191
192    /// Review Focus #6. A lapsed Pro+ subscriber holds more snapshots than the
193    /// new tier allows, so the ceiling is what they hold — the store stops
194    /// growing without deleting anything, rather than draining to the lower
195    /// tier a row per lookup.
196    func testTheGrowthLimitNeverFallsBelowWhatIsHeld() {
197        let limit = FeatureAccessService.historyRetentionLimit
198        let viewModel = makeViewModel()
199        viewModel.history = makeEntries(limit + 200)
200
201        XCTAssertEqual(viewModel.growthHistoryLimit, limit + 200)
202    }
203
204    /// The user's own auto-prune choice may ask for less than the tier allows,
205    /// never more.
206    func testTheRequestedLimitIsClampedByTheTier() {
207        let limit = FeatureAccessService.historyRetentionLimit
208        let viewModel = makeViewModel()
209
210        viewModel.setHistoryAutoPruneOption(.keep50)
211        XCTAssertEqual(viewModel.requestedHistoryLimit, min(50, limit))
212
213        viewModel.setHistoryAutoPruneOption(.unlimited)
214        XCTAssertEqual(viewModel.requestedHistoryLimit, limit, "unlimited is the tier's limit, not unbounded")
215    }
216
217    /// The user asked, so this one is allowed to delete.
218    func testTheUsersAutoPruneChoiceIsAllowedToPrune() {
219        let viewModel = makeViewModel()
220        viewModel.history = makeEntries(120)
221
222        viewModel.setHistoryAutoPruneOption(.keep50)
223
224        XCTAssertEqual(viewModel.history.count, 50)
225        XCTAssertEqual(
226            DomainDataPortabilityService.loadHistoryIndex(
227                defaults: scratch,
228                historyLocation: historyLocation
229            ).count,
230            50
231        )
232    }
233
234    func testUnlimitedAutoPruneTrimsToTheTierLimit() {
235        let limit = FeatureAccessService.historyRetentionLimit
236        let viewModel = makeViewModel()
237        viewModel.history = makeEntries(limit + 50)
238
239        viewModel.setHistoryAutoPruneOption(.unlimited)
240
241        XCTAssertEqual(viewModel.history.count, limit)
242    }
243
244    // MARK: The Settings caption
245
246    /// The old copy said auto-prune "defaults to unlimited", which was never
247    /// true: there has always been a hard ceiling.
248    func testTheRetentionCaptionNamesTheLimitAndNotUnlimited() {
249        let viewModel = makeViewModel()
250        viewModel.history = []
251
252        let caption = viewModel.historyRetentionCaption
253
254        XCTAssertTrue(caption.contains("\(FeatureAccessService.historyRetentionLimit)"))
255        XCTAssertFalse(caption.lowercased().contains("unlimited"))
256    }
257
258    /// Over the limit the caption says nothing already saved is removed, which
259    /// is what the store actually does.
260    func testTheRetentionCaptionReassuresWhenOverTheLimit() {
261        let viewModel = makeViewModel()
262        viewModel.history = makeEntries(FeatureAccessService.historyRetentionLimit + 10)
263
264        let caption = viewModel.historyRetentionCaption
265
266        XCTAssertTrue(caption.contains("Nothing already saved is removed"))
267    }
268
269    // MARK: Tracking
270
271    func testTrackingADomainPersistsToTheInjectedStore() {
272        let viewModel = makeViewModel()
273
274        XCTAssertTrue(viewModel.trackDomain(domain: "tracked.example", availabilityStatus: nil))
275
276        XCTAssertEqual(
277            DomainDataPortabilityService.loadTrackedDomains(defaults: scratch).map(\.domain),
278            ["tracked.example"]
279        )
280    }
281
282    /// The store key is the normalized domain, so a differently-cased repeat is
283    /// the same row. Returning true without inserting is what keeps the Track
284    /// button idempotent.
285    func testTrackingTheSameDomainInADifferentCaseDoesNotAddASecondRow() {
286        let viewModel = makeViewModel()
287
288        XCTAssertTrue(viewModel.trackDomain(domain: "tracked.example", availabilityStatus: nil))
289        XCTAssertTrue(viewModel.trackDomain(domain: "TRACKED.EXAMPLE", availabilityStatus: nil))
290
291        XCTAssertEqual(viewModel.trackedDomains.count, 1)
292        XCTAssertEqual(DomainDataPortabilityService.loadTrackedDomains(defaults: scratch).count, 1)
293    }
294
295    /// The gate is the live entitlement's ceiling rather than a pinned number:
296    /// the tier comes from `PurchaseService.shared`, which a cached purchase on
297    /// the simulator can change.
298    func testTrackingRefusesPastTheCeilingAndRaisesTheUpgradePrompt() {
299        let limit = FeatureAccessService.entitlements.trackedDomainLimit
300        let viewModel = makeViewModel()
301        viewModel.trackedDomains = (0..<limit).map {
302            TrackedDomain(domain: "filler\($0).example", createdAt: Date(), updatedAt: Date())
303        }
304
305        XCTAssertFalse(viewModel.trackDomain(domain: "overflow.example", availabilityStatus: nil))
306
307        XCTAssertNotNil(viewModel.upgradePrompt)
308        XCTAssertEqual(viewModel.trackedDomains.count, limit)
309    }
310
311    /// A lapsed subscriber holds more than the new ceiling. The limit gates
312    /// adding, not holding, so the rows above it must still load and read back.
313    func testAStoreOverTheCeilingStillLoadsEveryTrackedDomain() {
314        let over = FeatureAccessService.entitlements.trackedDomainLimit + 3
315        DomainDataPortabilityService.saveTrackedDomains(
316            (0..<over).map { TrackedDomain(domain: "held\($0).example", createdAt: Date(), updatedAt: Date()) },
317            defaults: scratch
318        )
319
320        let viewModel = makeViewModel()
321
322        XCTAssertEqual(viewModel.trackedDomains.count, over)
323        XCTAssertFalse(viewModel.canTrackCurrentDomain)
324    }
325
326    // MARK: Batch cancellation
327
328    /// Cancelling must resolve every row it started. A pending row left pending
329    /// reads as still running in the batch view, and the sweep summary counts
330    /// it as outstanding forever.
331    ///
332    /// Start and cancel both run on the main actor with no suspension between
333    /// them, so the batch task cannot begin before the cancel lands — the
334    /// transition under test is the synchronous one.
335    func testCancellingABatchResolvesEveryPendingRow() {
336        let viewModel = makeViewModel()
337
338        viewModel.startBatchLookup(domains: ["one.example", "two.example"], source: .manual)
339        XCTAssertTrue(viewModel.batchLookupRunning)
340        XCTAssertEqual(viewModel.batchResults.map(\.status), [.pending, .pending])
341
342        viewModel.cancelBatchLookup()
343
344        XCTAssertFalse(viewModel.batchLookupRunning)
345        XCTAssertNil(viewModel.batchCurrentDomain)
346        XCTAssertTrue(viewModel.batchResults.allSatisfy { $0.quickStatus == "Cancelled" })
347        XCTAssertFalse(viewModel.batchResults.contains { $0.status == .pending || $0.status == .running })
348    }
349
350    /// `batchLookupRunning` and the one-second throttle both refuse the second
351    /// start. Either way the running batch must not be replaced out from under
352    /// the results view.
353    func testASecondBatchStartDoesNotReplaceTheRunningOne() {
354        let viewModel = makeViewModel()
355
356        viewModel.startBatchLookup(domains: ["one.example"], source: .manual)
357        viewModel.startBatchLookup(domains: ["a.example", "b.example", "c.example"], source: .manual)
358
359        XCTAssertEqual(viewModel.batchTotalCount, 1)
360        XCTAssertEqual(viewModel.batchResults.count, 1)
361    }
362
363    // MARK: Lookup generation (Review Focus #4)
364
365    /// A second Run while the first lookup's sections are still in flight. Each
366    /// section applier checks `isCurrentLookup` before writing, so the first
367    /// lookup's generation must stop being current the moment the second
368    /// begins — otherwise a late DNS or TLS result lands on the new snapshot.
369    func testASecondLookupInvalidatesTheFirstOnesGeneration() {
370        let viewModel = makeViewModel()
371
372        let first = viewModel.beginLookup(for: "first.example")
373        XCTAssertTrue(viewModel.isCurrentLookup(first))
374
375        let second = viewModel.beginLookup(for: "second.example")
376
377        XCTAssertFalse(
378            viewModel.isCurrentLookup(first),
379            "a section result from the first lookup would still be applied"
380        )
381        XCTAssertTrue(viewModel.isCurrentLookup(second))
382        XCTAssertEqual(viewModel.searchedDomain, "second.example")
383    }
384
385    /// Two lookups of the same domain are still separate generations. Keying
386    /// the guard on the domain rather than the run would let a stale result
387    /// through on a re-run.
388    func testRerunningTheSameDomainStillStartsANewGeneration() {
389        let viewModel = makeViewModel()
390
391        let first = viewModel.beginLookup(for: "same.example")
392        let second = viewModel.beginLookup(for: "same.example")
393
394        XCTAssertNotEqual(first, second)
395        XCTAssertFalse(viewModel.isCurrentLookup(first))
396    }
397
398    /// Starting a lookup clears the previous run's snapshot identity, so the
399    /// history row the UI is pointing at cannot be mistaken for the new one.
400    func testBeginningALookupClearsThePreviousSnapshotIdentity() {
401        let viewModel = makeViewModel()
402        viewModel.history = makeEntries(1)
403
404        _ = viewModel.beginLookup(for: "fresh.example")
405
406        XCTAssertNil(viewModel.currentHistoryEntryID)
407        XCTAssertTrue(viewModel.hasRun)
408    }
409}
410