using AttendanceHub.Sync.Configuration; using Xunit; namespace AttendanceHub.Sync.Tests; /// /// Config validation tests. /// /// The class under test exists because System.Text.Json silently ignores properties it does not /// model, and DeviceWorker silently substitutes Auto for an unknown read.mode. Both are ways for a /// typo to be absorbed without a sound — which is the same class of failure that disabled delivery /// for ten hours on 2026-10-11. Every test here is therefore about a config that LOOKS like it /// loaded. /// public class ConfigValidatorTests { /// A config shaped exactly like the production one. Any finding here is a false alarm /// that would refuse to start a perfectly good host, so this is the most important test in the file. private static string ValidConfig() => """ { "$comment": "documentation must never fail a deploy", "device": { "deviceId": "phase1-test-01", "displayName": "test", "ip": "172.24.30.9", "port": 4370, "machineNumber": 1, "commKey": 0 }, "devices": { "source": "laravel", "baseAddress": "http://localhost/AttendanceHub/public", "listPath": "/api/v1/devices", "apiToken": "", "refreshSeconds": 60, "fallbackToStatic": true, "machineNumber": 1, "idOverrides": { "172.24.30.9": "phase1-test-01" } }, "sdk": { "commTimeoutSeconds": 5, "expectedSdkVersion": "6.3.1.45" }, "session": { "operationTimeoutMs": 30000, "connectTimeoutMs": 15000 }, "realtime": { "eventMask": 1, "channelCapacity": 256 }, "read": { "mode": "Auto", "lookbackMinutes": 1440, "maxRecordsPerRead": 1000000, "failureRetryLimit": 3, "failureRetryBackoffMs": 15000, "tryTimeWindow": true, "windowedIntervalMs": 15000, "fullReconcileMinutes": 30, "overlapMinutes": 10 }, "supervisor": { "reconnectDelayMs": 5000, "healthIntervalMs": 15000, "readIntervalMs": 60000, "maxReconnectDelayMs": 60000, "pingFailThreshold": 2, "readRecreateThreshold": 6, "liveStaleMinutes": 15 }, "persistence": { "dedupeLogEnabled": false }, "upload": { "enabled": true, "baseAddress": "http://localhost/AttendanceHub/public", "batchPath": "/api/v1/sync/punches", "apiToken": "tok", "deviceId": "172.24.30.9", "timeoutSeconds": 30, "batchSize": 200, "maxConcurrency": 1, "pollingIntervalMs": 15000 } } """; private static string[] Codes(string json) => ConfigValidator.Validate(json).Select(f => f.Code).ToArray(); // ---------- 1) the false-alarm trap ---------- [Fact] public void A_Production_Shape_Config_Produces_No_Findings() { var findings = ConfigValidator.Validate(ValidConfig()); Assert.True(findings.Count == 0, "the shipped config shape must validate cleanly, otherwise the host refuses to start on a " + "good config. Findings: " + string.Join(" | ", findings.Select(f => f.Code + ": " + f.Message))); } [Fact] public void Dollar_Comment_Keys_Are_Always_Allowed() { // The shipped config documents itself with $comment at root AND inside sections. var json = ValidConfig().Replace( "\"commTimeoutSeconds\": 5", "\"commTimeoutSeconds\": 5, \"$comment\": \"sdk note\""); Assert.Empty(ConfigValidator.Validate(json)); } // ---------- 2) the silent-ignore trap: the 2026-10-11 shape ---------- [Fact] public void Unknown_Key_Is_An_Error_With_A_Suggestion() { // "enabel" would be swallowed by the deserializer and delivery would silently stay off. var json = ValidConfig().Replace("\"enabled\": true", "\"enabel\": true"); var findings = ConfigValidator.Validate(json); Assert.Contains("KEY_UNKNOWN", findings.Select(f => f.Code)); var finding = findings.First(f => f.Code == "KEY_UNKNOWN"); Assert.True(finding.IsError, "a swallowed key must block startup, not merely warn"); Assert.Contains("enabled", finding.Message, StringComparison.OrdinalIgnoreCase); } [Fact] public void Unknown_Root_Key_Is_Caught() { var json = ValidConfig().Replace("\"persistence\":", "\"persistense\":"); Assert.Contains("KEY_UNKNOWN", Codes(json)); } // ---------- 3) self-contradictory numbers ---------- [Theory] [InlineData("\"pollingIntervalMs\": 15000", "\"pollingIntervalMs\": 0")] [InlineData("\"pollingIntervalMs\": 15000", "\"pollingIntervalMs\": -1")] [InlineData("\"windowedIntervalMs\": 15000", "\"windowedIntervalMs\": 0")] [InlineData("\"healthIntervalMs\": 15000", "\"healthIntervalMs\": -30")] [InlineData("\"timeoutSeconds\": 30", "\"timeoutSeconds\": 0")] public void Non_Positive_Cadence_Is_Rejected(string from, string to) { var json = ValidConfig().Replace(from, to); Assert.Contains("INTERVAL_NOT_POSITIVE", Codes(json)); } [Fact] public void Batch_Size_Of_Zero_Is_Rejected() { // batchSize=0 claims a batch and uploads nothing, forever, without an error. var json = ValidConfig().Replace("\"batchSize\": 200", "\"batchSize\": 0"); Assert.Contains("VALUE_OUT_OF_RANGE", Codes(json)); } [Fact] public void Inverted_Backoff_Ceiling_Is_Rejected() { // Starting the backoff above its own ceiling leaves the ceiling meaningless. var json = ValidConfig().Replace("\"reconnectDelayMs\": 5000", "\"reconnectDelayMs\": 90000"); Assert.Contains("SUPERVISOR_BACKOFF_INVERTED", Codes(json)); } [Fact] public void Read_Mode_Is_Case_Sensitive_Because_DeviceWorker_Is() { // Lower-casing one letter would otherwise become Auto with no message at all. var json = ValidConfig().Replace("\"mode\": \"Auto\"", "\"mode\": \"auto\""); Assert.Contains("READ_MODE_UNKNOWN", Codes(json)); } // ---------- 4) read.mode: DeviceWorker silently substitutes Auto ---------- [Fact] public void Unknown_Read_Mode_Is_Rejected_Rather_Than_Silently_Becoming_Auto() { var json = ValidConfig().Replace("\"mode\": \"Auto\"", "\"mode\": \"Timewindow\""); var findings = ConfigValidator.Validate(json); var finding = Assert.Single(findings, f => f.Code == "READ_MODE_UNKNOWN"); Assert.Contains("TimeWindow", finding.Message); } // ---------- 5) delivery switched on but unable to run ---------- [Fact] public void Enabled_With_Empty_Endpoint_Is_Rejected() { var json = ValidConfig().Replace( "\"upload\": { \"enabled\": true, \"baseAddress\": \"http://localhost/AttendanceHub/public\"", "\"upload\": { \"enabled\": true, \"baseAddress\": \" \""); Assert.Contains("UPLOAD_ENDPOINT_EMPTY", Codes(json)); } [Fact] public void Disabled_Upload_Needs_No_Endpoint() { // An acquisition-only host is legal; it just has to say so, which the plan print does. var json = ValidConfig().Replace( "\"upload\": { \"enabled\": true, \"baseAddress\": \"http://localhost/AttendanceHub/public\"", "\"upload\": { \"enabled\": false, \"baseAddress\": \" \""); Assert.Empty(ConfigValidator.Validate(json)); } // ---------- 6) the device list has to be resolvable ---------- [Fact] public void Empty_Device_Ip_Is_Rejected() { var json = ValidConfig().Replace("\"ip\": \"172.24.30.9\"", "\"ip\": \"\""); Assert.Contains("DEVICE_IP_EMPTY", Codes(json)); } [Fact] public void Unknown_Device_Source_Is_Rejected() { // An unknown source would otherwise fall back to the single static device without saying so. var json = ValidConfig().Replace("\"source\": \"laravel\"", "\"source\": \"laravell\""); Assert.Contains("DEVICES_SOURCE_UNKNOWN", Codes(json)); } // ---------- 7) malformed input ---------- [Fact] public void Invalid_Json_Is_An_Error_Not_A_Crash() { var findings = ConfigValidator.Validate("{ this is not json "); Assert.Contains(findings, f => f.IsError && f.Code == "JSON_INVALID"); } /// /// The live config must pass, or the next restart refuses to start and takes capture with it. /// Skipped silently when this checkout has no deployed config (any machine but this host). /// [Fact] public void The_Actually_Deployed_Config_Must_Validate() { var path = FindDeployedConfig(); if (path is null) return; // nothing deployed here to guard var findings = ConfigValidator.Validate(File.ReadAllText(path)); Assert.True(findings.Count == 0, $"the deployed config {path} would be REJECTED at startup: " + string.Join(" | ", findings.Select(f => f.Code + ": " + f.Message))); } // ---------- heartbeat: the subsystem whose failure is invisible on its own side ---------- /// Derive a config from the production shape, with a heartbeat section appended. private static string WithHeartbeat(string heartbeatJson) => ValidConfig().Replace( "\"pollingIntervalMs\": 15000 }", "\"pollingIntervalMs\": 15000 },\n " + heartbeatJson); [Fact] public void A_Heartbeat_Section_Against_A_Working_Delivery_Path_Adds_No_Findings() { // The configuration the host will actually be started with. Any finding here is a false // alarm that would take a healthy host down on the next restart. var json = WithHeartbeat("\"heartbeat\": { \"enabled\": true, \"intervalSeconds\": 60 }"); Assert.Empty(ConfigValidator.Validate(json)); } [Fact] public void A_Missing_Heartbeat_Section_Is_Not_A_Finding() { // Opt-in: hosts that do not report must still start. This is the current production state. Assert.Empty(ConfigValidator.Validate(ValidConfig())); } [Fact] public void A_Typo_In_The_Heartbeat_Section_Is_An_Error_Not_A_Silent_Default() { var json = WithHeartbeat("\"heartbeat\": { \"enabled\": true, \"intervallSeconds\": 60 }"); var findings = ConfigValidator.Validate(json); Assert.Contains("KEY_UNKNOWN", findings.Select(f => f.Code)); Assert.Contains("heartbeat.intervallSeconds", findings.First(f => f.Code == "KEY_UNKNOWN").Message); } [Theory] [InlineData(120)] // exactly the backend's online window: a beat arrives just as the last one expires [InlineData(300)] [InlineData(3600)] public void A_Cadence_At_Or_Above_The_Backend_Online_Window_Is_Rejected(int interval) { // Nothing on this side would object to this config: the beats would be sent, accepted and // logged, and every device would still read offline. That silent uselessness is the whole // reason this is an error instead of a warning. var json = WithHeartbeat($"\"heartbeat\": {{ \"enabled\": true, \"intervalSeconds\": {interval} }}"); var findings = ConfigValidator.Validate(json); var finding = findings.FirstOrDefault(f => f.Code == "HEARTBEAT_INTERVAL_TOO_SLOW"); Assert.True(finding is not null, "expected HEARTBEAT_INTERVAL_TOO_SLOW, got: " + string.Join(" | ", findings.Select(f => f.Code))); Assert.True(finding!.IsError, "a reporter that can never look online must block startup"); } [Fact] public void Heartbeat_Enabled_While_Delivery_Is_Off_Is_Rejected() { // The heartbeat rides the upload endpoint and token. With delivery off there is nothing to // send with, so "enabled" would be a setting that does nothing — exactly what this // validator exists to refuse. var json = """ { "upload": { "enabled": false }, "heartbeat": { "enabled": true, "intervalSeconds": 60 } } """; Assert.Contains("HEARTBEAT_REQUIRES_UPLOAD", Codes(json)); } [Fact] public void Heartbeat_Enabled_Without_Any_Upload_Section_Is_Rejected() { var json = """{ "heartbeat": { "enabled": true, "intervalSeconds": 60 } }"""; Assert.Contains("HEARTBEAT_NO_UPLOAD_SECTION", Codes(json)); } private static string? FindDeployedConfig() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { var candidate = Path.Combine(dir.FullName, "publish", "config", "phase1.device.json"); if (File.Exists(candidate)) return candidate; dir = dir.Parent; } return null; } }