DomainDigTests/DomainNameTests.swift

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

263 lines · 10639 bytes

31 symbols in this file
  1import XCTest
  2@testable import DomainDig
  3
  4/// `run()` used to hand anything non-empty to 14 section services, which each
  5/// reported their own network error for input that was never a domain. These pin
  6/// the input-boundary validator that answers before the lookup starts.
  7final class DomainNameTests: XCTestCase {
  8
  9    func testAcceptsAPlainHost() {
 10        XCTAssertEqual(DomainName.validate("example.com"), .success("example.com"))
 11    }
 12
 13    func testLowercasesAndTrims() {
 14        XCTAssertEqual(DomainName.validate("  EXAMPLE.COM\n"), .success("example.com"))
 15    }
 16
 17    func testStripsSchemeAndPath() {
 18        XCTAssertEqual(DomainName.validate("https://example.com/path?q=1"), .success("example.com"))
 19    }
 20
 21    func testStripsAPort() {
 22        XCTAssertEqual(DomainName.validate("example.com:8443"), .success("example.com"))
 23    }
 24
 25    func testStripsUserInfo() {
 26        XCTAssertEqual(DomainName.validate("user:pass@example.com"), .success("example.com"))
 27    }
 28
 29    func testStripsAQueryWithNoPath() {
 30        XCTAssertEqual(DomainName.validate("example.com?q=1"), .success("example.com"))
 31    }
 32
 33    func testRejectsASingleLabel() {
 34        XCTAssertEqual(DomainName.validate("localhost"), .failure(.singleLabel))
 35    }
 36
 37    func testRejectsAnInteriorSpace() {
 38        XCTAssertEqual(DomainName.validate("exa mple.com"), .failure(.invalidCharacter(" ")))
 39    }
 40
 41    /// `DomainHostURL` decodes escapes, so it reads `https://ex%20ample.com` as
 42    /// host `ex ample.com` and forms a URL no section service can resolve.
 43    func testRejectsAPercentEscape() {
 44        XCTAssertEqual(DomainName.validate("https://ex%20ample.com"), .failure(.invalidCharacter("%")))
 45    }
 46
 47    func testRejectsAnEmptyLabel() {
 48        XCTAssertEqual(DomainName.validate("a..b.com"), .failure(.malformedLabel("")))
 49    }
 50
 51    /// `-x.com` forms a URL, so `DomainHostURL` is not a substitute for these
 52    /// label rules — the invariant only runs the other way.
 53    func testRejectsALeadingHyphenLabel() {
 54        XCTAssertEqual(DomainName.validate("-x.com"), .failure(.malformedLabel("-x")))
 55    }
 56
 57    func testRejectsALabelOver63Bytes() {
 58        let label = String(repeating: "a", count: 64)
 59        XCTAssertEqual(DomainName.validate("\(label).com"), .failure(.labelTooLong))
 60    }
 61
 62    func testRejectsAHostOver253Bytes() {
 63        let label = String(repeating: "a", count: 63)
 64        let host = Array(repeating: label, count: 4).joined(separator: ".")
 65        XCTAssertEqual(DomainName.validate(host), .failure(.tooLong))
 66    }
 67
 68    /// The limit applies to the IDNA-encoded label, so it turns on the encoded
 69    /// size rather than the typed one: these 40 distinct CJK characters encode
 70    /// to 83 bytes, while 40 repeats of one character encode to 46 and pass.
 71    func testMeasuresLengthOnPunycode() {
 72        let label = String((0..<40).compactMap { UnicodeScalar(UInt32(0x4E00 + $0 * 7)).map(Character.init) })
 73        XCTAssertEqual(DomainName.validate("\(label).com"), .failure(.labelTooLong))
 74        XCTAssertEqual(
 75            DomainName.validate("\(String(repeating: "域", count: 40)).com"),
 76            .success("\(String(repeating: "域", count: 40)).com")
 77        )
 78    }
 79
 80    /// C8: the probe used to look only at a label's first few characters, so
 81    /// an unencodable character sitting after them reported `.labelTooLong`
 82    /// instead of `.malformedLabel`.
 83    ///
 84    /// Calibrated on the character rather than hard-coded, because which
 85    /// scalars IDNA refuses is Foundation's business and moves between
 86    /// releases. If none of the candidates is refused, there is nothing to
 87    /// assert on this runtime.
 88    func testAnUnencodableCharacterIsMalformedWhereverItSitsInTheLabel() throws {
 89        let candidates = ["\u{200B}", "\u{FFFF}", "\u{2E2F}", "\u{1D173}"]
 90        guard let unencodable = candidates.first(where: { character in
 91            DomainName.validate("\(character).com") == .failure(.malformedLabel(character))
 92        }) else {
 93            throw XCTSkip("no IDNA-unencodable character among the candidates on this runtime")
 94        }
 95
 96        // Far enough in that the old eight-character prefix probe missed it,
 97        // and short enough that the label cannot be over the byte limit.
 98        let label = String(repeating: "a", count: 20) + unencodable
 99
100        XCTAssertEqual(
101            DomainName.validate("\(label).com"),
102            .failure(.malformedLabel(label)),
103            "an unencodable character past the probe length still makes the label malformed"
104        )
105    }
106
107    func testAcceptsAUnicodeHost() {
108        XCTAssertEqual(DomainName.validate("münchen.de"), .success("münchen.de"))
109    }
110
111    func testAcceptsATrailingDot() {
112        XCTAssertEqual(DomainName.validate("example.com."), .success("example.com"))
113    }
114
115    /// One-directional invariant: everything the validator accepts can be built
116    /// into a request URL.
117    func testAcceptedHostsFormARequestURL() {
118        for host in ["example.com", "münchen.de", "a.b.c.example.com"] {
119            guard case .success(let validated) = DomainName.validate(host) else {
120                return XCTFail("\(host) should validate")
121            }
122            XCTAssertNotNil(DomainHostURL.https(validated))
123        }
124    }
125}
126
127/// The validator sits at the input boundary only. `normalizedDomain` is the key
128/// that matches already-stored rows, so it stays lenient: routing it through the
129/// validator would turn tracking and workflow lookups into no-ops for any stored
130/// domain the rules reject.
131@MainActor
132final class DomainViewModelInputTests: XCTestCase {
133    /// Shared and never released: deallocating a `DomainViewModel` runs its
134    /// implicit main-actor-isolated deinit through the iOS 17 back-deployment
135    /// shim, which aborts in the simulator. The app holds one for its whole
136    /// lifetime, so nothing releases one there either.
137    /// On a scratch store: `trackDomain` persists, so on `.standard` this
138    /// test wrote "localhost" into the store of whichever app shares the
139    /// simulator.
140    private static let viewModel = DomainViewModel(
141        defaults: UserDefaults(suiteName: "net.cleberg.DomainDig.tests.input") ?? .standard
142    )
143
144    // MARK: Bulk input (U5)
145
146    /// The defect: ten domains with two typos ran eight and said nothing about
147    /// the other two.
148    func testBulkInputKeepsTheValidEntriesAndNamesTheRest() {
149        let parsed = Self.viewModel.parsedBulkInput(from: "example.com, not valid!!, apple.com")
150
151        XCTAssertEqual(parsed.domains, ["example.com", "apple.com"])
152        XCTAssertEqual(parsed.skipped, ["not", "valid!!"], "each rejected token is reported as typed")
153        XCTAssertEqual(
154            parsed.skippedMessage,
155            "Skipped 2 entries that are not valid domains: not, valid!!."
156        )
157    }
158
159    func testBulkInputDeduplicatesAndIgnoresBlankSeparators() {
160        let parsed = Self.viewModel.parsedBulkInput(from: "example.com,\n\n  example.com ,\napple.com\n\n")
161
162        XCTAssertEqual(parsed.domains, ["example.com", "apple.com"])
163        XCTAssertTrue(parsed.skipped.isEmpty, "whitespace between entries is not an entry")
164        XCTAssertNil(parsed.skippedMessage)
165    }
166
167    func testValidBulkInputReportsNothing() {
168        let parsed = Self.viewModel.parsedBulkInput(from: "example.com\napple.com")
169
170        XCTAssertEqual(parsed.domains.count, 2)
171        XCTAssertNil(parsed.skippedMessage)
172    }
173
174    /// One bad entry reads as a sentence about that entry, not as a count.
175    func testASingleSkippedEntryIsNamedInTheSingular() {
176        let parsed = ParsedBulkInput(domains: ["example.com"], skipped: ["nope!"])
177
178        XCTAssertEqual(parsed.skippedMessage, "Skipped nope!: not a valid domain.")
179    }
180
181    /// The worst case before this change: every entry invalid meant the button
182    /// did nothing at all, with no explanation.
183    func testAllEntriesInvalidSaysThereIsNothingToRun() {
184        let many = ParsedBulkInput(domains: [], skipped: ["a!", "b!"])
185        XCTAssertEqual(
186            many.skippedMessage,
187            "None of these is a valid domain, so there is nothing to run: a!, b!."
188        )
189
190        let one = ParsedBulkInput(domains: [], skipped: ["a!"])
191        XCTAssertEqual(one.skippedMessage, "a! is not a valid domain, so there is nothing to run.")
192    }
193
194    /// A pasted list of typos names the first few and counts the rest, rather
195    /// than becoming a wall of text.
196    func testManySkippedEntriesAreTruncated() {
197        let parsed = ParsedBulkInput(
198            domains: ["example.com"],
199            skipped: ["a!", "b!", "c!", "d!", "e!", "f!", "g!"]
200        )
201
202        XCTAssertEqual(
203            parsed.skippedMessage,
204            "Skipped 7 entries that are not valid domains: a!, b!, c!, d!, e! and 2 more."
205        )
206    }
207
208    /// The whole point: running a bulk lookup leaves the message behind for the
209    /// view to show.
210    func testRunningABulkLookupReportsWhatItSkipped() {
211        let viewModel = Self.viewModel
212        viewModel.bulkInputError = nil
213        viewModel.bulkInput = "example.com, localhost"
214
215        viewModel.runBulkLookup()
216
217        XCTAssertEqual(viewModel.bulkInputError, "Skipped localhost: not a valid domain.")
218    }
219
220    func testABulkLookupWithNothingValidStillReports() {
221        let viewModel = Self.viewModel
222        viewModel.bulkInputError = nil
223        viewModel.bulkInput = "localhost"
224
225        viewModel.runBulkLookup()
226
227        XCTAssertEqual(
228            viewModel.bulkInputError,
229            "localhost is not a valid domain, so there is nothing to run."
230        )
231        XCTAssertFalse(viewModel.batchLookupRunning)
232    }
233
234    func testAValidBulkLookupLeavesNoMessage() {
235        let viewModel = Self.viewModel
236        viewModel.bulkInputError = "stale"
237        viewModel.bulkInput = "example.com"
238
239        viewModel.runBulkLookup()
240
241        XCTAssertNil(viewModel.bulkInputError)
242        viewModel.cancelBatchLookup()
243    }
244
245    func testAnInvalidDomainDoesNotStartALookup() {
246        let viewModel = Self.viewModel
247        viewModel.domain = "localhost"
248
249        viewModel.run()
250
251        XCTAssertFalse(viewModel.hasRun)
252        XCTAssertNotNil(viewModel.domainInputError)
253    }
254
255    func testAStoredSingleLabelDomainStillTracksAndMatchesWorkflows() {
256        let viewModel = Self.viewModel
257        viewModel.trackedDomains = []
258        viewModel.workflows = [DomainWorkflow(name: "Internal", domains: ["localhost"])]
259
260        XCTAssertTrue(viewModel.trackDomain(domain: "localhost", availabilityStatus: nil))
261        XCTAssertEqual(viewModel.workflowsContaining(domain: "localhost").count, 1)
262    }
263}