Commit 00258de594

00258de594b6be23c73a86837b4a772d6110554b

parent: ee19a31ad8

Unsigned

cmc <hello@cleberg.net> · 2026-10-26 02:45 UTC

Cover the sync store and the Local API's success paths (!47)

Closes C7's two remaining gaps. Both turned out to be seam problems rather than
unwillingness, which is why they sat open.

**`CloudSyncService`.** It already took a `defaults:` — the initialiser was just
`private`, so the only instance was `shared` on `UserDefaults.standard`, and
`CloudSyncMergeTests` says so in its own header: "`CloudSyncService` itself
cannot be built in a test." Covering a deletion would have written to the
simulator's shared defaults. The initialiser is internal now, matching
`DomainViewModel`'s from W4, and `loadTombstones` is readable.

`CloudSyncStoreTests` covers what a deletion actually records: the normalized
identifier (a tombstone under the typed spelling would not suppress the row it
means to), the entity type, the newer of two deletions of the same domain, a
reset writing one each, a domain and a workflow coexisting — and that none of it
reaches `.standard`. The merge *decisions* were covered by !7; the service that
stores them was not, and "losing or resurrecting a user's data" includes a
tombstone written somewhere nothing reads back.

**The Local API's success paths.** `LocalAPIRequestHandler` now takes a
`defaults:` and a `historyLocation:` and threads them through the thirteen reads
and writes that were calling `DomainDataPortabilityService` and
`MonitoringStorage` with their default argument. `LocalAPISuccessTests` answers
`/portfolio`, `/domains`, `/domains/{domain}` and its `domain_not_found` 404,
`/domains/{domain}/history`, `/events` and `/monitoring` from a scratch store,
and checks that auth still runs ahead of the store so a seeded store is no way
around a missing token.

`/inspect` stays uncovered, and deliberately: it runs a live lookup, which is a
network dependency rather than a store one. `LocalAPIRoutingTests`' header said
the success paths were unreachable — no longer true, so it now names the one
that still is.

22 new tests, 375 green on iOS 18.6 and 27.0. Ratchet unchanged at 280.

Separately, the catalogue is updated: C7 is recorded closed, and **A2's
remainder is withdrawn** rather than left looking like pending work. The
view-model half landed in !30; what was left is `LookupSnapshot` (75 stored
properties), `HistoryEntry` and `DomainReport` — the persisted store format and
the locked `v1` export contract. I measured that duplication at about 12% of the
view model during !33, and moving code between those types was already shown not
to be the route to a smaller file. Changing them risks the store format and a
contract `v1` consumers depend on for a gain of that size, so it is withdrawn on
the measurement, as I2 was.

Layout: unified · split

DomainDig/CloudSyncService.swift +8 −2
@@ -165,7 +165,12 @@ final class CloudSyncService {
165165 static let changeTokenPrefix = "cloudSync.changeToken."
166166 }
167167
168 private init(defaults: UserDefaults = .standard) {
168 /// Injectable so the tombstone paths can be exercised against a scratch
169 /// store. Every write below goes through `defaults`, and C7's remaining gap
170 /// was that nothing could prove it: with a private init the only instance
171 /// was `shared`, on `.standard`, and covering a deletion meant polluting
172 /// the simulator the suite runs on. The app still uses `shared`.
173 init(defaults: UserDefaults = .standard) {
169174 self.defaults = defaults
170175 self.container = nil
171176 self.privateDatabase = nil
@@ -835,7 +840,8 @@ final class CloudSyncService {
835840 saveTombstones(tombstones)
836841 }
837842
838 private func loadTombstones() -> [SyncTombstone] {
843 /// Internal so a test can read back what a deletion recorded.
844 func loadTombstones() -> [SyncTombstone] {
839845 guard let data = defaults.data(forKey: StorageKey.tombstones),
840846 let tombstones = try? decoder.decode([SyncTombstone].self, from: data) else {
841847 return []
DomainDig/LocalAPIService.swift +26 −13
@@ -521,6 +521,19 @@ enum LocalAPIRoute: Equatable {
521521}
522522
523523struct LocalAPIRequestHandler {
524 /// Injectable so the success paths can be answered from a scratch store.
525 /// They read the real one through `DomainDataPortabilityService` and
526 /// `MonitoringStorage`, which both take a `defaults:`; nothing was passing
527 /// one, so the only way to exercise `/portfolio` or `/domains` was against
528 /// the simulator's shared defaults (C7).
529 let defaults: UserDefaults
530 let historyLocation: HistoryFileStore.Location
531
532 init(defaults: UserDefaults = .standard, historyLocation: HistoryFileStore.Location = .default) {
533 self.defaults = defaults
534 self.historyLocation = historyLocation
535 }
536
524537 private let encoder = LocalAPIContract.makeEncoder()
525538
526539 private let decoder: JSONDecoder = {
@@ -545,7 +558,7 @@ struct LocalAPIRequestHandler {
545558 case .portfolio:
546559 return successResponse(PortfolioPayload(summary: buildPortfolioSummary()))
547560 case .domains:
548 return successResponse(DomainListPayload(domains: DomainDataPortabilityService.loadTrackedDomains()))
561 return successResponse(DomainListPayload(domains: DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)))
549562 case let .domainDetails(domain):
550563 return domainDetailsResponse(for: domain)
551564 case let .domainHistory(domain):
@@ -595,7 +608,7 @@ struct LocalAPIRequestHandler {
595608
596609 private func domainDetailsResponse(for domain: String) -> LocalAPIHTTPResponse {
597610 let normalized = normalizedDomain(domain)
598 let trackedDomain = DomainDataPortabilityService.loadTrackedDomains().first {
611 let trackedDomain = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults).first {
599612 $0.domain.caseInsensitiveCompare(normalized) == .orderedSame
600613 }
601614 let history = historyEntries(for: normalized)
@@ -652,20 +665,20 @@ struct LocalAPIRequestHandler {
652665 return .error(statusCode: 400, code: "invalid_domain", message: "A valid domain is required.")
653666 }
654667
655 var trackedDomains = DomainDataPortabilityService.loadTrackedDomains()
668 var trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
656669 guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame }) else {
657670 return .error(statusCode: 404, code: "domain_not_found", message: "Tracked domain \(normalized) was not found.")
658671 }
659672
660673 trackedDomains[index].monitoringEnabled = enabled
661674 trackedDomains[index].updatedAt = Date()
662 DomainDataPortabilityService.saveTrackedDomains(trackedDomains)
675 DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
663676
664677 let sanitizedSettings = MonitoringStorage.sanitizeSettings(
665 MonitoringStorage.loadSettings(),
678 MonitoringStorage.loadSettings(defaults: defaults),
666679 trackedDomains: trackedDomains
667680 )
668 MonitoringStorage.saveSettings(sanitizedSettings)
681 MonitoringStorage.saveSettings(sanitizedSettings, defaults: defaults)
669682
670683 await MainActor.run {
671684 _ = DomainMonitoringScheduler.shared.syncSchedule()
@@ -680,8 +693,8 @@ struct LocalAPIRequestHandler {
680693 }
681694
682695 private func buildPortfolioSummary() -> PortfolioSummary {
683 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains()
684 let history = DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
696 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
697 let history = DomainDataPortabilityService.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
685698
686699 var healthyCount = 0
687700 var warningCount = 0
@@ -724,8 +737,8 @@ struct LocalAPIRequestHandler {
724737 }
725738
726739 private func monitoringPayload() -> MonitoringPayload {
727 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains()
728 let settings = MonitoringStorage.sanitizeSettings(MonitoringStorage.loadSettings(), trackedDomains: trackedDomains)
740 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
741 let settings = MonitoringStorage.sanitizeSettings(MonitoringStorage.loadSettings(defaults: defaults), trackedDomains: trackedDomains)
729742
730743 return MonitoringPayload(
731744 isEnabled: settings.isEnabled,
@@ -744,7 +757,7 @@ struct LocalAPIRequestHandler {
744757 }
745758
746759 private func recentEvents() -> [RecentEventPayload] {
747 MonitoringStorage.loadLogs()
760 MonitoringStorage.loadLogs(defaults: defaults)
748761 .prefix(25)
749762 .flatMap { log in
750763 log.checkedDomains.map { result in
@@ -761,13 +774,13 @@ struct LocalAPIRequestHandler {
761774
762775 private func historyEntries(for domain: String) -> [HistoryEntry] {
763776 let normalized = normalizedDomain(domain)
764 return DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default).filter {
777 return DomainDataPortabilityService.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation).filter {
765778 $0.domain.caseInsensitiveCompare(normalized) == .orderedSame
766779 }
767780 }
768781
769782 private func latestHistoryEntry(for domain: String, history: [HistoryEntry]? = nil) -> HistoryEntry? {
770 let entries = history ?? DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
783 let entries = history ?? DomainDataPortabilityService.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
771784 let normalized = normalizedDomain(domain)
772785 return entries.first { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame }
773786 }
DomainDigTests/CloudSyncStoreTests.swift added +186
@@ -0,0 +1,186 @@
1import XCTest
2@testable import DomainDig
3
4/// C7's first remaining gap: the merge *decisions* were covered (!7), but the
5/// service that stores them was not, because a private initialiser meant the
6/// only instance was `shared` on `UserDefaults.standard` and covering a
7/// deletion would have polluted the simulator the suite runs on.
8///
9/// What these assert is that a deletion is recorded, is recorded correctly, and
10/// is recorded *in the injected store* — losing or resurrecting a user's
11/// tracked domains is the failure mode C7 called out, and the second half of
12/// that is a tombstone written somewhere nothing reads back.
13@MainActor
14final class CloudSyncStoreTests: XCTestCase {
15
16 private var suiteName = ""
17 private var scratch = UserDefaults.standard
18
19 /// Releasing a main-actor-isolated object aborts the runner on iOS 18.6
20 /// (E1), and `Scripts/test.sh` runs that tier. `CloudSyncService` also
21 /// cancels a network path monitor in `deinit`, so it is never released.
22 private static var retained: [CloudSyncService] = []
23
24 override func setUpWithError() throws {
25 try super.setUpWithError()
26 suiteName = "net.cleberg.DomainDig.tests.sync.\(UUID().uuidString)"
27 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
28 }
29
30 override func tearDown() {
31 UserDefaults.standard.removePersistentDomain(forName: suiteName)
32 super.tearDown()
33 }
34
35 private func makeService() -> CloudSyncService {
36 let service = CloudSyncService(defaults: scratch)
37 Self.retained.append(service)
38 return service
39 }
40
41 private func trackedDomain(_ domain: String) -> TrackedDomain {
42 TrackedDomain(domain: domain, createdAt: Date(), updatedAt: Date())
43 }
44
45 // MARK: Tracked domains
46
47 func testDeletingATrackedDomainRecordsATombstone() {
48 let service = makeService()
49 let deletedAt = Date(timeIntervalSince1970: 1_700_000_000)
50
51 service.recordTrackedDomainDeletion(trackedDomain("example.com"), deletedAt: deletedAt)
52
53 let tombstones = service.loadTombstones()
54 XCTAssertEqual(tombstones.count, 1)
55 XCTAssertEqual(tombstones.first?.entityType, .trackedDomain)
56 XCTAssertEqual(tombstones.first?.identifier, "example.com")
57 XCTAssertEqual(tombstones.first?.deletedAt, deletedAt)
58 }
59
60 /// The identifier is the normalized domain, because that is the key the
61 /// merge matches rows on. A tombstone under the typed spelling would not
62 /// suppress the row it is meant to.
63 func testTheTombstoneIdentifierIsNormalized() {
64 let service = makeService()
65
66 service.recordTrackedDomainDeletion(trackedDomain(" WWW.Example.COM "))
67
68 XCTAssertEqual(
69 service.loadTombstones().first?.identifier,
70 CloudSyncMerge.normalizeDomain(" WWW.Example.COM ")
71 )
72 }
73
74 func testADomainThatNormalizesToNothingRecordsNoTombstone() {
75 let service = makeService()
76
77 service.recordTrackedDomainDeletion(trackedDomain(" "))
78
79 XCTAssertTrue(service.loadTombstones().isEmpty)
80 }
81
82 // MARK: Workflows
83
84 func testDeletingAWorkflowRecordsATombstoneUnderItsID() {
85 let service = makeService()
86 let workflow = DomainWorkflow(name: "Nightly", domains: ["example.com"])
87
88 service.recordWorkflowDeletion(workflow)
89
90 let tombstones = service.loadTombstones()
91 XCTAssertEqual(tombstones.count, 1)
92 XCTAssertEqual(tombstones.first?.entityType, .workflow)
93 XCTAssertEqual(tombstones.first?.identifier, workflow.id.uuidString)
94 }
95
96 /// A domain and a workflow can share an identifier without colliding,
97 /// because the entity type is part of the key.
98 func testADomainAndAWorkflowTombstoneCoexist() {
99 let service = makeService()
100 let workflow = DomainWorkflow(name: "Nightly", domains: [])
101
102 service.recordTrackedDomainDeletion(trackedDomain("example.com"))
103 service.recordWorkflowDeletion(workflow)
104
105 XCTAssertEqual(Set(service.loadTombstones().map(\.entityType)), [.trackedDomain, .workflow])
106 }
107
108 // MARK: Re-recording
109
110 /// Deleting the same domain twice leaves one tombstone, with the later
111 /// date — `latestTombstones` dedupes by identifier and this is the write
112 /// path feeding it.
113 func testDeletingTheSameDomainTwiceKeepsTheNewerTombstone() {
114 let service = makeService()
115 let older = Date(timeIntervalSince1970: 1_700_000_000)
116 let newer = older.addingTimeInterval(60)
117
118 service.recordTrackedDomainDeletion(trackedDomain("example.com"), deletedAt: older)
119 service.recordTrackedDomainDeletion(trackedDomain("example.com"), deletedAt: newer)
120
121 let tombstones = service.loadTombstones()
122 XCTAssertEqual(tombstones.count, 1)
123 XCTAssertEqual(tombstones.first?.deletedAt, newer)
124 }
125
126 // MARK: The injected store
127
128 /// The assertion C7 is actually about. Every tombstone write goes through
129 /// the injected store, so a test can exercise deletions without writing to
130 /// the simulator's shared defaults.
131 func testNothingIsWrittenToTheStandardStore() throws {
132 let key = "cloudSync.tombstones"
133 let before = UserDefaults.standard.data(forKey: key)
134 let service = makeService()
135
136 service.recordTrackedDomainDeletion(trackedDomain("scratch-only.example"))
137
138 XCTAssertFalse(service.loadTombstones().isEmpty, "the scratch store has it")
139 XCTAssertEqual(
140 UserDefaults.standard.data(forKey: key),
141 before,
142 "the standard store must be untouched"
143 )
144 }
145
146 /// A second service on the same store reads what the first wrote, which is
147 /// what makes the tombstone survive a launch.
148 func testTombstonesSurviveAFreshServiceOnTheSameStore() {
149 let first = makeService()
150 first.recordTrackedDomainDeletion(trackedDomain("example.com"))
151
152 let second = makeService()
153
154 XCTAssertEqual(second.loadTombstones().map(\.identifier), ["example.com"])
155 }
156
157 /// And a service on a different store sees none of it.
158 func testAnotherStoreSeesNoTombstones() throws {
159 let first = makeService()
160 first.recordTrackedDomainDeletion(trackedDomain("example.com"))
161
162 let otherName = "net.cleberg.DomainDig.tests.sync.other.\(UUID().uuidString)"
163 let other = try XCTUnwrap(UserDefaults(suiteName: otherName))
164 defer { UserDefaults.standard.removePersistentDomain(forName: otherName) }
165 let isolated = CloudSyncService(defaults: other)
166 Self.retained.append(isolated)
167
168 XCTAssertTrue(isolated.loadTombstones().isEmpty)
169 }
170
171 // MARK: Reset
172
173 func testResettingTrackedDomainsRecordsOneTombstoneEach() {
174 let service = makeService()
175
176 service.recordTrackedDomainReset([
177 trackedDomain("a.example"),
178 trackedDomain("b.example")
179 ])
180
181 XCTAssertEqual(
182 Set(service.loadTombstones().map(\.identifier)),
183 ["a.example", "b.example"]
184 )
185 }
186}
DomainDigTests/LocalAPIRoutingTests.swift +3 −1
@@ -5,7 +5,9 @@ import XCTest
55/// pins the JSON shape of a response, not which request produces it. Matching
66/// and authorisation are both pure, and `handle` answers 401 and 404 before it
77/// reaches the store or the network, so all of that is reachable here. The
8/// success paths are not — they read the real store and run live lookups.
8/// success paths moved to `LocalAPISuccessTests` once the handler took an
9/// injected store; `/inspect` is still uncovered, because it runs a live
10/// lookup.
911final class LocalAPIRoutingTests: XCTestCase {
1012
1113 // MARK: Every documented route
DomainDigTests/LocalAPISuccessTests.swift added +204
@@ -0,0 +1,204 @@
1import XCTest
2@testable import DomainDig
3
4/// C7's second remaining gap: `LocalAPIRoutingTests` covers which request maps
5/// to which route and the 401/404 envelopes, which `handle` answers before it
6/// reaches the store — but nothing covered what the success paths actually
7/// return, because they read the real store.
8///
9/// `LocalAPIRequestHandler` takes a `defaults:` and a `historyLocation:` now,
10/// so they can be answered from a scratch store and asserted. `/inspect` still
11/// is not here: it runs a live lookup, which is a network dependency rather
12/// than a store one.
13@MainActor
14final class LocalAPISuccessTests: XCTestCase {
15
16 private let token = "test-token"
17 private var suiteName = ""
18 private var scratch = UserDefaults.standard
19 private var historyLocation = HistoryFileStore.Location.default
20
21 override func setUpWithError() throws {
22 try super.setUpWithError()
23 suiteName = "net.cleberg.DomainDig.tests.localapi.\(UUID().uuidString)"
24 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
25 historyLocation = HistoryFileStore.Location(
26 root: URL(fileURLWithPath: NSTemporaryDirectory())
27 .appendingPathComponent("DomainDigLocalAPITest-\(UUID().uuidString)", isDirectory: true)
28 )
29 }
30
31 override func tearDown() {
32 UserDefaults.standard.removePersistentDomain(forName: suiteName)
33 HistoryFileStore.removeAll(at: historyLocation)
34 super.tearDown()
35 }
36
37 private var handler: LocalAPIRequestHandler {
38 LocalAPIRequestHandler(defaults: scratch, historyLocation: historyLocation)
39 }
40
41 private func get(_ path: String) async -> LocalAPIHTTPResponse {
42 await handler.handle(
43 request: LocalAPIHTTPRequest(
44 method: "GET",
45 path: path,
46 queryItems: [],
47 headers: ["x-api-token": token],
48 body: Data()
49 ),
50 expectedToken: token
51 )
52 }
53
54 /// The envelope's `data`, as loosely typed JSON — these assert on the
55 /// values the store produced, and `LocalAPIContractTests` already pins the
56 /// shape.
57 private func data(from response: LocalAPIHTTPResponse) throws -> [String: Any] {
58 XCTAssertEqual(response.statusCode, 200)
59 let json = try XCTUnwrap(
60 try JSONSerialization.jsonObject(with: response.body) as? [String: Any]
61 )
62 XCTAssertEqual(json["success"] as? Bool, true)
63 return try XCTUnwrap(json["data"] as? [String: Any])
64 }
65
66 private func seedTrackedDomains(_ domains: [String]) {
67 DomainDataPortabilityService.saveTrackedDomains(
68 domains.map { TrackedDomain(domain: $0, createdAt: Date(), updatedAt: Date()) },
69 defaults: scratch
70 )
71 }
72
73 // MARK: /domains
74
75 func testDomainsReturnsTheTrackedDomainsFromTheInjectedStore() async throws {
76 seedTrackedDomains(["b.example", "a.example"])
77
78 let payload = try data(from: await get("/domains"))
79 let domains = try XCTUnwrap(payload["domains"] as? [[String: Any]])
80
81 XCTAssertEqual(Set(domains.compactMap { $0["domain"] as? String }), ["a.example", "b.example"])
82 }
83
84 func testDomainsIsEmptyOnAFreshStore() async throws {
85 let payload = try data(from: await get("/domains"))
86
87 XCTAssertEqual((payload["domains"] as? [[String: Any]])?.count, 0)
88 }
89
90 // MARK: /portfolio
91
92 func testPortfolioCountsTheTrackedDomains() async throws {
93 seedTrackedDomains(["a.example", "b.example", "c.example"])
94
95 let payload = try data(from: await get("/portfolio"))
96 let summary = try XCTUnwrap(payload["summary"] as? [String: Any])
97
98 XCTAssertEqual(summary["totalDomains"] as? Int, 3)
99 }
100
101 func testPortfolioIsZeroedOnAFreshStore() async throws {
102 let payload = try data(from: await get("/portfolio"))
103 let summary = try XCTUnwrap(payload["summary"] as? [String: Any])
104
105 XCTAssertEqual(summary["totalDomains"] as? Int, 0)
106 XCTAssertEqual(summary["healthyCount"] as? Int, 0)
107 }
108
109 // MARK: /domains/{domain}
110
111 func testDomainDetailsAnswersForATrackedDomain() async throws {
112 seedTrackedDomains(["example.com"])
113
114 let payload = try data(from: await get("/domains/example.com"))
115
116 XCTAssertEqual(payload["domain"] as? String, "example.com")
117 XCTAssertNotNil(payload["trackedDomain"])
118 }
119
120 /// A domain the store does not hold is a 404 with the documented code,
121 /// rather than an empty 200.
122 func testDomainDetailsIsNotFoundForAnUntrackedDomain() async throws {
123 let response = await get("/domains/unknown.example")
124
125 XCTAssertEqual(response.statusCode, 404)
126 let json = try XCTUnwrap(try JSONSerialization.jsonObject(with: response.body) as? [String: Any])
127 let error = try XCTUnwrap(json["error"] as? [String: Any])
128 XCTAssertEqual(error["code"] as? String, "domain_not_found")
129 }
130
131 /// The path is matched case-insensitively, because that is how the store
132 /// matches it everywhere else.
133 func testDomainDetailsMatchesCaseInsensitively() async throws {
134 seedTrackedDomains(["example.com"])
135
136 let payload = try data(from: await get("/domains/EXAMPLE.COM"))
137
138 XCTAssertEqual(payload["domain"] as? String, "example.com")
139 }
140
141 // MARK: /domains/{domain}/history
142
143 func testDomainHistoryIsEmptyWithoutSnapshots() async throws {
144 seedTrackedDomains(["example.com"])
145
146 let payload = try data(from: await get("/domains/example.com/history"))
147
148 XCTAssertEqual(payload["domain"] as? String, "example.com")
149 XCTAssertEqual((payload["history"] as? [[String: Any]])?.count, 0)
150 }
151
152 // MARK: /events and /monitoring
153
154 func testEventsAnswersOnAFreshStore() async throws {
155 let payload = try data(from: await get("/events"))
156
157 XCTAssertEqual((payload["events"] as? [[String: Any]])?.count, 0)
158 }
159
160 func testMonitoringReportsTheStoredSettings() async throws {
161 seedTrackedDomains(["example.com"])
162
163 let payload = try data(from: await get("/monitoring"))
164
165 XCTAssertNotNil(payload["isEnabled"])
166 XCTAssertNotNil(payload["scope"])
167 XCTAssertNotNil(payload["monitoredDomains"])
168 }
169
170 // MARK: The injected store
171
172 /// The point of the seam: answering these touches the scratch store and
173 /// leaves the simulator's shared defaults alone.
174 func testTheSuccessPathsDoNotReadTheStandardStore() async throws {
175 let key = "trackedDomains"
176 let before = UserDefaults.standard.data(forKey: key)
177 seedTrackedDomains(["scratch-only.example"])
178
179 let payload = try data(from: await get("/domains"))
180 let domains = try XCTUnwrap(payload["domains"] as? [[String: Any]])
181
182 XCTAssertEqual(domains.compactMap { $0["domain"] as? String }, ["scratch-only.example"])
183 XCTAssertEqual(UserDefaults.standard.data(forKey: key), before, "standard store untouched")
184 }
185
186 /// Auth still runs ahead of the store, so a seeded store is no way around
187 /// a missing token.
188 func testAMissingTokenIsStillRejectedWithASeededStore() async throws {
189 seedTrackedDomains(["example.com"])
190
191 let response = await handler.handle(
192 request: LocalAPIHTTPRequest(
193 method: "GET",
194 path: "/domains",
195 queryItems: [],
196 headers: [:],
197 body: Data()
198 ),
199 expectedToken: token
200 )
201
202 XCTAssertEqual(response.statusCode, 401)
203 }
204}