From a7d154e1db9fd9904b2255db889144ad15aac2f2 Mon Sep 17 00:00:00 2001 From: Christian Cleberg Date: Fri, 24 Jul 2026 19:27:24 -0500 Subject: test: establish unit-test net for the deterministic core (v5 step 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stands up the DomainDigTests unit-test target the v5.0.0 roadmap flags as the mandatory first move before decomposing the god-files and locking external contracts. The project had no XCTest unit target — only the DomainDigUITests accessibility suite. - New DomainDigTests target (unit_test_bundle), hosted by the app so @testable import DomainDig links. Mirrors the UITests build settings (SWIFT_VERSION 5.0 + MainActor default isolation) to avoid the XCTest override-isolation issue recorded for the Swift 6 targets. Wired into the shared DomainDig scheme's Test action, so it runs in CI and the pre-push audit hook automatically (both invoke the whole scheme). - SnapshotFixture builds the deep LookupSnapshot/DomainReport models through their real initializer and the DomainReportBuilder, exposing only the fields the tests vary. - 36 characterization tests across the four deterministic units the roadmap names: - DiffService: change classification, case/whitespace normalization, DNS record reorder-vs-change, summary phrasing, resolver context note, certificate-warning thresholds. - DomainReportBuilder: snapshot -> report field mapping, primary-IP and DNSSEC derivation, TLS status, partial-snapshot/validation passthrough. - DomainReportExporter: format dispatch, JSON round-trip (the machine contract), CSV/markdown/text/PDF structural invariants, timeline. - DomainDataPortabilityService: CSV round-trip and the merge/dedup semantics (case-insensitive collapse, OR-merged pin state, min-created/max-updated, recency sort) via an ephemeral UserDefaults suite. - build.yml comment updated to reflect the second test target. --- .github/workflows/build.yml | 6 +- DomainDig.xcodeproj/project.pbxproj | 179 ++++++++++++++++++- .../xcshareddata/xcschemes/DomainDig.xcscheme | 10 ++ DomainDigTests/DiffServiceTests.swift | 163 ++++++++++++++++++ .../DomainDataPortabilityServiceTests.swift | 124 +++++++++++++ DomainDigTests/DomainReportBuilderTests.swift | 130 ++++++++++++++ DomainDigTests/DomainReportExporterTests.swift | 107 ++++++++++++ DomainDigTests/Fixtures/SnapshotFixture.swift | 191 +++++++++++++++++++++ 8 files changed, 900 insertions(+), 10 deletions(-) create mode 100644 DomainDigTests/DiffServiceTests.swift create mode 100644 DomainDigTests/DomainDataPortabilityServiceTests.swift create mode 100644 DomainDigTests/DomainReportBuilderTests.swift create mode 100644 DomainDigTests/DomainReportExporterTests.swift create mode 100644 DomainDigTests/Fixtures/SnapshotFixture.swift diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5d9d877..4f09d50 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,8 +6,10 @@ name: Build # # This runs `xcodebuild test`, which also compiles the app, the widget, and the # share extension (the DomainDig scheme's build action pulls both in as -# dependencies). The test target is DomainDigUITests — an accessibility audit -# suite; see DomainDigUITests/AccessibilityAuditHarness.swift. +# dependencies). The scheme has two test targets: DomainDigUITests — an +# accessibility audit suite; see DomainDigUITests/AccessibilityAuditHarness.swift +# — and DomainDigTests — unit coverage of the deterministic core (report builder, +# exporter, diff, portability dedup). # # WHAT THIS JOB IS FOR, given the audit also runs locally: # a clean checkout of the merge result. A local hook runs against the working diff --git a/DomainDig.xcodeproj/project.pbxproj b/DomainDig.xcodeproj/project.pbxproj index d3070e4..37e5bea 100644 --- a/DomainDig.xcodeproj/project.pbxproj +++ b/DomainDig.xcodeproj/project.pbxproj @@ -7,6 +7,9 @@ objects = { /* Begin PBXBuildFile section */ + 38316D90539394C2CC7C12BE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DE8B269A01CC5E593DA3DFC2 /* Foundation.framework */; }; + 47CD3BB1AE143733A73E0E5B /* DomainReportExporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D7C7D97A4006831572F468 /* DomainReportExporterTests.swift */; }; + 81359F63C7A23454B8FA0141 /* DomainReportBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E82320955416797CFE59464A /* DomainReportBuilderTests.swift */; }; 8BBFEF092F9874AE00E8E144 /* DomainInspectionService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BBFEF032F9874AE00E8E144 /* DomainInspectionService.swift */; }; 8BBFEF0A2F9874AE00E8E144 /* DomainReportBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BBFEF042F9874AE00E8E144 /* DomainReportBuilder.swift */; }; 8BBFEF0B2F9874AE00E8E144 /* DomainReportExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BBFEF052F9874AE00E8E144 /* DomainReportExporter.swift */; }; @@ -16,9 +19,19 @@ 8BDA00010000000000000002 /* DomainDigWidgetExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 8BDA00010000000000000001 /* DomainDigWidgetExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 8BDB00010000000000000002 /* DomainDigShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 8BDB00010000000000000001 /* DomainDigShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 8BF9DA872F9B13FB00EF41D5 /* DomainDataPortabilityService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */; }; + A5AF921BC1C2E6E940CC05DC /* SnapshotFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CA789D3607B55E3612E6FFA /* SnapshotFixture.swift */; }; + C7CA9E02B0DC2708DE7A8563 /* DomainDataPortabilityServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */; }; + E959C4D24DAAB3CB80D854B2 /* DiffServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 57D61F819B6EA1C654237C8F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 8B7800612F6090E300933221 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8B7800682F6090E300933221; + remoteInfo = DomainDig; + }; 8BDA00010000000000000003 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 8B7800612F6090E300933221 /* Project object */; @@ -58,6 +71,9 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DiffServiceTests.swift; sourceTree = ""; }; + 54D7C7D97A4006831572F468 /* DomainReportExporterTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainReportExporterTests.swift; sourceTree = ""; }; + 5CA789D3607B55E3612E6FFA /* SnapshotFixture.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SnapshotFixture.swift; sourceTree = ""; }; 8B6472EF300EBFA30018E10A /* SyncedProducts.storekit */ = {isa = PBXFileReference; lastKnownFileType = text; path = SyncedProducts.storekit; sourceTree = ""; }; 8B7800692F6090E300933221 /* DomainDig.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DomainDig.app; sourceTree = BUILT_PRODUCTS_DIR; }; 8BBFEF032F9874AE00E8E144 /* DomainInspectionService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainInspectionService.swift; sourceTree = ""; }; @@ -70,6 +86,10 @@ 8BDB00010000000000000001 /* DomainDigShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = DomainDigShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 8BDC00010000000000000001 /* DomainDigUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DomainDigUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityService.swift; sourceTree = ""; }; + A77F7ED29E7C6669F5E61C04 /* DomainDigTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DomainDigTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityServiceTests.swift; sourceTree = ""; }; + DE8B269A01CC5E593DA3DFC2 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS26.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + E82320955416797CFE59464A /* DomainReportBuilderTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainReportBuilderTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ @@ -109,6 +129,8 @@ }; 8BDA0001000000000000000D /* Shared */ = { isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + ); path = Shared; sourceTree = ""; }; @@ -130,12 +152,22 @@ }; 8BDC0001000000000000000E /* DomainDigUITests */ = { isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + ); path = DomainDigUITests; sourceTree = ""; }; /* End PBXFileSystemSynchronizedRootGroup section */ /* Begin PBXFrameworksBuildPhase section */ + 68EB2A07F42245EE1B09B018 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 38316D90539394C2CC7C12BE /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 8B7800662F6090E300933221 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -167,6 +199,36 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 12026CD045DFB45E9E37D207 /* Frameworks */ = { + isa = PBXGroup; + children = ( + E4CAAB98268DE269071F04E3 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 2B31A5F9F390F512E966D4B1 /* Fixtures */ = { + isa = PBXGroup; + children = ( + 5CA789D3607B55E3612E6FFA /* SnapshotFixture.swift */, + ); + name = Fixtures; + path = Fixtures; + sourceTree = ""; + }; + 7CC29A88387286DE8B4D17B3 /* DomainDigTests */ = { + isa = PBXGroup; + children = ( + 2B31A5F9F390F512E966D4B1 /* Fixtures */, + 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */, + E82320955416797CFE59464A /* DomainReportBuilderTests.swift */, + 54D7C7D97A4006831572F468 /* DomainReportExporterTests.swift */, + CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */, + ); + name = DomainDigTests; + path = DomainDigTests; + sourceTree = ""; + }; 8B7800602F6090E300933221 = { isa = PBXGroup; children = ( @@ -184,6 +246,8 @@ 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */, 8BCA3CBC2F9C8D57004B742C /* LocalAPIModels.swift */, 8BCA3CBD2F9C8D57004B742C /* LocalAPIService.swift */, + 12026CD045DFB45E9E37D207 /* Frameworks */, + 7CC29A88387286DE8B4D17B3 /* DomainDigTests */, ); sourceTree = ""; }; @@ -194,13 +258,40 @@ 8BDA00010000000000000001 /* DomainDigWidgetExtension.appex */, 8BDB00010000000000000001 /* DomainDigShareExtension.appex */, 8BDC00010000000000000001 /* DomainDigUITests.xctest */, + A77F7ED29E7C6669F5E61C04 /* DomainDigTests.xctest */, ); name = Products; sourceTree = ""; }; + E4CAAB98268DE269071F04E3 /* iOS */ = { + isa = PBXGroup; + children = ( + DE8B269A01CC5E593DA3DFC2 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 77CB8BAE320E7119E3283122 /* DomainDigTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 108E5397EABF84F5A56080A9 /* Build configuration list for PBXNativeTarget "DomainDigTests" */; + buildPhases = ( + 34C44EAF4B4DA8C10B33208D /* Sources */, + 68EB2A07F42245EE1B09B018 /* Frameworks */, + A5B47E96AE4B6A13198132C2 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + D17881CF5E934733B8E99DE8 /* PBXTargetDependency */, + ); + name = DomainDigTests; + productName = DomainDigTests; + productReference = A77F7ED29E7C6669F5E61C04 /* DomainDigTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; 8B7800682F6090E300933221 /* DomainDig */ = { isa = PBXNativeTarget; buildConfigurationList = 8B7800742F6090E400933221 /* Build configuration list for PBXNativeTarget "DomainDig" */; @@ -221,8 +312,6 @@ 8BDA0001000000000000000D /* Shared */, ); name = DomainDig; - packageProductDependencies = ( - ); productName = DomainDig; productReference = 8B7800692F6090E300933221 /* DomainDig.app */; productType = "com.apple.product-type.application"; @@ -244,8 +333,6 @@ 8BDA0001000000000000000E /* DomainDigWidget */, ); name = DomainDigWidgetExtension; - packageProductDependencies = ( - ); productName = DomainDigWidgetExtension; productReference = 8BDA00010000000000000001 /* DomainDigWidgetExtension.appex */; productType = "com.apple.product-type.app-extension"; @@ -267,8 +354,6 @@ 8BDB0001000000000000000E /* DomainDigShareExtension */, ); name = DomainDigShareExtension; - packageProductDependencies = ( - ); productName = DomainDigShareExtension; productReference = 8BDB00010000000000000001 /* DomainDigShareExtension.appex */; productType = "com.apple.product-type.app-extension"; @@ -290,8 +375,6 @@ 8BDC0001000000000000000E /* DomainDigUITests */, ); name = DomainDigUITests; - packageProductDependencies = ( - ); productName = DomainDigUITests; productReference = 8BDC00010000000000000001 /* DomainDigUITests.xctest */; productType = "com.apple.product-type.bundle.ui-testing"; @@ -344,6 +427,7 @@ 8BDA00010000000000000006 /* DomainDigWidgetExtension */, 8BDB00010000000000000006 /* DomainDigShareExtension */, 8BDC00010000000000000006 /* DomainDigUITests */, + 77CB8BAE320E7119E3283122 /* DomainDigTests */, ); }; /* End PBXProject section */ @@ -377,9 +461,28 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + A5B47E96AE4B6A13198132C2 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 34C44EAF4B4DA8C10B33208D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E959C4D24DAAB3CB80D854B2 /* DiffServiceTests.swift in Sources */, + 81359F63C7A23454B8FA0141 /* DomainReportBuilderTests.swift in Sources */, + 47CD3BB1AE143733A73E0E5B /* DomainReportExporterTests.swift in Sources */, + C7CA9E02B0DC2708DE7A8563 /* DomainDataPortabilityServiceTests.swift in Sources */, + A5AF921BC1C2E6E940CC05DC /* SnapshotFixture.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 8B7800652F6090E300933221 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -433,9 +536,38 @@ target = 8B7800682F6090E300933221 /* DomainDig */; targetProxy = 8BDC00010000000000000003 /* PBXContainerItemProxy */; }; + D17881CF5E934733B8E99DE8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = DomainDig; + target = 8B7800682F6090E300933221 /* DomainDig */; + targetProxy = 57D61F819B6EA1C654237C8F /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ + 87FD0A9B1630561EDC7F2A3D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 44; + DEVELOPMENT_TEAM = ZCNAX3VL9D; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + MARKETING_VERSION = 4.9.0; + PRODUCT_BUNDLE_IDENTIFIER = net.cleberg.DomainDigTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DomainDig.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/DomainDig"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; 8B7800722F6090E400933221 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -787,9 +919,40 @@ }; name = Release; }; + A6C716A4AC78E316F1378CBB /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 44; + DEVELOPMENT_TEAM = ZCNAX3VL9D; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + MARKETING_VERSION = 4.9.0; + PRODUCT_BUNDLE_IDENTIFIER = net.cleberg.DomainDigTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DomainDig.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/DomainDig"; + }; + name = Debug; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 108E5397EABF84F5A56080A9 /* Build configuration list for PBXNativeTarget "DomainDigTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 87FD0A9B1630561EDC7F2A3D /* Release */, + A6C716A4AC78E316F1378CBB /* Debug */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 8B7800642F6090E300933221 /* Build configuration list for PBXProject "DomainDig" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/DomainDig.xcodeproj/xcshareddata/xcschemes/DomainDig.xcscheme b/DomainDig.xcodeproj/xcshareddata/xcschemes/DomainDig.xcscheme index 5b0bc8e..3de7abf 100644 --- a/DomainDig.xcodeproj/xcshareddata/xcschemes/DomainDig.xcscheme +++ b/DomainDig.xcodeproj/xcshareddata/xcschemes/DomainDig.xcscheme @@ -40,6 +40,16 @@ ReferencedContainer = "container:DomainDig.xcodeproj"> + + + + CertificateWarningLevel { + let ssl = days.map { SnapshotFixture.certificate(daysUntilExpiry: $0) } + return DiffService.certificateWarningLevel(for: SnapshotFixture.snapshot(sslInfo: ssl)) + } + + XCTAssertEqual(level(daysUntilExpiry: nil), .none) + XCTAssertEqual(level(daysUntilExpiry: 45), .none) + XCTAssertEqual(level(daysUntilExpiry: 29), .warning) + XCTAssertEqual(level(daysUntilExpiry: 14), .warning) + XCTAssertEqual(level(daysUntilExpiry: 13), .critical) + XCTAssertEqual(level(daysUntilExpiry: 0), .critical) + } + + func testCrossDomainComparisonPairsBothDomains() { + let a = SnapshotFixture.report(domain: "alpha.example", availability: .registered) + let b = SnapshotFixture.report(domain: "beta.example", availability: .available) + + let result = DiffService.compare(domainA: a, domainB: b) + + XCTAssertEqual(result.domainA, "alpha.example") + XCTAssertEqual(result.domainB, "beta.example") + XCTAssertTrue(result.changeCount > 0) + } +} diff --git a/DomainDigTests/DomainDataPortabilityServiceTests.swift b/DomainDigTests/DomainDataPortabilityServiceTests.swift new file mode 100644 index 0000000..ca2c72c --- /dev/null +++ b/DomainDigTests/DomainDataPortabilityServiceTests.swift @@ -0,0 +1,124 @@ +import XCTest +@testable import DomainDig + +/// Characterization tests for the portability layer's deterministic core: the +/// CSV round-trip and the merge/dedup semantics that `load*/save*` apply. Storage +/// is exercised through an ephemeral `UserDefaults` suite so nothing touches the +/// real app domain. +final class DomainDataPortabilityServiceTests: XCTestCase { + private let suiteName = "DomainDigTests.portability" + private var defaults: UserDefaults! + private let base = Date(timeIntervalSince1970: 1_700_000_000) + + override func setUp() { + super.setUp() + defaults = UserDefaults(suiteName: suiteName) + defaults.removePersistentDomain(forName: suiteName) + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + defaults = nil + super.tearDown() + } + + // MARK: - CSV round-trip + + func testTrackedDomainCSVRoundTripPreservesFields() throws { + let original = TrackedDomain( + domain: "csv.example", + createdAt: base, + updatedAt: base.addingTimeInterval(3_600), + note: "keep an eye on this", + isPinned: true, + monitoringEnabled: false, + lastKnownAvailability: .registered, + certificateWarningLevel: .warning, + certificateDaysRemaining: 12 + ) + + let csv = DataPortabilityCSV.trackedDomains([original]) + let parsed = try DataPortabilityCSV.parseTrackedDomains(from: csv) + + XCTAssertEqual(parsed.count, 1) + let restored = try XCTUnwrap(parsed.first) + XCTAssertEqual(restored.domain, "csv.example") + XCTAssertEqual(restored.note, "keep an eye on this") + XCTAssertTrue(restored.isPinned) + XCTAssertFalse(restored.monitoringEnabled) + XCTAssertEqual(restored.lastKnownAvailability, .registered) + XCTAssertEqual(restored.certificateWarningLevel, .warning) + XCTAssertEqual(restored.certificateDaysRemaining, 12) + } + + func testTrackedDomainCSVParseSkipsRowsWithoutDomain() throws { + let csv = """ + domain,isPinned,monitoringEnabled + ,true,true + valid.example,false,true + """ + + let parsed = try DataPortabilityCSV.parseTrackedDomains(from: csv) + + XCTAssertEqual(parsed.map(\.domain), ["valid.example"]) + } + + // MARK: - Merge / dedup + + func testSaveLoadDeduplicatesSameDomainCaseInsensitively() { + let older = TrackedDomain( + domain: "example.com", + createdAt: base.addingTimeInterval(-100), + updatedAt: base.addingTimeInterval(-50), + isPinned: false, + monitoringEnabled: false + ) + let newer = TrackedDomain( + domain: "EXAMPLE.com", + createdAt: base.addingTimeInterval(-80), + updatedAt: base.addingTimeInterval(-10), + isPinned: true, + monitoringEnabled: false + ) + + DomainDataPortabilityService.saveTrackedDomains([older, newer], defaults: defaults) + let loaded = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) + + XCTAssertEqual(loaded.count, 1, "same domain differing only in case must collapse to one entry") + let merged = loaded[0] + XCTAssertEqual(merged.domain, "example.com") + XCTAssertTrue(merged.isPinned, "pinned state is OR-merged") + XCTAssertFalse(merged.monitoringEnabled) + XCTAssertEqual(merged.createdAt, base.addingTimeInterval(-100), "createdAt takes the earliest") + XCTAssertEqual(merged.updatedAt, base.addingTimeInterval(-10), "updatedAt takes the latest") + } + + func testSaveLoadKeepsDistinctDomainsSortedByRecency() { + let domains = [ + TrackedDomain(domain: "old.example", updatedAt: base.addingTimeInterval(-300)), + TrackedDomain(domain: "new.example", updatedAt: base.addingTimeInterval(-10)), + TrackedDomain(domain: "mid.example", updatedAt: base.addingTimeInterval(-100)) + ] + + DomainDataPortabilityService.saveTrackedDomains(domains, defaults: defaults) + let loaded = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) + + XCTAssertEqual(loaded.map(\.domain), ["new.example", "mid.example", "old.example"]) + } + + func testLoadTrackedDomainsEmptyWhenUnset() { + XCTAssertTrue(DomainDataPortabilityService.loadTrackedDomains(defaults: defaults).isEmpty) + } + + // MARK: - Recent searches + + func testRecentSearchesRoundTripAndTruncateToTwenty() { + let values = (0..<30).map { "domain\($0).example" } + + DomainDataPortabilityService.saveRecentSearches(values, defaults: defaults) + let loaded = DomainDataPortabilityService.loadRecentSearches(defaults: defaults) + + XCTAssertEqual(loaded.count, 20, "recent searches are capped at 20") + XCTAssertEqual(loaded, Array(values.prefix(20)), "order is preserved") + } +} diff --git a/DomainDigTests/DomainReportBuilderTests.swift b/DomainDigTests/DomainReportBuilderTests.swift new file mode 100644 index 0000000..7c8db15 --- /dev/null +++ b/DomainDigTests/DomainReportBuilderTests.swift @@ -0,0 +1,130 @@ +import XCTest +@testable import DomainDig + +/// Characterization tests for the snapshot → report projection. These lock the +/// field-mapping and derivation rules the export/diff contracts depend on. +final class DomainReportBuilderTests: XCTestCase { + private let builder = DomainReportBuilder() + + func testCoreIdentityFieldsPassThrough() { + let report = builder.build( + from: SnapshotFixture.snapshot( + domain: "mapped.example", + resolverURLString: "https://r.example/dns-query" + ), + deriveChangeSummary: false + ) + + XCTAssertEqual(report.domain, "mapped.example") + XCTAssertEqual(report.timestamp, SnapshotFixture.referenceDate) + XCTAssertEqual(report.resolverURLString, "https://r.example/dns-query") + XCTAssertFalse(report.metadata.schemaVersion.isEmpty) + } + + func testAvailabilityDefaultsToUnknownWhenAbsent() { + let unknown = builder.build(from: SnapshotFixture.snapshot(availability: nil), deriveChangeSummary: false) + XCTAssertEqual(unknown.availability, .unknown) + + let registered = builder.build(from: SnapshotFixture.snapshot(availability: .registered), deriveChangeSummary: false) + XCTAssertEqual(registered.availability, .registered) + } + + func testPrimaryIPComesFromFirstARecord() { + let report = builder.build( + from: SnapshotFixture.snapshot( + dnsSections: [ + SnapshotFixture.dnsSection(type: .A, values: ["198.51.100.7", "198.51.100.8"]), + SnapshotFixture.dnsSection(type: .AAAA, values: ["2001:db8::1"]) + ] + ), + deriveChangeSummary: false + ) + + XCTAssertEqual(report.dns.primaryIP, "198.51.100.7") + XCTAssertEqual(report.network.primaryIP, "198.51.100.7") + } + + func testPrimaryIPNilWithoutARecord() { + let report = builder.build( + from: SnapshotFixture.snapshot( + dnsSections: [SnapshotFixture.dnsSection(type: .MX, values: ["mail.example.com"])] + ), + deriveChangeSummary: false + ) + XCTAssertNil(report.dns.primaryIP) + } + + func testDNSSECDerivedFromSections() { + let signed = builder.build( + from: SnapshotFixture.snapshot( + dnsSections: [SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1"], dnssecSigned: true)] + ), + deriveChangeSummary: false + ) + XCTAssertEqual(signed.dns.dnssecSigned, true) + + let unknown = builder.build( + from: SnapshotFixture.snapshot( + dnsSections: [SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1"])] + ), + deriveChangeSummary: false + ) + XCTAssertNil(unknown.dns.dnssecSigned) + } + + func testTLSStatusReflectsCertificatePresence() { + let valid = builder.build( + from: SnapshotFixture.snapshot(sslInfo: SnapshotFixture.certificate()), + deriveChangeSummary: false + ) + XCTAssertEqual(valid.web.tlsStatus, "valid") + + let missing = builder.build(from: SnapshotFixture.snapshot(sslInfo: nil), deriveChangeSummary: false) + XCTAssertEqual(missing.web.tlsStatus, "unavailable") + } + + func testWebHeaderCountAndFinalURL() { + let report = builder.build( + from: SnapshotFixture.snapshot( + httpHeaders: [ + HTTPHeader(name: "Content-Type", value: "text/html"), + HTTPHeader(name: "Strict-Transport-Security", value: "max-age=63072000") + ], + httpStatusCode: 200 + ), + deriveChangeSummary: false + ) + + XCTAssertEqual(report.web.headerCount, 2) + XCTAssertEqual(report.web.statusCode, 200) + XCTAssertNil(report.web.finalURL, "no redirect chain means no final URL") + } + + func testPartialSnapshotAndValidationIssuesPropagate() { + let report = builder.build( + from: SnapshotFixture.snapshot( + isPartialSnapshot: true, + validationIssues: ["missing DNS", "stale WHOIS"] + ), + deriveChangeSummary: false + ) + + XCTAssertTrue(report.isPartialSnapshot) + XCTAssertEqual(report.validationIssues, ["missing DNS", "stale WHOIS"]) + XCTAssertTrue(report.metadata.isPartialSnapshot) + XCTAssertEqual(report.metadata.validationIssues, ["missing DNS", "stale WHOIS"]) + } + + func testRecordSectionsArePreserved() { + let sections = [ + SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1"]), + SnapshotFixture.dnsSection(type: .MX, values: ["mail.example.com"]) + ] + let report = builder.build( + from: SnapshotFixture.snapshot(dnsSections: sections), + deriveChangeSummary: false + ) + + XCTAssertEqual(Set(report.dns.recordSections.map(\.recordType)), [.A, .MX]) + } +} diff --git a/DomainDigTests/DomainReportExporterTests.swift b/DomainDigTests/DomainReportExporterTests.swift new file mode 100644 index 0000000..ddecabf --- /dev/null +++ b/DomainDigTests/DomainReportExporterTests.swift @@ -0,0 +1,107 @@ +import XCTest +@testable import DomainDig + +/// Characterization tests for the export surface. These pin the format dispatch, +/// the JSON round-trip (the canonical machine contract), and the structural +/// invariants of the human-readable formats. +final class DomainReportExporterTests: XCTestCase { + + private let decoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return decoder + }() + + func testEveryFormatProducesNonEmptyData() throws { + let report = SnapshotFixture.report(availability: .registered) + for format in DomainExportFormat.allCases { + let data = try DomainReportExporter.data(for: report, format: format) + XCTAssertFalse(data.isEmpty, "\(format.rawValue) export was empty") + } + } + + func testJSONExportRoundTripsToReport() throws { + let report = SnapshotFixture.report(domain: "roundtrip.example", availability: .registered) + + let data = try DomainReportExporter.data(for: report, format: .json) + let decoded = try decoder.decode(DomainReport.self, from: data) + + XCTAssertEqual(decoded.domain, "roundtrip.example") + XCTAssertEqual(decoded.availability, .registered) + XCTAssertEqual(decoded.timestamp, report.timestamp) + } + + func testBatchJSONExportRoundTripsToReportArray() throws { + let reports = [ + SnapshotFixture.report(domain: "one.example"), + SnapshotFixture.report(domain: "two.example") + ] + + let data = try DomainReportExporter.data(for: reports, format: .json, title: "Batch") + let decoded = try decoder.decode([DomainReport].self, from: data) + + XCTAssertEqual(decoded.map(\.domain), ["one.example", "two.example"]) + } + + func testCSVHasHeaderAndOneRowPerReport() { + let reports = [ + SnapshotFixture.report(domain: "alpha.example"), + SnapshotFixture.report(domain: "beta.example") + ] + + let csv = DomainReportExporter.csv(for: reports) + let lines = csv.split(separator: "\n", omittingEmptySubsequences: false) + + XCTAssertEqual(lines.count, 3, "one header line plus one row per report") + XCTAssertTrue(lines[0].contains("\"domain\"")) + XCTAssertTrue(csv.contains("\"alpha.example\"")) + XCTAssertTrue(csv.contains("\"beta.example\"")) + } + + func testMarkdownIsHeadedAndNamesTheDomain() { + let markdown = DomainReportExporter.markdown(for: SnapshotFixture.report(domain: "md.example")) + + XCTAssertTrue(markdown.hasPrefix("# "), "markdown export should open with an H1") + XCTAssertTrue(markdown.contains("md.example")) + } + + func testTextExportNamesTheDomain() { + let text = DomainReportExporter.text(for: SnapshotFixture.report(domain: "txt.example")) + XCTAssertTrue(text.contains("txt.example")) + } + + func testBatchExportsCarryTitleAndEveryDomain() { + let reports = [ + SnapshotFixture.report(domain: "first.example"), + SnapshotFixture.report(domain: "second.example") + ] + + let markdown = DomainReportExporter.batchMarkdown(for: reports, title: "Portfolio Sweep") + XCTAssertTrue(markdown.contains("Portfolio Sweep")) + XCTAssertTrue(markdown.contains("first.example")) + XCTAssertTrue(markdown.contains("second.example")) + + let text = DomainReportExporter.batchText(for: reports, title: "Portfolio Sweep") + XCTAssertTrue(text.contains("Portfolio Sweep")) + XCTAssertTrue(text.contains("first.example")) + XCTAssertTrue(text.contains("second.example")) + } + + func testPDFExportHasPDFSignature() throws { + let data = try DomainReportExporter.data(for: SnapshotFixture.report(), format: .pdf) + XCTAssertTrue(data.starts(with: Array("%PDF".utf8)), "PDF export should begin with the %PDF signature") + } + + func testTimelineTextNamesTheDomain() { + let reports = [ + SnapshotFixture.report(domain: "timeline.example", timestamp: SnapshotFixture.referenceDate), + SnapshotFixture.report( + domain: "timeline.example", + timestamp: SnapshotFixture.referenceDate.addingTimeInterval(86_400) + ) + ] + + let text = DomainReportExporter.timelineText(for: reports, domain: "timeline.example", includeDiffSummary: false) + XCTAssertTrue(text.contains("timeline.example")) + } +} diff --git a/DomainDigTests/Fixtures/SnapshotFixture.swift b/DomainDigTests/Fixtures/SnapshotFixture.swift new file mode 100644 index 0000000..4129a30 --- /dev/null +++ b/DomainDigTests/Fixtures/SnapshotFixture.swift @@ -0,0 +1,191 @@ +import Foundation +@testable import DomainDig + +/// Deterministic builders for the deep `LookupSnapshot` / `DomainReport` models +/// so the core unit tests can construct inputs without wiring up every one of the +/// ~75 snapshot fields at each call site. +/// +/// `snapshot(...)` exposes only the fields the tests actually vary; everything +/// else defaults to an empty/absent value. `report(...)` runs a snapshot through +/// the real `DomainReportBuilder`, which is both the natural constructor for the +/// otherwise-unconstructable `DomainReport` and, for the builder tests, the unit +/// under test. +enum SnapshotFixture { + /// Fixed instant so timestamp-derived output (diff ranges, export headers) is + /// stable across runs. + static let referenceDate = Date(timeIntervalSince1970: 1_700_000_000) + + static let defaultResolverURL = "https://resolver.example/dns-query" + + static func snapshot( + domain: String = "example.com", + timestamp: Date = referenceDate, + resolverURLString: String = defaultResolverURL, + resultSource: LookupResultSource = .live, + availability: DomainAvailabilityStatus? = nil, + ownership: DomainOwnership? = nil, + dnsSections: [DNSSection] = [], + ptrRecord: String? = nil, + sslInfo: SSLCertificateInfo? = nil, + httpHeaders: [HTTPHeader] = [], + httpStatusCode: Int? = nil, + httpSecurityGrade: String? = nil, + subdomains: [DiscoveredSubdomain] = [], + extendedSubdomains: [DiscoveredSubdomain] = [], + isPartialSnapshot: Bool = false, + validationIssues: [String] = [], + changeSummary: DomainChangeSummary? = nil + ) -> LookupSnapshot { + LookupSnapshot( + historyEntryID: nil, + domain: domain, + timestamp: timestamp, + trackedDomainID: nil, + note: nil, + appVersion: "test", + resolverDisplayName: "Test Resolver", + resolverURLString: resolverURLString, + dataSources: [], + provenanceBySection: [:], + availabilityConfidence: nil, + ownershipConfidence: nil, + subdomainConfidence: nil, + emailSecurityConfidence: nil, + geolocationConfidence: nil, + errorDetails: [:], + isPartialSnapshot: isPartialSnapshot, + validationIssues: validationIssues, + totalLookupDurationMs: nil, + snapshotIndex: nil, + previousSnapshotID: nil, + changeCount: 0, + severitySummary: nil, + dnsSections: dnsSections, + dnsError: nil, + availabilityResult: availability.map { DomainAvailabilityResult(domain: domain, status: $0) }, + suggestions: [], + sslInfo: sslInfo, + sslError: nil, + hstsPreloaded: nil, + httpHeaders: httpHeaders, + httpSecurityGrade: httpSecurityGrade, + httpStatusCode: httpStatusCode, + httpResponseTimeMs: nil, + httpProtocol: nil, + http3Advertised: false, + httpHeadersError: nil, + reachabilityResults: [], + reachabilityError: nil, + ipGeolocation: nil, + ipGeolocationError: nil, + emailSecurity: nil, + emailSecurityError: nil, + ownership: ownership, + ownershipError: nil, + ownershipHistory: [], + ownershipHistoryError: nil, + inferredProvider: nil, + priorProviders: [], + domainClassification: nil, + ownershipTransitions: [], + hostingTransitions: [], + subdomainHistory: [], + riskSignals: [], + intelligenceTimeline: [], + ptrRecord: ptrRecord, + ptrError: nil, + redirectChain: [], + redirectChainError: nil, + subdomains: subdomains, + subdomainsError: nil, + extendedSubdomains: extendedSubdomains, + extendedSubdomainsError: nil, + dnsHistory: [], + dnsHistoryError: nil, + domainPricing: nil, + domainPricingError: nil, + reputation: nil, + reputationError: nil, + portScanResults: [], + portScanError: nil, + changeSummary: changeSummary, + resultSource: resultSource, + cachedSections: [], + statusMessage: nil + ) + } + + static func report( + domain: String = "example.com", + timestamp: Date = referenceDate, + resolverURLString: String = defaultResolverURL, + resultSource: LookupResultSource = .live, + availability: DomainAvailabilityStatus? = nil, + ownership: DomainOwnership? = nil, + dnsSections: [DNSSection] = [], + ptrRecord: String? = nil, + sslInfo: SSLCertificateInfo? = nil, + httpHeaders: [HTTPHeader] = [], + httpStatusCode: Int? = nil, + httpSecurityGrade: String? = nil, + subdomains: [DiscoveredSubdomain] = [], + extendedSubdomains: [DiscoveredSubdomain] = [], + isPartialSnapshot: Bool = false, + validationIssues: [String] = [] + ) -> DomainReport { + DomainReportBuilder().build( + from: snapshot( + domain: domain, + timestamp: timestamp, + resolverURLString: resolverURLString, + resultSource: resultSource, + availability: availability, + ownership: ownership, + dnsSections: dnsSections, + ptrRecord: ptrRecord, + sslInfo: sslInfo, + httpHeaders: httpHeaders, + httpStatusCode: httpStatusCode, + httpSecurityGrade: httpSecurityGrade, + subdomains: subdomains, + extendedSubdomains: extendedSubdomains, + isPartialSnapshot: isPartialSnapshot, + validationIssues: validationIssues + ), + deriveChangeSummary: false + ) + } + + // MARK: - Nested model conveniences + + static func dnsSection( + type: DNSRecordType, + values: [String], + ttl: Int = 300, + dnssecSigned: Bool? = nil, + wildcards: [String] = [] + ) -> DNSSection { + DNSSection( + recordType: type, + records: values.map { DNSRecord(value: $0, ttl: ttl) }, + wildcardRecords: wildcards.map { DNSRecord(value: $0, ttl: ttl) }, + dnssecSigned: dnssecSigned + ) + } + + static func certificate( + commonName: String = "example.com", + issuer: String = "Test CA", + daysUntilExpiry: Int = 90 + ) -> SSLCertificateInfo { + SSLCertificateInfo( + commonName: commonName, + subjectAltNames: [commonName], + issuer: issuer, + validFrom: referenceDate, + validUntil: referenceDate.addingTimeInterval(Double(daysUntilExpiry) * 86_400), + daysUntilExpiry: daysUntilExpiry, + chainDepth: 1 + ) + } +} -- cgit v1.2.3