DomainDigTests/LocalAPISuccessTests.swift
204 lines · 7622 bytes
18 symbols in this file
LocalAPISuccessTestssetUpWithErrortearDowngetdataseedTrackedDomainstestDomainsReturnsTheTrackedDomainsFromTheInjectedStoretestDomainsIsEmptyOnAFreshStoretestPortfolioCountsTheTrackedDomainstestPortfolioIsZeroedOnAFreshStoretestDomainDetailsAnswersForATrackedDomaintestDomainDetailsIsNotFoundForAnUntrackedDomaintestDomainDetailsMatchesCaseInsensitivelytestDomainHistoryIsEmptyWithoutSnapshotstestEventsAnswersOnAFreshStoretestMonitoringReportsTheStoredSettingstestTheSuccessPathsDoNotReadTheStandardStoretestAMissingTokenIsStillRejectedWithASeededStore
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}