DomainDigTests/PortfolioDashboardTests.swift

2ad5d8160338d289a65d6a4d1c214a02bf916f1f
domain-dig/DomainDigTests/PortfolioDashboardTests.swift history · blame · raw

262 lines · 10442 bytes

16 symbols in this file
  1import XCTest
  2@testable import DomainDig
  3
  4/// Filtering the dashboard used to be five computed properties on the view
  5/// model, each re-reading `portfolioDashboardData` and re-deriving the visible
  6/// set — so the whole dashboard was rebuilt more than twenty times per render
  7/// (A4), and none of it was covered.
  8///
  9/// It is a function of the data now, which makes it testable, and these are
 10/// what that bought.
 11final class PortfolioDashboardTests: XCTestCase {
 12
 13    private func state(
 14        domain: String,
 15        apex: String? = nil,
 16        health: DomainHealth = .healthy,
 17        lastChangeDate: Date? = nil,
 18        certificateExpiry: CertificateWarningLevel = .none,
 19        certificateDaysRemaining: Int? = nil,
 20        isUnreachable: Bool = false
 21    ) -> PortfolioDomainStatus {
 22        PortfolioDomainStatus(
 23            trackedDomain: TrackedDomain(domain: domain, createdAt: Date(), updatedAt: Date()),
 24            latestEntry: nil,
 25            report: SnapshotFixture.report(domain: domain),
 26            apexDomain: apex ?? domain,
 27            health: health,
 28            lastChangeDate: lastChangeDate,
 29            lastMonitoringFailure: nil,
 30            instabilityScore: 0,
 31            certificateExpiryState: certificateExpiry,
 32            certificateDaysRemaining: certificateDaysRemaining,
 33            isUnreachable: isUnreachable,
 34            recentDNSChange: false,
 35            recentCriticalChange: false,
 36            recentFailureCount: 0
 37        )
 38    }
 39
 40    private func dashboard(_ states: [PortfolioDomainStatus]) -> PortfolioDashboardData {
 41        PortfolioDashboardData(
 42            snapshot: PortfolioSnapshot(
 43                totalDomains: states.count,
 44                healthyCount: states.filter { $0.health == .healthy }.count,
 45                warningCount: states.filter { $0.health == .warning }.count,
 46                criticalCount: states.filter { $0.health == .critical }.count,
 47                changedLast24h: 0,
 48                expiringSoonCount: states.filter { $0.certificateExpiryState != .none }.count,
 49                unreachableCount: states.filter(\.isUnreachable).count
 50            ),
 51            domainStates: states,
 52            recentActivity: states.map {
 53                PortfolioActivityItem(
 54                    id: "activity-\($0.trackedDomain.domain)",
 55                    trackedDomainID: $0.trackedDomain.id,
 56                    domain: $0.trackedDomain.domain,
 57                    message: "changed",
 58                    timestamp: Date(),
 59                    health: $0.health,
 60                    systemImage: "circle"
 61                )
 62            },
 63            attentionRequired: states.map {
 64                PortfolioAttentionItem(
 65                    id: "attention-\($0.trackedDomain.domain)",
 66                    trackedDomainID: $0.trackedDomain.id,
 67                    domain: $0.trackedDomain.domain,
 68                    reason: "needs attention",
 69                    timestamp: Date(),
 70                    health: $0.health
 71                )
 72            },
 73            expiringSoon: states.filter { $0.certificateExpiryState != .none },
 74            groups: PortfolioDashboardData.groups(from: states)
 75        )
 76    }
 77
 78    // MARK: Filters
 79
 80    func testTheAllFilterKeepsEveryDomain() {
 81        let data = dashboard([
 82            state(domain: "a.example", health: .healthy),
 83            state(domain: "b.example", health: .critical)
 84        ])
 85
 86        let visible = data.filtered(by: .all, searchText: "")
 87
 88        XCTAssertEqual(visible.domainStates.map(\.trackedDomain.domain), ["a.example", "b.example"])
 89    }
 90
 91    func testEachHealthFilterKeepsOnlyThatHealth() {
 92        let data = dashboard([
 93            state(domain: "healthy.example", health: .healthy),
 94            state(domain: "warning.example", health: .warning),
 95            state(domain: "critical.example", health: .critical)
 96        ])
 97
 98        XCTAssertEqual(
 99            data.filtered(by: .healthy, searchText: "").domainStates.map(\.trackedDomain.domain),
100            ["healthy.example"]
101        )
102        XCTAssertEqual(
103            data.filtered(by: .warning, searchText: "").domainStates.map(\.trackedDomain.domain),
104            ["warning.example"]
105        )
106        XCTAssertEqual(
107            data.filtered(by: .critical, searchText: "").domainStates.map(\.trackedDomain.domain),
108            ["critical.example"]
109        )
110    }
111
112    func testTheUnreachableFilterKeepsOnlyUnreachableDomains() {
113        let data = dashboard([
114            state(domain: "up.example"),
115            state(domain: "down.example", isUnreachable: true)
116        ])
117
118        XCTAssertEqual(
119            data.filtered(by: .unreachable, searchText: "").domainStates.map(\.trackedDomain.domain),
120            ["down.example"]
121        )
122    }
123
124    func testTheExpiringFilterKeepsAnyNonNoneWarningLevel() {
125        let data = dashboard([
126            state(domain: "fine.example", certificateExpiry: .none),
127            state(domain: "soon.example", certificateExpiry: .warning),
128            state(domain: "urgent.example", certificateExpiry: .critical)
129        ])
130
131        XCTAssertEqual(
132            Set(data.filtered(by: .expiring, searchText: "").domainStates.map(\.trackedDomain.domain)),
133            ["soon.example", "urgent.example"]
134        )
135    }
136
137    /// The 24-hour window is relative to now, so a change from last week is not
138    /// "changed" and one from a minute ago is.
139    func testTheChangedFilterUsesATwentyFourHourWindow() {
140        let data = dashboard([
141            state(domain: "recent.example", lastChangeDate: Date().addingTimeInterval(-60)),
142            state(domain: "old.example", lastChangeDate: Date().addingTimeInterval(-8 * 24 * 60 * 60)),
143            state(domain: "never.example", lastChangeDate: nil)
144        ])
145
146        XCTAssertEqual(
147            data.filtered(by: .changed, searchText: "").domainStates.map(\.trackedDomain.domain),
148            ["recent.example"]
149        )
150    }
151
152    // MARK: Search
153
154    func testSearchMatchesTheDomainAndTheApexCaseInsensitively() {
155        let data = dashboard([
156            state(domain: "shop.example.com", apex: "example.com"),
157            state(domain: "other.test", apex: "other.test")
158        ])
159
160        XCTAssertEqual(
161            data.filtered(by: .all, searchText: "SHOP").domainStates.map(\.trackedDomain.domain),
162            ["shop.example.com"]
163        )
164        XCTAssertEqual(
165            data.filtered(by: .all, searchText: "example.com").domainStates.map(\.trackedDomain.domain),
166            ["shop.example.com"]
167        )
168    }
169
170    func testSearchIgnoresSurroundingWhitespace() {
171        let data = dashboard([state(domain: "a.example"), state(domain: "b.example")])
172
173        XCTAssertEqual(
174            data.filtered(by: .all, searchText: "   ").domainStates.count, 2,
175            "a whitespace-only query should not filter anything out"
176        )
177        XCTAssertEqual(
178            data.filtered(by: .all, searchText: "  a.  ").domainStates.map(\.trackedDomain.domain),
179            ["a.example"],
180            "the query is trimmed at the ends, so this matches as 'a.'"
181        )
182    }
183
184    func testTheFilterAndTheSearchBothApply() {
185        let data = dashboard([
186            state(domain: "bad.example", health: .critical),
187            state(domain: "bad.other", health: .healthy),
188            state(domain: "good.example", health: .critical)
189        ])
190
191        XCTAssertEqual(
192            data.filtered(by: .critical, searchText: "bad").domainStates.map(\.trackedDomain.domain),
193            ["bad.example"]
194        )
195    }
196
197    // MARK: The dependent lists follow the visible set
198
199    /// Each list used to be filtered by its own computed property against a
200    /// separately rebuilt dashboard. They have to agree.
201    func testEveryListIsNarrowedToTheVisibleDomains() {
202        let data = dashboard([
203            state(domain: "keep.example", health: .critical, certificateExpiry: .warning),
204            state(domain: "drop.example", health: .healthy, certificateExpiry: .warning)
205        ])
206
207        let visible = data.filtered(by: .critical, searchText: "")
208
209        XCTAssertEqual(visible.domainStates.map(\.trackedDomain.domain), ["keep.example"])
210        XCTAssertEqual(visible.recentActivity.map(\.domain), ["keep.example"])
211        XCTAssertEqual(visible.attentionRequired.map(\.domain), ["keep.example"])
212        XCTAssertEqual(visible.expiringSoon.map(\.trackedDomain.domain), ["keep.example"])
213        XCTAssertEqual(visible.groups.flatMap { $0.domains.map(\.trackedDomain.domain) }, ["keep.example"])
214    }
215
216    /// The snapshot counts describe the whole portfolio, not the filtered view —
217    /// the summary cards are what the filter is selected *from*, so filtering
218    /// must not change them.
219    func testFilteringDoesNotChangeTheSummaryCounts() {
220        let data = dashboard([
221            state(domain: "a.example", health: .healthy),
222            state(domain: "b.example", health: .critical)
223        ])
224
225        let visible = data.filtered(by: .critical, searchText: "")
226
227        XCTAssertEqual(visible.snapshot.totalDomains, 2)
228        XCTAssertEqual(visible.snapshot.healthyCount, 1)
229        XCTAssertEqual(visible.snapshot.criticalCount, 1)
230    }
231
232    // MARK: Grouping
233
234    func testGroupsPutTheWorstHealthFirst() {
235        let groups = PortfolioDashboardData.groups(from: [
236            state(domain: "a.calm", apex: "calm", health: .healthy),
237            state(domain: "b.bad", apex: "bad", health: .critical),
238            state(domain: "c.mid", apex: "mid", health: .warning)
239        ])
240
241        XCTAssertEqual(groups.map(\.apexDomain), ["bad", "mid", "calm"])
242    }
243
244    func testDomainsWithinAGroupAreWorstFirstThenAlphabetical() {
245        let groups = PortfolioDashboardData.groups(from: [
246            state(domain: "z.example", apex: "example", health: .healthy),
247            state(domain: "a.example", apex: "example", health: .healthy),
248            state(domain: "m.example", apex: "example", health: .critical)
249        ])
250
251        XCTAssertEqual(groups.count, 1)
252        XCTAssertEqual(
253            groups[0].domains.map(\.trackedDomain.domain),
254            ["m.example", "a.example", "z.example"]
255        )
256    }
257
258    func testHealthSeverityRankOrdersWorstHighest() {
259        XCTAssertLessThan(DomainHealth.healthy.severityRank, DomainHealth.warning.severityRank)
260        XCTAssertLessThan(DomainHealth.warning.severityRank, DomainHealth.critical.severityRank)
261    }
262}