DomainDigTests/DomainNameTests.swift

162 lines · 6889 bytes

  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    func testAnInvalidDomainDoesNotStartALookup() {
145        let viewModel = Self.viewModel
146        viewModel.domain = "localhost"
147
148        viewModel.run()
149
150        XCTAssertFalse(viewModel.hasRun)
151        XCTAssertNotNil(viewModel.domainInputError)
152    }
153
154    func testAStoredSingleLabelDomainStillTracksAndMatchesWorkflows() {
155        let viewModel = Self.viewModel
156        viewModel.trackedDomains = []
157        viewModel.workflows = [DomainWorkflow(name: "Internal", domains: ["localhost"])]
158
159        XCTAssertTrue(viewModel.trackDomain(domain: "localhost", availabilityStatus: nil))
160        XCTAssertEqual(viewModel.workflowsContaining(domain: "localhost").count, 1)
161    }
162}