DomainDigTests/SectionStateTests.swift
281 lines · 11676 bytes
1import XCTest
2@testable import DomainDig
3
4/// What each result section ends up showing after an inspection lands.
5///
6/// `applySnapshot` is the one place section state is written, and until now
7/// nothing covered it — which is why A2's collapse of the 20 `*Loading` flags
8/// and 19 `*Error` strings into `SectionState` could not be attempted safely.
9/// These assert on the section slices the views actually consume rather than
10/// on the raw properties behind them, so they survive that collapse and are
11/// the thing it must not change.
12@MainActor
13final class SectionStateTests: XCTestCase {
14
15 private var suiteName = ""
16 private var scratch = UserDefaults.standard
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("DomainDigSectionTest-\(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 runner on iOS 18.6
36 /// (E1), and `Scripts/test.sh` runs that tier.
37 private static var retained: [DomainViewModel] = []
38
39 private func makeViewModel() -> DomainViewModel {
40 let viewModel = DomainViewModel(defaults: scratch, historyLocation: historyLocation)
41 Self.retained.append(viewModel)
42 return viewModel
43 }
44
45 // MARK: Loading
46
47 /// Starting a lookup puts every section in flight; applying a snapshot
48 /// takes them all out of it. Nothing may be left loading, or the section
49 /// spins forever.
50 // MARK: Provenance (A12)
51
52 /// Provenance used to be recovered from the saved history entry, so it was
53 /// empty until the snapshot had been written. It now comes from the
54 /// snapshot itself, which is visible here because nothing is saved.
55 func testProvenanceIsAvailableBeforeTheSnapshotIsSaved() {
56 let viewModel = makeViewModel()
57 let provenance = SnapshotFixture.provenance(source: "DNS-over-HTTPS query", provider: "Selected DoH resolver")
58
59 viewModel.applySnapshot(
60 SnapshotFixture.snapshot(provenanceBySection: [.dns: provenance])
61 )
62
63 XCTAssertNil(viewModel.currentHistoryEntryID, "nothing should have been saved")
64 XCTAssertEqual(viewModel.currentSnapshot.provenanceBySection[.dns], provenance)
65 }
66
67 /// The case the finding called out: a lookup that ends with a status
68 /// message returns before saving, so this was the state in which every
69 /// section showed no source at all.
70 func testProvenanceSurvivesASnapshotThatWouldNotBeSaved() {
71 let viewModel = makeViewModel()
72 let provenance = SnapshotFixture.provenance(source: "RDAP domain lookup", provider: "rdap.org")
73
74 viewModel.applySnapshot(
75 SnapshotFixture.snapshot(provenanceBySection: [.ownership: provenance])
76 )
77
78 XCTAssertEqual(viewModel.currentSnapshot.provenanceBySection[.ownership], provenance)
79 XCTAssertEqual(viewModel.currentSnapshot.provenanceBySection.count, 1)
80 }
81
82 /// Reset drops it, so a cleared screen does not keep claiming a source.
83 func testResetClearsTheInspectionMetadata() {
84 let viewModel = makeViewModel()
85 viewModel.applySnapshot(
86 SnapshotFixture.snapshot(provenanceBySection: [.dns: SnapshotFixture.provenance()])
87 )
88 XCTAssertFalse(viewModel.currentSnapshot.provenanceBySection.isEmpty)
89
90 viewModel.reset()
91
92 XCTAssertTrue(viewModel.currentSnapshot.provenanceBySection.isEmpty)
93 }
94
95 func testApplyingASnapshotSettlesEverySection() {
96 let viewModel = makeViewModel()
97 _ = viewModel.beginLookup(for: "example.com")
98
99 XCTAssertFalse(viewModel.resultsLoaded, "sections should be in flight after a lookup starts")
100
101 viewModel.applySnapshot(SnapshotFixture.snapshot())
102
103 XCTAssertTrue(viewModel.resultsLoaded, "a section was left loading")
104 XCTAssertFalse(viewModel.webSectionData.tls.isLoading)
105 XCTAssertFalse(viewModel.webSectionData.http.isLoading)
106 XCTAssertFalse(viewModel.webSectionData.redirect.isLoading)
107 XCTAssertFalse(viewModel.networkSectionData.reachability.isLoading)
108 XCTAssertFalse(viewModel.networkSectionData.location.isLoading)
109 XCTAssertFalse(viewModel.networkSectionData.portScan.isLoading)
110 XCTAssertFalse(viewModel.networkSectionData.customPortScan.isLoading)
111 }
112
113 /// `resultsLoaded` gates the whole results area, so it must not read true
114 /// before a lookup has ever run.
115 func testResultsAreNotLoadedBeforeAnyLookup() {
116 XCTAssertFalse(makeViewModel().resultsLoaded)
117 }
118
119 // MARK: Values
120
121 func testASuccessfulSnapshotPopulatesTheWebSection() throws {
122 let viewModel = makeViewModel()
123 let certificate = SnapshotFixture.certificate(commonName: "example.com", issuer: "Test CA")
124
125 viewModel.applySnapshot(
126 SnapshotFixture.snapshot(
127 sslInfo: certificate,
128 httpHeaders: [HTTPHeader(name: "server", value: "test")]
129 )
130 )
131
132 let web = viewModel.webSectionData
133 XCTAssertNil(web.tls.error)
134 XCTAssertEqual(web.sslInfo?.commonName, "example.com")
135 XCTAssertEqual(web.sslInfo?.issuer, "Test CA")
136 XCTAssertNil(web.http.error)
137 XCTAssertEqual(web.headers.map(\.name), ["server"])
138 }
139
140 func testASuccessfulSnapshotPopulatesTheNetworkSection() {
141 let viewModel = makeViewModel()
142
143 viewModel.applySnapshot(SnapshotFixture.snapshot(dnsSections: [
144 SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1"])
145 ]))
146
147 let network = viewModel.networkSectionData
148 XCTAssertNil(network.reachability.error)
149 XCTAssertNil(network.location.error)
150 XCTAssertNil(network.portScan.error)
151 }
152
153 func testTheDNSSectionTakesItsRecordsFromTheSnapshot() {
154 let viewModel = makeViewModel()
155
156 viewModel.applySnapshot(SnapshotFixture.snapshot(dnsSections: [
157 SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1", "203.0.113.2"]),
158 SnapshotFixture.dnsSection(type: .MX, values: ["10 mail.example.com"])
159 ]))
160
161 XCTAssertEqual(viewModel.dnsSections.map(\.recordType), [.A, .MX])
162 XCTAssertEqual(
163 viewModel.dnsSections.flatMap { $0.records.map(\.value) },
164 ["203.0.113.1", "203.0.113.2", "10 mail.example.com"]
165 )
166 XCTAssertNil(viewModel.dnsError)
167 }
168
169 // MARK: Failures
170
171 func testAFailedSectionCarriesItsMessage() {
172 let viewModel = makeViewModel()
173
174 viewModel.applySnapshot(
175 SnapshotFixture.snapshot(
176 failures: .init(sslError: "handshake failed", httpHeadersError: "timed out")
177 )
178 )
179
180 XCTAssertEqual(viewModel.webSectionData.tls.error, "handshake failed")
181 XCTAssertEqual(viewModel.webSectionData.http.error, "timed out")
182 }
183
184 /// One section failing must not mark the others failed. Partial snapshots
185 /// are the normal case, not the exception.
186 func testOneFailedSectionLeavesTheOthersAlone() {
187 let viewModel = makeViewModel()
188
189 viewModel.applySnapshot(SnapshotFixture.snapshot(failures: .init(sslError: "handshake failed")))
190
191 XCTAssertEqual(viewModel.webSectionData.tls.error, "handshake failed")
192 XCTAssertNil(viewModel.webSectionData.http.error)
193 XCTAssertNil(viewModel.webSectionData.redirect.error)
194 XCTAssertNil(viewModel.networkSectionData.reachability.error)
195 XCTAssertNil(viewModel.networkSectionData.location.error)
196 XCTAssertNil(viewModel.networkSectionData.portScan.error)
197 }
198
199 func testEachNetworkCardCarriesItsOwnFailure() {
200 let viewModel = makeViewModel()
201
202 viewModel.applySnapshot(
203 SnapshotFixture.snapshot(
204 failures: .init(
205 reachabilityError: "no route",
206 ipGeolocationError: "no geolocation",
207 portScanError: "scan refused"
208 )
209 )
210 )
211
212 let network = viewModel.networkSectionData
213 XCTAssertEqual(network.reachability.error, "no route")
214 XCTAssertEqual(network.location.error, "no geolocation")
215 XCTAssertEqual(network.portScan.error, "scan refused")
216 }
217
218 /// A snapshot can carry a value *and* an error for one section, and every
219 /// section view renders `loading → error → rows`: the error wins and the
220 /// value is not shown. Collapsing the triples must keep that order, and
221 /// must keep the value reachable where a card reads it alongside the error
222 /// — the TLS badge takes both.
223 func testAnErrorAndAValueTogetherKeepBothReachable() {
224 let viewModel = makeViewModel()
225
226 viewModel.applySnapshot(
227 SnapshotFixture.snapshot(
228 sslInfo: SnapshotFixture.certificate(commonName: "stale.example"),
229 failures: .init(sslError: "handshake failed")
230 )
231 )
232
233 let web = viewModel.webSectionData
234 XCTAssertEqual(web.tls.error, "handshake failed", "the error must still be what the card shows")
235 XCTAssertEqual(
236 web.sslInfo?.commonName, "stale.example",
237 "the TLS badge reads sslInfo alongside the error, so it must survive"
238 )
239 }
240
241 // MARK: Provenance
242
243 /// Provenance now comes from the snapshot that was just applied, which is
244 /// A12 closed. It used to be recovered from the saved history entry, so
245 /// between applying and saving — and on a lookup that ends with a status
246 /// message and is therefore never saved — the cards showed none at all.
247 ///
248 /// This asserts through the section slice the view consumes, which is what
249 /// the earlier version of this test pinned in the opposite direction.
250 func testTheAppliedSnapshotCarriesProvenanceToTheSection() {
251 let viewModel = makeViewModel()
252 let provenance = SnapshotFixture.provenance(source: "Direct TLS handshake", provider: "Target host")
253
254 viewModel.applySnapshot(
255 SnapshotFixture.snapshot(provenanceBySection: [.ssl: provenance])
256 )
257
258 XCTAssertEqual(viewModel.webSectionData.tls.provenance, provenance)
259 }
260
261 // MARK: A second lookup clears the first one's results
262
263 /// Starting a new lookup must not leave the previous domain's sections on
264 /// screen as though they belonged to the new one.
265 func testANewLookupClearsThePreviousSectionResults() {
266 let viewModel = makeViewModel()
267 viewModel.applySnapshot(
268 SnapshotFixture.snapshot(
269 domain: "first.example",
270 dnsSections: [SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1"])],
271 failures: .init(sslError: "handshake failed")
272 )
273 )
274 XCTAssertFalse(viewModel.dnsSections.isEmpty)
275
276 _ = viewModel.beginLookup(for: "second.example")
277
278 XCTAssertTrue(viewModel.dnsSections.isEmpty, "the previous domain's records survived a new lookup")
279 XCTAssertNil(viewModel.webSectionData.tls.error, "the previous domain's failure survived a new lookup")
280 }
281}