Commit 00258de594
Unsigned
Layout: unified · split
DomainDig/CloudSyncService.swift +8 −2
| @@ -165,7 +165,12 @@ final class CloudSyncService { | |||
| 165 | static let changeTokenPrefix = "cloudSync.changeToken." | 165 | static let changeTokenPrefix = "cloudSync.changeToken." |
| 166 | } | 166 | } |
| 167 | 167 | ||
| 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) { | ||
| 169 | self.defaults = defaults | 174 | self.defaults = defaults |
| 170 | self.container = nil | 175 | self.container = nil |
| 171 | self.privateDatabase = nil | 176 | self.privateDatabase = nil |
| @@ -835,7 +840,8 @@ final class CloudSyncService { | |||
| 835 | saveTombstones(tombstones) | 840 | saveTombstones(tombstones) |
| 836 | } | 841 | } |
| 837 | 842 | ||
| 838 | private func loadTombstones() -> [SyncTombstone] { | 843 | /// Internal so a test can read back what a deletion recorded. |
| 844 | func loadTombstones() -> [SyncTombstone] { | ||
| 839 | guard let data = defaults.data(forKey: StorageKey.tombstones), | 845 | guard let data = defaults.data(forKey: StorageKey.tombstones), |
| 840 | let tombstones = try? decoder.decode([SyncTombstone].self, from: data) else { | 846 | let tombstones = try? decoder.decode([SyncTombstone].self, from: data) else { |
| 841 | return [] | 847 | return [] |
DomainDig/LocalAPIService.swift +26 −13
| @@ -521,6 +521,19 @@ enum LocalAPIRoute: Equatable { | |||
| 521 | } | 521 | } |
| 522 | 522 | ||
| 523 | struct LocalAPIRequestHandler { | 523 | struct 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 | |||
| 524 | private let encoder = LocalAPIContract.makeEncoder() | 537 | private let encoder = LocalAPIContract.makeEncoder() |
| 525 | 538 | ||
| 526 | private let decoder: JSONDecoder = { | 539 | private let decoder: JSONDecoder = { |
| @@ -545,7 +558,7 @@ struct LocalAPIRequestHandler { | |||
| 545 | case .portfolio: | 558 | case .portfolio: |
| 546 | return successResponse(PortfolioPayload(summary: buildPortfolioSummary())) | 559 | return successResponse(PortfolioPayload(summary: buildPortfolioSummary())) |
| 547 | case .domains: | 560 | case .domains: |
| 548 | return successResponse(DomainListPayload(domains: DomainDataPortabilityService.loadTrackedDomains())) | 561 | return successResponse(DomainListPayload(domains: DomainDataPortabilityService.loadTrackedDomains(defaults: defaults))) |
| 549 | case let .domainDetails(domain): | 562 | case let .domainDetails(domain): |
| 550 | return domainDetailsResponse(for: domain) | 563 | return domainDetailsResponse(for: domain) |
| 551 | case let .domainHistory(domain): | 564 | case let .domainHistory(domain): |
| @@ -595,7 +608,7 @@ struct LocalAPIRequestHandler { | |||
| 595 | 608 | ||
| 596 | private func domainDetailsResponse(for domain: String) -> LocalAPIHTTPResponse { | 609 | private func domainDetailsResponse(for domain: String) -> LocalAPIHTTPResponse { |
| 597 | let normalized = normalizedDomain(domain) | 610 | let normalized = normalizedDomain(domain) |
| 598 | let trackedDomain = DomainDataPortabilityService.loadTrackedDomains().first { | 611 | let trackedDomain = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults).first { |
| 599 | $0.domain.caseInsensitiveCompare(normalized) == .orderedSame | 612 | $0.domain.caseInsensitiveCompare(normalized) == .orderedSame |
| 600 | } | 613 | } |
| 601 | let history = historyEntries(for: normalized) | 614 | let history = historyEntries(for: normalized) |
| @@ -652,20 +665,20 @@ struct LocalAPIRequestHandler { | |||
| 652 | return .error(statusCode: 400, code: "invalid_domain", message: "A valid domain is required.") | 665 | return .error(statusCode: 400, code: "invalid_domain", message: "A valid domain is required.") |
| 653 | } | 666 | } |
| 654 | 667 | ||
| 655 | var trackedDomains = DomainDataPortabilityService.loadTrackedDomains() | 668 | var trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) |
| 656 | guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame }) else { | 669 | guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame }) else { |
| 657 | return .error(statusCode: 404, code: "domain_not_found", message: "Tracked domain \(normalized) was not found.") | 670 | return .error(statusCode: 404, code: "domain_not_found", message: "Tracked domain \(normalized) was not found.") |
| 658 | } | 671 | } |
| 659 | 672 | ||
| 660 | trackedDomains[index].monitoringEnabled = enabled | 673 | trackedDomains[index].monitoringEnabled = enabled |
| 661 | trackedDomains[index].updatedAt = Date() | 674 | trackedDomains[index].updatedAt = Date() |
| 662 | DomainDataPortabilityService.saveTrackedDomains(trackedDomains) | 675 | DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults) |
| 663 | 676 | ||
| 664 | let sanitizedSettings = MonitoringStorage.sanitizeSettings( | 677 | let sanitizedSettings = MonitoringStorage.sanitizeSettings( |
| 665 | MonitoringStorage.loadSettings(), | 678 | MonitoringStorage.loadSettings(defaults: defaults), |
| 666 | trackedDomains: trackedDomains | 679 | trackedDomains: trackedDomains |
| 667 | ) | 680 | ) |
| 668 | MonitoringStorage.saveSettings(sanitizedSettings) | 681 | MonitoringStorage.saveSettings(sanitizedSettings, defaults: defaults) |
| 669 | 682 | ||
| 670 | await MainActor.run { | 683 | await MainActor.run { |
| 671 | _ = DomainMonitoringScheduler.shared.syncSchedule() | 684 | _ = DomainMonitoringScheduler.shared.syncSchedule() |
| @@ -680,8 +693,8 @@ struct LocalAPIRequestHandler { | |||
| 680 | } | 693 | } |
| 681 | 694 | ||
| 682 | private func buildPortfolioSummary() -> PortfolioSummary { | 695 | private func buildPortfolioSummary() -> PortfolioSummary { |
| 683 | let trackedDomains = DomainDataPortabilityService.loadTrackedDomains() | 696 | let trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) |
| 684 | let history = DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default) | 697 | let history = DomainDataPortabilityService.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation) |
| 685 | 698 | ||
| 686 | var healthyCount = 0 | 699 | var healthyCount = 0 |
| 687 | var warningCount = 0 | 700 | var warningCount = 0 |
| @@ -724,8 +737,8 @@ struct LocalAPIRequestHandler { | |||
| 724 | } | 737 | } |
| 725 | 738 | ||
| 726 | private func monitoringPayload() -> MonitoringPayload { | 739 | private func monitoringPayload() -> MonitoringPayload { |
| 727 | let trackedDomains = DomainDataPortabilityService.loadTrackedDomains() | 740 | let trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) |
| 728 | let settings = MonitoringStorage.sanitizeSettings(MonitoringStorage.loadSettings(), trackedDomains: trackedDomains) | 741 | let settings = MonitoringStorage.sanitizeSettings(MonitoringStorage.loadSettings(defaults: defaults), trackedDomains: trackedDomains) |
| 729 | 742 | ||
| 730 | return MonitoringPayload( | 743 | return MonitoringPayload( |
| 731 | isEnabled: settings.isEnabled, | 744 | isEnabled: settings.isEnabled, |
| @@ -744,7 +757,7 @@ struct LocalAPIRequestHandler { | |||
| 744 | } | 757 | } |
| 745 | 758 | ||
| 746 | private func recentEvents() -> [RecentEventPayload] { | 759 | private func recentEvents() -> [RecentEventPayload] { |
| 747 | MonitoringStorage.loadLogs() | 760 | MonitoringStorage.loadLogs(defaults: defaults) |
| 748 | .prefix(25) | 761 | .prefix(25) |
| 749 | .flatMap { log in | 762 | .flatMap { log in |
| 750 | log.checkedDomains.map { result in | 763 | log.checkedDomains.map { result in |
| @@ -761,13 +774,13 @@ struct LocalAPIRequestHandler { | |||
| 761 | 774 | ||
| 762 | private func historyEntries(for domain: String) -> [HistoryEntry] { | 775 | private func historyEntries(for domain: String) -> [HistoryEntry] { |
| 763 | let normalized = normalizedDomain(domain) | 776 | let normalized = normalizedDomain(domain) |
| 764 | return DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default).filter { | 777 | return DomainDataPortabilityService.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation).filter { |
| 765 | $0.domain.caseInsensitiveCompare(normalized) == .orderedSame | 778 | $0.domain.caseInsensitiveCompare(normalized) == .orderedSame |
| 766 | } | 779 | } |
| 767 | } | 780 | } |
| 768 | 781 | ||
| 769 | private func latestHistoryEntry(for domain: String, history: [HistoryEntry]? = nil) -> HistoryEntry? { | 782 | 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) |
| 771 | let normalized = normalizedDomain(domain) | 784 | let normalized = normalizedDomain(domain) |
| 772 | return entries.first { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame } | 785 | return entries.first { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame } |
| 773 | } | 786 | } |
DomainDigTests/CloudSyncStoreTests.swift added +186
| @@ -0,0 +1,186 @@ | |||
| 1 | import 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 | ||
| 14 | final 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 | |||
| 5 | /// pins the JSON shape of a response, not which request produces it. Matching | 5 | /// pins the JSON shape of a response, not which request produces it. Matching |
| 6 | /// and authorisation are both pure, and `handle` answers 401 and 404 before it | 6 | /// and authorisation are both pure, and `handle` answers 401 and 404 before it |
| 7 | /// reaches the store or the network, so all of that is reachable here. The | 7 | /// 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. | ||
| 9 | final class LocalAPIRoutingTests: XCTestCase { | 11 | final class LocalAPIRoutingTests: XCTestCase { |
| 10 | 12 | ||
| 11 | // MARK: Every documented route | 13 | // MARK: Every documented route |
DomainDigTests/LocalAPISuccessTests.swift added +204
| @@ -0,0 +1,204 @@ | |||
| 1 | import 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 | ||
| 14 | final 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 | } | ||