using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace BizTalkCheckmkPulse.Tests { internal static class Program { private static readonly List Failures = new List(); private static int ExecutedTests; private static int Main() { Run("SelfTestEmitsAllStableServices", SelfTestEmitsAllStableServices); Run("UnavailableSourcesAreUnknown", UnavailableSourcesAreUnknown); Run("UnknownApplicationDoesNotCreateService", UnknownApplicationDoesNotCreateService); Run("KnownApplicationCreatesService", KnownApplicationCreatesService); Run("ServerNamesAreComparedWithoutWql", ServerNamesAreComparedWithoutWql); Run("GroupSettingQueryUsesDocumentedSchema", GroupSettingQueryUsesDocumentedSchema); Run("ProviderSqlLoginFailureIsPermission", ProviderSqlLoginFailureIsPermission); Run("RejectedSqlPrincipalIsExtracted", RejectedSqlPrincipalIsExtracted); Run("PlatformPermissionPropagatesToSqlDiscovery", PlatformPermissionPropagatesToSqlDiscovery); Run("RoutingFailureReportsAreCounted", RoutingFailureReportsAreCounted); Run("ReceiveLocationAllowlistSeparatesExpectedState", ReceiveLocationAllowlistSeparatesExpectedState); Run("UnknownReceiveLocationStateIsNotGreen", UnknownReceiveLocationStateIsNotGreen); Run("SendPortAllowlistSeparatesExpectedState", SendPortAllowlistSeparatesExpectedState); Run("ArtifactSummaryIsBounded", ArtifactSummaryIsBounded); Run("EndpointAddressesResolveWithoutSecrets", EndpointAddressesResolveWithoutSecrets); Run("AdapterSpecificEndpointAddressesResolve", AdapterSpecificEndpointAddressesResolve); Run("EndpointClassificationSeparatesExpectedAndUnresolved", EndpointClassificationSeparatesExpectedAndUnresolved); Run("EndpointCatalogPreservesManualOverrides", EndpointCatalogPreservesManualOverrides); Run("EndpointRuntimeUsesCurrentAddressAndManualOverrides", EndpointRuntimeUsesCurrentAddressAndManualOverrides); Run("EndpointCatalogRoundTrip", EndpointCatalogRoundTrip); Run("EndpointOutputListsOnlyUnavailableTargets", EndpointOutputListsOnlyUnavailableTargets); Run("EndpointOutputExplainsOnlyRealResolutionGaps", EndpointOutputExplainsOnlyRealResolutionGaps); Run("EndpointProbeBudgetFitsMinuteInterval", EndpointProbeBudgetFitsMinuteInterval); Run("ForcedEndpointRefreshRewritesFreshCatalog", ForcedEndpointRefreshRewritesFreshCatalog); Run("EnvironmentLabelDoesNotRenameServicesByDefault", EnvironmentLabelDoesNotRenameServicesByDefault); Run("DefaultServiceContractIsExact", DefaultServiceContractIsExact); Run("InstallerRejectsUnconfirmedServiceRename", InstallerRejectsUnconfirmedServiceRename); Run("InstallerAllowsConfirmedServiceRename", InstallerAllowsConfirmedServiceRename); Run("InstallerAcceptsLegacyEightServiceSelfTest", InstallerAcceptsLegacyEightServiceSelfTest); Run("InstallerRequiresNineServicesForCandidate", InstallerRequiresNineServicesForCandidate); Run("InstallerAllowsAdditiveServiceContract", InstallerAllowsAdditiveServiceContract); Run("InstallerUpdatePreservesExistingSettings", InstallerUpdatePreservesExistingSettings); Run("RuntimeValidationAcceptsFreshConsistentArtifacts", RuntimeValidationAcceptsFreshConsistentArtifacts); Run("RuntimeValidationRejectsPreInstallSnapshot", RuntimeValidationRejectsPreInstallSnapshot); Run("RuntimeValidationRejectsWrongIdentity", RuntimeValidationRejectsWrongIdentity); Run("RuntimeValidationRejectsStaleCatalog", RuntimeValidationRejectsStaleCatalog); Run("RuntimeValidationRejectsChangedServiceContract", RuntimeValidationRejectsChangedServiceContract); Run("RuntimeValidationRejectsUnknownStableService", RuntimeValidationRejectsUnknownStableService); Run("RuntimeValidationAllowsEndpointUnknownAsWarning", RuntimeValidationAllowsEndpointUnknownAsWarning); Run("RuntimeValidationRejectsEndpointUnknownWhenProbeDisabled", RuntimeValidationRejectsEndpointUnknownWhenProbeDisabled); Run("RuntimeValidationAllowsDisabledEndpointProbeWithoutCatalog", RuntimeValidationAllowsDisabledEndpointProbeWithoutCatalog); Run("ForceEndpointRefreshRequiresProviderMode", ForceEndpointRefreshRequiresProviderMode); Run("RuntimeValidationArgumentsAreParsedStrictly", RuntimeValidationArgumentsAreParsedStrictly); Run("TaskCompletionRequiresFreshSuccessfulRun", TaskCompletionRequiresFreshSuccessfulRun); Run("TaskFailureIsDetectedImmediately", TaskFailureIsDetectedImmediately); Run("SnapshotRoundTripPreservesLines", SnapshotRoundTripPreservesLines); Run("SnapshotRejectsTampering", SnapshotRejectsTampering); Run("SnapshotRejectsStaleData", SnapshotRejectsStaleData); Run("SnapshotRejectsDifferentMachine", SnapshotRejectsDifferentMachine); Run("SnapshotReportsMissingFile", SnapshotReportsMissingFile); Run("SnapshotFailureEmitsStableUnknownServices", SnapshotFailureEmitsStableUnknownServices); if (Failures.Count == 0) { Console.WriteLine("PASS: " + ExecutedTests + " tests"); return 0; } foreach (var failure in Failures) { Console.Error.WriteLine("FAIL: " + failure); } return 1; } private static void SelfTestEmitsAllStableServices() { var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); AssertEqual(9, lines.Length, "self-test line count"); AssertEqual(9, lines.Distinct(StringComparer.Ordinal).Count(), "unique self-test lines"); Assert(lines.All(x => x.StartsWith("0 \"BizTalk ", StringComparison.Ordinal)), "every self-test line must be OK"); Assert(lines.Any(x => x.Contains("\"BizTalk Event Log\"")), "Event Log service missing"); Assert(lines.Any(x => x.Contains("\"BizTalk Receive Locations\"")), "Receive Locations service missing"); Assert(lines.Any(x => x.Contains("\"BizTalk Send Ports\"")), "Send Ports service missing"); Assert(lines.Any(x => x.Contains("\"BizTalk Endpoint Reachability\"")), "Endpoint Reachability service missing"); Assert(lines.Any(x => x.Contains("\"BizTalk Orchestrations\"")), "Orchestrations service missing"); } private static void UnavailableSourcesAreUnknown() { var lines = new CheckmkLocalFormatter(new MonitoringOptions()).Format(new ProbeResult()).Take(9).ToArray(); AssertEqual(9, lines.Length, "stable service count"); Assert(lines.All(x => x.StartsWith("3 \"BizTalk ", StringComparison.Ordinal)), "unavailable sources must be UNKNOWN"); } private static void UnknownApplicationDoesNotCreateService() { var options = new MonitoringOptions { EmitPerApplicationSuspensionServices = true }; var result = CreateSuspensionResult("(unknown)"); var lines = new CheckmkLocalFormatter(options).Format(result).ToArray(); AssertEqual(9, lines.Length, "unknown application must not create a dynamic service"); } private static void KnownApplicationCreatesService() { var options = new MonitoringOptions { EmitPerApplicationSuspensionServices = true }; var result = CreateSuspensionResult("Orders"); var lines = new CheckmkLocalFormatter(options).Format(result).ToArray(); AssertEqual(10, lines.Length, "known application should create one dynamic service"); Assert(lines.Any(x => x.Contains("\"BizTalk Suspended Orders\"")), "known application service missing"); } private static void ServerNamesAreComparedWithoutWql() { Assert(WmiBizTalkProbe.IsSameServer("BIZTALK01.corp.example", "biztalk01"), "FQDN and short name must match"); Assert(WmiBizTalkProbe.IsSameServer(@"\\BIZ-TALK+01", "biz-talk+01.example"), "special characters must be compared client-side"); Assert(!WmiBizTalkProbe.IsSameServer("BIZTALK01", "BIZTALK02"), "different servers must not match"); } private static void GroupSettingQueryUsesDocumentedSchema() { var query = WmiBizTalkProbe.GroupSettingQuery; Assert(query.Contains("FROM MSBTS_GroupSetting"), "MSBTS_GroupSetting query missing"); Assert(query.Contains("BizTalkOperatorGroup"), "configured operator group property missing"); Assert(query.Contains("BizTalkReadOnlyUserGroup"), "configured read-only group property missing"); Assert(query.Contains("SubscriptionDBServerName"), "master MessageBox server property missing"); Assert(query.Contains("SubscriptionDBName"), "master MessageBox database property missing"); Assert(query.IndexOf("MessageBoxSetting", StringComparison.OrdinalIgnoreCase) < 0, "unsupported MessageBoxSetting class present"); Assert(WmiBizTalkProbe.SuspendedInstancesQuery.Contains("ServiceClass = 64"), "routing failure report filter missing"); } private static void ProviderSqlLoginFailureIsPermission() { var exception = new COMException( "Internal error from OLEDB provider: 'Login failed for user 'BEW\\AV23AGPWBIO1$'.'", unchecked((int)0x80131904)); AssertEqual( DiagnosticCategory.Permission, WmiBizTalkProbe.ClassifyWmiException(exception), "provider SQL login classification"); } private static void RejectedSqlPrincipalIsExtracted() { var message = "Internal error from OLEDB provider: 'Login failed for user 'BEW\\AV23AGPWBIO1$'.'"; AssertEqual( "BEW\\AV23AGPWBIO1$", WmiBizTalkProbe.ExtractSqlLoginPrincipal(message), "rejected SQL principal"); } private static void PlatformPermissionPropagatesToSqlDiscovery() { var result = new ProbeResult(); result.Diagnostics.Add(new ProbeDiagnostic { Area = DiagnosticArea.Wmi, Category = DiagnosticCategory.Permission, Component = "MSBTS_GroupSetting", Required = true }); new SqlConnectivityProbe(new MonitoringOptions()).Query(result); var discovery = result.Diagnostics.Single(x => x.Area == DiagnosticArea.Sql && x.Component == "BizTalk database discovery"); AssertEqual( DiagnosticCategory.Permission, discovery.Category, "SQL discovery classification"); } private static void RoutingFailureReportsAreCounted() { var result = new ProbeResult(); result.Platform.SuspendedInstancesDataAvailable = true; result.SuspendedInstances.Add(new SuspendedInstance { ApplicationName = "(unknown)", ServiceName = string.Empty, ServiceClassId = 64, Kind = SuspendedKind.NonResumable }); result.SuspendedInstances.Add(new SuspendedInstance { ApplicationName = "Orders", ServiceName = "Receive.Order", Kind = SuspendedKind.Resumable }); var line = FindServiceLine(result, "Suspended Instances"); Assert(line.StartsWith("2 \"BizTalk Suspended Instances\"", StringComparison.Ordinal), "routing failure must be CRIT"); Assert(line.Contains("biztalk_suspended_total=2"), "suspended total metric missing"); Assert(line.Contains("biztalk_suspended_nonresumable=1"), "non-resumable metric missing"); Assert(line.Contains("biztalk_routing_failure_reports=1"), "routing failure metric missing"); Assert(line.Contains("routing_failure_reports=1"), "routing failure summary missing"); } private static void ReceiveLocationAllowlistSeparatesExpectedState() { var options = new MonitoringOptions { ExpectedDisabledReceiveLocations = new[] { "Maintenance\\RL Expected" } }; var result = new ProbeResult(); result.Platform.ReceiveLocationsDataAvailable = true; result.ReceiveLocations.Add(new ReceiveLocationState { ApplicationName = "Maintenance", Name = "RL Expected", IsDisabled = true }); result.ReceiveLocations.Add(new ReceiveLocationState { ApplicationName = "Orders", Name = "RL Orders", IsDisabled = true }); result.ReceiveLocations.Add(new ReceiveLocationState { ApplicationName = "Orders", Name = "RL Active", IsDisabled = false }); var line = FindServiceLine(result, "Receive Locations", options); Assert(line.StartsWith("2 \"BizTalk Receive Locations\"", StringComparison.Ordinal), "unexpected disabled receive location must be CRIT"); Assert(line.Contains("biztalk_receive_locations_enabled=1"), "enabled receive metric missing"); Assert(line.Contains("biztalk_receive_locations_unexpected_disabled=1"), "unexpected disabled metric missing"); Assert(line.Contains("biztalk_receive_locations_expected_disabled=1"), "expected disabled metric missing"); Assert(line.Contains(@"Orders\RL Orders"), "affected receive location missing"); Assert(line.IndexOf("RL Expected", StringComparison.Ordinal) < 0, "expected disabled receive location should not clutter affected list"); options.ExpectedDisabledReceiveLocations = new[] { "Maintenance\\RL Expected", "RL Orders" }; var allExpected = FindServiceLine(result, "Receive Locations", options); Assert(allExpected.StartsWith("0 \"BizTalk Receive Locations\"", StringComparison.Ordinal), "all expected disabled receive locations should be OK"); Assert(allExpected.Contains("biztalk_receive_locations_expected_disabled=2"), "all expected receive count missing"); } private static void SendPortAllowlistSeparatesExpectedState() { var options = new MonitoringOptions { ExpectedInactiveSendPorts = new[] { "Maintenance\\SP Expected" } }; var result = new ProbeResult(); result.Platform.SendPortsDataAvailable = true; result.SendPorts.Add(new SendPortState { ApplicationName = "Maintenance", Name = "SP Expected", Status = 2 }); result.SendPorts.Add(new SendPortState { ApplicationName = "Orders", Name = "SP Orders", Status = 1 }); result.SendPorts.Add(new SendPortState { ApplicationName = "Orders", Name = "SP Active", Status = 3 }); var line = FindServiceLine(result, "Send Ports", options); Assert(line.StartsWith("2 \"BizTalk Send Ports\"", StringComparison.Ordinal), "unexpected inactive send port must be CRIT"); Assert(line.Contains("biztalk_send_ports_started=1"), "started send port metric missing"); Assert(line.Contains("biztalk_send_ports_unexpected_inactive=1"), "unexpected inactive send metric missing"); Assert(line.Contains("biztalk_send_ports_expected_inactive=1"), "expected inactive send metric missing"); Assert(line.Contains(@"Orders\SP Orders(bound)"), "affected send port missing"); Assert(line.IndexOf("SP Expected", StringComparison.Ordinal) < 0, "expected inactive send port should not clutter affected list"); options.ExpectedInactiveSendPorts = new[] { "Maintenance\\SP Expected", "SP Orders" }; var allExpected = FindServiceLine(result, "Send Ports", options); Assert(allExpected.StartsWith("0 \"BizTalk Send Ports\"", StringComparison.Ordinal), "all expected inactive send ports should be OK"); Assert(allExpected.Contains("biztalk_send_ports_expected_inactive=2"), "all expected send count missing"); } private static void UnknownReceiveLocationStateIsNotGreen() { var result = new ProbeResult(); result.Platform.ReceiveLocationsDataAvailable = true; result.ReceiveLocations.Add(new ReceiveLocationState { ApplicationName = "Orders", Name = "RL Missing State", IsDisabled = null }); var line = FindServiceLine(result, "Receive Locations"); Assert(line.StartsWith("3 \"BizTalk Receive Locations\"", StringComparison.Ordinal), "unknown receive state must be UNKNOWN"); Assert(line.Contains("biztalk_receive_locations_unknown=1"), "unknown receive metric missing"); Assert(line.Contains(@"Orders\RL Missing State"), "unknown receive location must be visible"); } private static void ArtifactSummaryIsBounded() { var options = new MonitoringOptions { MaxSummaryItems = 2, MaxDetailCharacters = 256 }; var result = new ProbeResult(); result.Platform.ReceiveLocationsDataAvailable = true; for (var i = 1; i <= 6; i++) { result.ReceiveLocations.Add(new ReceiveLocationState { ApplicationName = "Application", Name = "Disabled-" + i, IsDisabled = true }); } var line = FindServiceLine(result, "Receive Locations", options); Assert(line.Contains("(+4 more)"), "omitted item count missing"); Assert(line.Length < 700, "local check line should remain compact"); var longResult = new ProbeResult(); longResult.Platform.ReceiveLocationsDataAvailable = true; longResult.ReceiveLocations.Add(new ReceiveLocationState { ApplicationName = new string('A', 400), Name = new string('R', 400), IsDisabled = true }); var truncated = FindServiceLine(longResult, "Receive Locations", options); Assert(truncated.Contains("[truncated]"), "detail character limit should be visible"); Assert(truncated.Length < 700, "truncated local check line should remain bounded"); } private static void SnapshotRoundTripPreservesLines() { WithTemporarySnapshot((path, store) => { var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); var generated = DateTime.UtcNow; store.Write(lines, generated, "DOMAIN\\collector$"); var result = store.Read(generated.AddSeconds(10), TimeSpan.FromMinutes(3)); Assert(result.IsSuccess, "snapshot should be readable: " + result.Error); AssertEqual(lines.Length, result.Lines.Count, "snapshot line count"); Assert(lines.SequenceEqual(result.Lines), "snapshot payload changed"); AssertEqual("DOMAIN\\collector$", result.Identity, "snapshot identity"); var replacement = lines.Select(x => x.Replace("Self test OK", "Replacement OK")).ToArray(); store.Write(replacement, generated.AddSeconds(30), "DOMAIN\\collector$"); var replaced = store.Read(generated.AddSeconds(40), TimeSpan.FromMinutes(3)); Assert(replaced.IsSuccess, "replaced snapshot should be readable"); Assert(replacement.SequenceEqual(replaced.Lines), "atomic replacement payload changed"); }); } private static void EndpointAddressesResolveWithoutSecrets() { EndpointCatalogEntry endpoint; string reason; var candidate = new EndpointCandidate { ArtifactType = "SendPort", ApplicationName = "Orders", ArtifactName = "SP Orders", TransportRole = "Primary", AdapterName = "WCF-BasicHttp", Address = "https://api-user:top-secret@example.test/orders?q=secret", Active = true }; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "HTTPS endpoint should resolve: " + reason); AssertEqual("example.test", endpoint.Host, "HTTPS host"); AssertEqual(443, endpoint.Port, "HTTPS port"); Assert(endpoint.Key.IndexOf("secret", StringComparison.OrdinalIgnoreCase) < 0, "catalog key must not contain URI secrets"); Assert(endpoint.Host.IndexOf("secret", StringComparison.OrdinalIgnoreCase) < 0, "catalog host must not contain URI secrets"); candidate.Address = @"\\fileserver\drop\%MessageID%.xml"; candidate.AdapterName = "FILE"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "UNC endpoint should resolve: " + reason); AssertEqual("fileserver", endpoint.Host, "UNC host"); AssertEqual(445, endpoint.Port, "UNC SMB port"); candidate.Address = "recipient@example.test"; candidate.AdapterName = "SMTP"; Assert(!EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "SMTP recipient must not become a host probe"); Assert(!EndpointAddressParser.IsPotentialExternalEndpoint(candidate), "SMTP recipient must not cause UNKNOWN"); candidate.Address = "/Orders/Receive.svc"; candidate.AdapterName = "WCF-CustomIsolated"; candidate.ArtifactType = "ReceiveLocation"; candidate.TransportRole = "Inbound"; Assert(!EndpointAddressParser.IsPotentialExternalEndpoint(candidate), "relative local receive address must not cause UNKNOWN"); } private static void AdapterSpecificEndpointAddressesResolve() { EndpointCatalogEntry endpoint; string reason; var candidate = new EndpointCandidate { ArtifactType = "SendPort", ApplicationName = "Orders", ArtifactName = "SP SQL", TransportRole = "Primary", AdapterName = "WCF-Custom", Address = "mssql://sql01/INSTANCE/Orders", Active = true }; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "WCF-SQL URI should resolve: " + reason); AssertEqual("sql01", endpoint.Host, "WCF-SQL host"); AssertEqual(1433, endpoint.Port, "WCF-SQL default port"); candidate.Address = "mssql://sql01:15433/INSTANCE/Orders"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "WCF-SQL explicit port should resolve: " + reason); AssertEqual(15433, endpoint.Port, "WCF-SQL explicit port"); candidate.Address = "net.tcp://service01/Orders"; candidate.AdapterName = "WCF-NetTcp"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "net.tcp URI should resolve: " + reason); AssertEqual(808, endpoint.Port, "net.tcp default port"); candidate.Address = "transfer.example.test:2222/outbound"; candidate.AdapterName = "Custom Adapter"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "plain host:port should resolve before URI parsing: " + reason); AssertEqual("transfer.example.test", endpoint.Host, "plain host:port host"); AssertEqual(2222, endpoint.Port, "plain host:port port"); candidate.Address = "integration-user@sftp.example.test/inbound"; candidate.AdapterName = "SFTP"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "schema-less SFTP URI with user info should resolve: " + reason); AssertEqual("sftp.example.test", endpoint.Host, "schema-less SFTP host"); AssertEqual(22, endpoint.Port, "schema-less SFTP default port"); Assert(endpoint.Host.IndexOf("integration-user", StringComparison.OrdinalIgnoreCase) < 0, "SFTP user info must not enter catalog host"); candidate.Address = "ftp-user@ftp.example.test:2121/drop"; candidate.AdapterName = "FTP"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "schema-less FTP URI with user info should resolve: " + reason); AssertEqual("ftp.example.test", endpoint.Host, "schema-less FTP host"); AssertEqual(2121, endpoint.Port, "schema-less FTP explicit port"); candidate.Address = "sftp://[2001:db8::10]:2222/inbound"; candidate.AdapterName = "SFTP"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "bracketed IPv6 URI should resolve: " + reason); AssertEqual("2001:db8::10", endpoint.Host, "IPv6 catalog host must not retain URI brackets"); AssertEqual(2222, endpoint.Port, "IPv6 explicit port"); candidate.Address = "oracledb://oracle01/ORDERS/Dedicated"; candidate.AdapterName = "WCF-OracleDB"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "direct Oracle DB URI should resolve: " + reason); AssertEqual("oracle01", endpoint.Host, "Oracle DB host"); AssertEqual(1521, endpoint.Port, "Oracle DB default port"); candidate.Address = "oracledb://ORDERS_TNS"; Assert(!EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "tnsnames alias must not be guessed as DNS host"); candidate.ArtifactType = "ReceiveLocation"; candidate.TransportRole = "Inbound"; candidate.Address = "http://+:8080/Orders"; candidate.AdapterName = "WCF-WebHttp"; Assert(EndpointAddressParser.TryCreate(candidate, out endpoint, out reason), "wildcard listener should resolve: " + reason); AssertEqual("127.0.0.1", endpoint.Host, "wildcard listener loopback host"); AssertEqual(8080, endpoint.Port, "wildcard listener port"); } private static void EndpointClassificationSeparatesExpectedAndUnresolved() { var candidate = new EndpointCandidate { ArtifactType = "ReceiveLocation", ApplicationName = "Orders", ArtifactName = "RL HTTP", TransportRole = "Inbound", AdapterName = "WCF-CustomIsolated", Address = "/Orders/Receive.svc", Active = true }; AssertEqual( EndpointResolutionStatus.ExpectedNonProbeable, EndpointAddressParser.Analyze(candidate).Status, "relative listener classification"); candidate.ArtifactType = "SendPort"; candidate.TransportRole = "Primary"; AssertEqual( EndpointResolutionStatus.Unresolved, EndpointAddressParser.Analyze(candidate).Status, "relative outbound address classification"); candidate.Address = "http://+:8080/Orders"; AssertEqual( EndpointResolutionStatus.Unresolved, EndpointAddressParser.Analyze(candidate).Status, "outbound wildcard must not become a loopback target"); candidate.Dynamic = true; AssertEqual( EndpointResolutionStatus.ExpectedNonProbeable, EndpointAddressParser.Analyze(candidate).Status, "dynamic send port classification"); } private static void EndpointCatalogPreservesManualOverrides() { var candidate = new EndpointCandidate { ArtifactType = "SendPort", ApplicationName = "Orders", ArtifactName = "SP Orders", TransportRole = "Primary", AdapterName = "SFTP", Address = "sftp://discovered.example.test/out", Active = true }; var inactive = new EndpointCandidate { ArtifactType = "ReceiveLocation", ApplicationName = "Orders", ArtifactName = "RL Disabled", TransportRole = "Inbound", AdapterName = "HTTPS", Address = "https://disabled.example.test/in", Active = false }; var existing = new EndpointCatalog { EnvironmentName = "ACC" }; existing.Entries.Add(new EndpointCatalogEntry { Key = candidate.Key, ArtifactType = candidate.ArtifactType, ApplicationName = candidate.ApplicationName, ArtifactName = candidate.ArtifactName, TransportRole = candidate.TransportRole, AdapterName = candidate.AdapterName, Protocol = "TCP", Host = "manual.example.test", Port = 2222, Enabled = true, AutoDiscovered = false }); var synchronized = EndpointConnectivityProbe.SynchronizeCatalog(existing, new[] { candidate, inactive }, DateTime.UtcNow); AssertEqual(1, synchronized.Entries.Count, "manual override count"); AssertEqual("manual.example.test", synchronized.Entries[0].Host, "manual override host"); AssertEqual(2222, synchronized.Entries[0].Port, "manual override port"); Assert(!synchronized.Entries[0].AutoDiscovered, "manual override marker"); Assert(synchronized.Entries.All(x => x.ArtifactName != "RL Disabled"), "inactive receive location must not be added"); } private static void EndpointRuntimeUsesCurrentAddressAndManualOverrides() { var candidate = new EndpointCandidate { ArtifactType = "SendPort", ApplicationName = "Orders", ArtifactName = "SP Orders", TransportRole = "Primary", AdapterName = "WCF-Custom", Address = "https://new.example.test/orders", Active = true }; var catalog = new EndpointCatalog(); var stale = TestEndpoint("SP Orders", "old.example.test"); stale.Key = candidate.Key; catalog.Entries.Add(stale); var state = new EndpointConnectivityState(); var selected = EndpointConnectivityProbe.ResolveActiveEndpoints(catalog, new[] { candidate }, state); AssertEqual(1, selected.Length, "current endpoint selection count"); AssertEqual("new.example.test", selected[0].Host, "current WMI address must replace stale catalog target"); candidate.Address = "adapter-specific-target-without-port"; var manual = TestEndpoint("SP Orders", "manual.example.test"); manual.Key = candidate.Key; manual.AutoDiscovered = false; manual.Port = 7443; catalog.Entries.Clear(); catalog.Entries.Add(manual); state = new EndpointConnectivityState(); selected = EndpointConnectivityProbe.ResolveActiveEndpoints(catalog, new[] { candidate }, state); AssertEqual(1, selected.Length, "manual endpoint selection count"); AssertEqual("manual.example.test", selected[0].Host, "manual override host"); AssertEqual(0, state.UnresolvedActive, "manual override must close resolution gap"); AssertEqual(1, state.ManualOverridesActive, "manual override metric"); } private static void EndpointOutputListsOnlyUnavailableTargets() { var result = new ProbeResult(); result.EndpointConnectivity.RuntimeStateAvailable = true; result.EndpointConnectivity.CatalogAvailable = true; result.EndpointConnectivity.RefreshSucceeded = true; result.EndpointConnectivity.Configured = 2; result.EndpointConnectivity.Active = 2; result.EndpointConnectivity.Results.Add(new EndpointProbeResult { Endpoint = TestEndpoint("Reachable", "up.example.test"), Available = true }); result.EndpointConnectivity.Results.Add(new EndpointProbeResult { Endpoint = TestEndpoint("Unavailable", "down.example.test"), Available = false, Failure = "TCP timeout" }); var line = FindServiceLine(result, "Endpoint Reachability"); Assert(line.StartsWith("2 \"BizTalk Endpoint Reachability\"", StringComparison.Ordinal), "failed endpoint must be CRIT"); Assert(line.Contains("Unavailable"), "unavailable endpoint name missing"); Assert(line.Contains("down.example.test:443/TCP"), "unavailable host missing"); Assert(line.IndexOf("Reachable", StringComparison.Ordinal) < 0, "reachable endpoint must not clutter output"); Assert(line.IndexOf("up.example.test", StringComparison.Ordinal) < 0, "reachable host must not clutter output"); } private static void EndpointOutputExplainsOnlyRealResolutionGaps() { var result = new ProbeResult(); result.EndpointConnectivity.RuntimeStateAvailable = true; result.EndpointConnectivity.CatalogAvailable = true; result.EndpointConnectivity.RefreshSucceeded = true; result.EndpointConnectivity.ExpectedNonProbeableActive = 4; var line = FindServiceLine(result, "Endpoint Reachability"); Assert(line.StartsWith("0 \"BizTalk Endpoint Reachability\"", StringComparison.Ordinal), "expected non-socket endpoints must remain OK"); Assert(line.Contains("biztalk_endpoints_expected_non_socket=4"), "expected non-socket metric missing"); Assert(line.IndexOf("unsupported", StringComparison.OrdinalIgnoreCase) < 0, "legacy unsupported wording must not be emitted"); result.EndpointConnectivity.UnresolvedActive = 1; result.EndpointConnectivity.ResolutionIssues.Add( "endpoint=SendPort:Orders\\SP Custom[Primary] adapter=WCF-Custom reason=Schema ohne Port"); line = FindServiceLine(result, "Endpoint Reachability"); Assert(line.StartsWith("3 \"BizTalk Endpoint Reachability\"", StringComparison.Ordinal), "real resolution gap must be UNKNOWN"); Assert(line.Contains("unresolved_endpoints="), "resolution issue list missing"); Assert(line.Contains("SP Custom"), "resolution issue artifact missing"); } private static void EndpointCatalogRoundTrip() { var directory = Path.Combine(Path.GetTempPath(), "BizTalkCheckmkPulse.CatalogTests." + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); var path = Path.Combine(directory, "endpoints.xml"); try { var catalog = new EndpointCatalog { EnvironmentName = "ACC", SynchronizedUtc = DateTime.UtcNow, ActiveCandidates = 150, UnresolvedCandidates = 7 }; catalog.Entries.Add(TestEndpoint("Orders", "api.example.test")); var store = new EndpointCatalogStore(path, 1048576, 100); store.Write(catalog); var loaded = store.Read("ACC"); AssertEqual(1, loaded.Entries.Count, "catalog entry count"); AssertEqual("api.example.test", loaded.Entries[0].Host, "catalog host"); AssertEqual(443, loaded.Entries[0].Port, "catalog port"); AssertEqual(7, loaded.UnresolvedCandidates, "catalog unresolved candidate count"); Assert(File.ReadAllText(path).IndexOf("top-secret", StringComparison.OrdinalIgnoreCase) < 0, "catalog must not contain URI secrets"); } finally { if (Directory.Exists(directory)) { Directory.Delete(directory, true); } } } private static EndpointCatalogEntry TestEndpoint(string name, string host) { return new EndpointCatalogEntry { Key = name, ArtifactType = "SendPort", ApplicationName = "Orders", ArtifactName = name, TransportRole = "Primary", Protocol = "TCP", Host = host, Port = 443, Enabled = true, AutoDiscovered = true }; } private static void EndpointProbeBudgetFitsMinuteInterval() { var options = new MonitoringOptions(); var seventyTargets = EndpointConnectivityProbe.CalculateWorstCaseProbeMilliseconds( 70, options.EndpointProbeMaxConcurrency, options.EndpointProbeTimeoutMilliseconds); var configuredMaximum = EndpointConnectivityProbe.CalculateWorstCaseProbeMilliseconds( options.EndpointMaxCount, options.EndpointProbeMaxConcurrency, options.EndpointProbeTimeoutMilliseconds); AssertEqual(15000, (int)seventyTargets, "70-target theoretical timeout budget"); Assert(configuredMaximum <= 30000, "configured endpoint worst-case must leave headroom in the minute interval"); } private static void ForcedEndpointRefreshRewritesFreshCatalog() { var directory = Path.Combine(Path.GetTempPath(), "BizTalkCheckmkPulse.ForcedCatalogTests." + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); try { var options = new MonitoringOptions { EnvironmentName = "ACC", EndpointCatalogPath = Path.Combine(directory, "endpoints.xml"), LogDirectory = Path.Combine(directory, "logs"), ForceEndpointCatalogRefresh = true }; var oldTimestamp = DateTime.UtcNow.AddHours(-1); new EndpointCatalogStore( options.EndpointCatalogPath, options.EndpointCatalogMaxBytes, options.EndpointCatalogMaxEntries) .Write(new EndpointCatalog { EnvironmentName = options.EnvironmentName, SynchronizedUtc = oldTimestamp }); var probeResult = new ProbeResult(); probeResult.Platform.ReceiveLocationsDataAvailable = true; probeResult.Platform.SendPortsDataAvailable = true; new EndpointConnectivityProbe(options, new FileLogger(options.LogDirectory, 1, "test")) .Query(probeResult); var refreshed = new EndpointCatalogStore( options.EndpointCatalogPath, options.EndpointCatalogMaxBytes, options.EndpointCatalogMaxEntries) .Read(options.EnvironmentName); Assert(probeResult.EndpointConnectivity.RefreshRequired, "forced catalog refresh was not requested"); Assert(probeResult.EndpointConnectivity.RefreshSucceeded, "forced catalog refresh failed"); Assert(refreshed.SynchronizedUtc > oldTimestamp, "forced catalog refresh did not replace timestamp"); } finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } } private static void EnvironmentLabelDoesNotRenameServicesByDefault() { var options = new MonitoringOptions { EnvironmentName = "ACC" }; var lines = new CheckmkLocalFormatter(options).FormatSelfTest().ToArray(); Assert(lines.Any(x => x.Contains("\"BizTalk Platform\"")), "stable service name without environment missing"); Assert(lines.All(x => x.IndexOf("\"BizTalk ACC ", StringComparison.Ordinal) < 0), "environment label must not rename services by default"); options.IncludeEnvironmentInServiceName = true; lines = new CheckmkLocalFormatter(options).FormatSelfTest().ToArray(); Assert(lines.Any(x => x.Contains("\"BizTalk ACC Platform\"")), "explicit environment service-name opt-in missing"); } private static void DefaultServiceContractIsExact() { var actual = new CheckmkLocalFormatter(new MonitoringOptions()) .FormatSelfTest() .Select(ExtractQuotedServiceName) .ToArray(); var expected = new[] { "BizTalk Platform", "BizTalk SQL Access", "BizTalk Suspended Instances", "BizTalk Host Instances", "BizTalk Receive Locations", "BizTalk Send Ports", "BizTalk Endpoint Reachability", "BizTalk Orchestrations", "BizTalk Event Log" }; AssertEqual(string.Join("|", expected), string.Join("|", actual), "exact default service contract"); } private static void InstallerRejectsUnconfirmedServiceRename() { try { BizTalkCheckmkPulse.Setup.InstallerEngine.EnsureServiceNameCompatibility( new[] { "BizTalk Platform", "BizTalk Event Log" }, new[] { "BizTalk ACC Platform", "BizTalk ACC Event Log" }, false); throw new InvalidOperationException("unconfirmed rename was accepted"); } catch (InvalidOperationException ex) { Assert(ex.Message.Contains("Sicherheitsstopp"), "rename rejection must explain the safety stop"); Assert(ex.Message.Contains("Service Discovery"), "rename rejection must require discovery"); } } private static void InstallerAllowsConfirmedServiceRename() { var unchanged = BizTalkCheckmkPulse.Setup.InstallerEngine.EnsureServiceNameCompatibility( new[] { "BizTalk Platform", "BizTalk Event Log" }, new[] { "BizTalk Event Log", "BizTalk Platform" }, false); AssertEqual(string.Empty, unchanged, "service ordering must not be treated as rename"); var change = BizTalkCheckmkPulse.Setup.InstallerEngine.EnsureServiceNameCompatibility( new[] { "BizTalk ACC Platform" }, new[] { "BizTalk Platform" }, true); Assert(change.Contains("BizTalk ACC Platform"), "confirmed rename must report removed service"); Assert(change.Contains("BizTalk Platform"), "confirmed rename must report new service"); } private static void InstallerAcceptsLegacyEightServiceSelfTest() { var output = string.Join("\r\n", Enumerable.Range(1, 8) .Select(x => "0 \"BizTalk Legacy " + x + "\" - Self test OK")); var services = BizTalkCheckmkPulse.Setup.InstallerEngine.ParseSelfTestOutput( output, string.Empty, 0, null, "Installierte Version"); AssertEqual(8, services.Count, "legacy self-test service count"); } private static void InstallerRequiresNineServicesForCandidate() { var output = string.Join("\n", Enumerable.Range(1, 8) .Select(x => "0 \"BizTalk Candidate " + x + "\" - Self test OK")); try { BizTalkCheckmkPulse.Setup.InstallerEngine.ParseSelfTestOutput( output, string.Empty, 0, 9, "Staging"); throw new InvalidOperationException("candidate with eight services was accepted"); } catch (InvalidOperationException ex) { Assert(ex.Message.Contains("Zeilen=8"), "candidate failure must report actual line count"); Assert(ex.Message.Contains("Erwartet=9"), "candidate failure must report expected line count"); Assert(ex.Message.Contains("Stdout="), "candidate failure must include stdout"); } } private static void InstallerAllowsAdditiveServiceContract() { var change = BizTalkCheckmkPulse.Setup.InstallerEngine.EnsureServiceNameCompatibility( new[] { "BizTalk Platform", "BizTalk Event Log" }, new[] { "BizTalk Platform", "BizTalk Endpoint Reachability", "BizTalk Event Log" }, false); Assert(change.Contains("Entfernt=[]"), "additive contract must not remove a service"); Assert(change.Contains("BizTalk Endpoint Reachability"), "additive contract must report the new service"); } private static string ExtractQuotedServiceName(string line) { var start = line.IndexOf('"') + 1; var end = line.IndexOf('"', start); return line.Substring(start, end - start); } private static void InstallerUpdatePreservesExistingSettings() { var directory = Path.Combine(Path.GetTempPath(), "BizTalkCheckmkPulse.InstallerTests." + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); try { var source = Path.Combine(directory, "source.config"); var existing = Path.Combine(directory, "existing.config"); var staged = Path.Combine(directory, "staged.config"); File.WriteAllText( source, "" + "" + "" + "" + "" + "" + "" + "", new UTF8Encoding(false)); File.WriteAllText( existing, "" + "" + "" + "" + "" + "", new UTF8Encoding(false)); var effectiveEnvironment = BizTalkCheckmkPulse.Setup.InstallerEngine.PrepareConfig( source, staged, existing, string.Empty); var merged = File.ReadAllText(staged); AssertEqual("ACC", effectiveEnvironment, "preserved installer environment"); Assert(merged.Contains("key=\"IncludeEnvironmentInServiceName\" value=\"false\""), "stable service-name default must be added on update"); Assert(merged.Contains("key=\"EndpointProbeMaxConcurrency\" value=\"7\""), "existing operational value must be preserved"); Assert(merged.Contains("key=\"EndpointMaxCount\" value=\"100\""), "superseded old default must migrate to new bounded default"); Assert(merged.Contains("key=\"EndpointCatalogMaxEntries\" value=\"1000\""), "new catalog entry limit must be added"); Assert(merged.Contains("key=\"NewSetting\" value=\"new-default\""), "new source setting must be added"); Assert(merged.IndexOf("RemovedLegacySetting", StringComparison.Ordinal) < 0, "removed legacy key must not be resurrected"); effectiveEnvironment = BizTalkCheckmkPulse.Setup.InstallerEngine.PrepareConfig( source, staged, existing, "PRD"); AssertEqual("PRD", effectiveEnvironment, "requested environment override"); } finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } } private static void RuntimeValidationAcceptsFreshConsistentArtifacts() { var boundary = DateTime.UtcNow.AddMinutes(-1); var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), boundary.AddSeconds(5), "BEW\\t231bizmon", "BEW\\t231bizmon", true, null); Assert(result.IsSuccess, "fresh consistent runtime artifacts must pass: " + result.Error); AssertEqual(9, result.StableServiceCount, "validated stable service count"); } private static void RuntimeValidationRejectsPreInstallSnapshot() { var boundary = DateTime.UtcNow.AddMinutes(-1); var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(-1), boundary.AddSeconds(5), "BEW\\t231bizmon", "BEW\\t231bizmon", true, null); Assert(!result.IsSuccess, "snapshot from before installation must fail"); Assert(result.Error.Contains("nicht aus dem gestarteten Providerlauf"), "old snapshot reason missing"); } private static void RuntimeValidationRejectsWrongIdentity() { var boundary = DateTime.UtcNow.AddMinutes(-1); var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), boundary.AddSeconds(5), "BEW\\other-account", "BEW\\t231bizmon", true, null); Assert(!result.IsSuccess, "unexpected provider identity must fail"); Assert(result.Error.Contains("unerwarteten Identitaet"), "identity mismatch reason missing"); } private static void RuntimeValidationRejectsStaleCatalog() { var boundary = DateTime.UtcNow.AddMinutes(-1); var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), boundary.AddSeconds(-1), "BEW\\t231bizmon", "BEW\\t231bizmon", true, null); Assert(!result.IsSuccess, "catalog from before installation must fail"); Assert(result.Error.Contains("nicht aktualisiert"), "old catalog reason missing"); } private static void RuntimeValidationRejectsChangedServiceContract() { var boundary = DateTime.UtcNow.AddMinutes(-1); var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); lines[0] = lines[0].Replace("BizTalk Platform", "BizTalk Renamed Platform"); var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), boundary.AddSeconds(5), "BEW\\t231bizmon", "BEW\\t231bizmon", true, lines); Assert(!result.IsSuccess, "changed runtime service contract must fail"); Assert(result.Error.Contains("Fehlend=[BizTalk Platform]"), "missing stable service reason missing"); } private static void RuntimeValidationAllowsDisabledEndpointProbeWithoutCatalog() { var boundary = DateTime.UtcNow.AddMinutes(-1); var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), null, "BEW\\t231bizmon", "BEW\\t231bizmon", false, null); Assert(result.IsSuccess, "disabled endpoint probe must not require catalog: " + result.Error); Assert(!result.CatalogSynchronizedUtc.HasValue, "disabled endpoint probe must report no catalog timestamp"); } private static void RuntimeValidationRejectsUnknownStableService() { var boundary = DateTime.UtcNow.AddMinutes(-1); var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); lines[0] = "3" + lines[0].Substring(1); var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), boundary.AddSeconds(5), "BEW\\t231bizmon", "BEW\\t231bizmon", true, lines); Assert(!result.IsSuccess, "UNKNOWN core service must fail runtime acceptance"); Assert(result.Error.Contains("UNKNOWN=[BizTalk Platform]"), "UNKNOWN core service reason missing"); } private static void RuntimeValidationAllowsEndpointUnknownAsWarning() { var boundary = DateTime.UtcNow.AddMinutes(-1); var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); var endpointIndex = Array.FindIndex( lines, x => x.Contains("\"BizTalk Endpoint Reachability\"")); Assert(endpointIndex >= 0, "endpoint service missing from self-test contract"); lines[endpointIndex] = "3 \"BizTalk Endpoint Reachability\" " + "biztalk_endpoints_unresolved=1;;1;0 Endpoint reachability incomplete; unresolved=1."; var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), boundary.AddSeconds(5), "BEW\\t231bizmon", "BEW\\t231bizmon", true, lines); Assert(result.IsSuccess, "endpoint UNKNOWN must be accepted as operational warning: " + result.Error); AssertEqual(1, result.AcceptedUnknownLines.Count, "accepted endpoint UNKNOWN count"); Assert(result.AcceptedUnknownLines[0].Contains("unresolved=1"), "endpoint UNKNOWN detail must be retained"); } private static void RuntimeValidationRejectsEndpointUnknownWhenProbeDisabled() { var boundary = DateTime.UtcNow.AddMinutes(-1); var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); var endpointIndex = Array.FindIndex( lines, x => x.Contains("\"BizTalk Endpoint Reachability\"")); lines[endpointIndex] = "3 \"BizTalk Endpoint Reachability\" - Unexpected UNKNOWN while probe is disabled."; var result = ValidateRuntimeArtifacts( boundary, boundary.AddSeconds(10), null, "BEW\\t231bizmon", "BEW\\t231bizmon", false, lines); Assert(!result.IsSuccess, "endpoint UNKNOWN must be rejected when endpoint probing is disabled"); Assert(result.Error.Contains("UNKNOWN=[BizTalk Endpoint Reachability]"), "disabled-probe UNKNOWN reason missing"); } private static void ForceEndpointRefreshRequiresProviderMode() { var options = MonitoringOptions.Load(new[] { "--collect", "--force-endpoint-refresh" }); Assert(options.Collect, "forced refresh must retain provider mode"); Assert(options.ForceEndpointCatalogRefresh, "forced refresh option missing"); try { MonitoringOptions.Load(new[] { "--force-endpoint-refresh" }); throw new InvalidOperationException("forced refresh without provider mode was accepted"); } catch (Exception ex) { Assert(ex.Message.Contains("valid only in provider mode"), "forced refresh rejection reason missing"); } } private static void RuntimeValidationArgumentsAreParsedStrictly() { var timestamp = DateTime.UtcNow; var identity = "BEW\\t231bizmon"; var options = MonitoringOptions.Load(new[] { "--validate-runtime", "--validation-not-before-utc", timestamp.ToString("o"), "--expected-identity-base64", Convert.ToBase64String(Encoding.UTF8.GetBytes(identity)) }); Assert(options.RuntimeValidation, "runtime validation mode missing"); AssertEqual(timestamp.ToString("o"), options.RuntimeValidationNotBeforeUtc.Value.ToString("o"), "runtime validation timestamp"); AssertEqual(identity, options.ExpectedRuntimeIdentity, "runtime validation identity"); } private static void TaskCompletionRequiresFreshSuccessfulRun() { var boundary = DateTime.UtcNow; Assert(BizTalkCheckmkPulse.Setup.TaskSchedulerService.IsSuccessfulCompletion( 3, 0, boundary.AddSeconds(1), boundary), "fresh successful ready task must pass"); Assert(!BizTalkCheckmkPulse.Setup.TaskSchedulerService.IsSuccessfulCompletion( 4, 0, boundary.AddSeconds(1), boundary), "running task must not pass"); Assert(!BizTalkCheckmkPulse.Setup.TaskSchedulerService.IsSuccessfulCompletion( 3, 1, boundary.AddSeconds(1), boundary), "failed task result must not pass"); Assert(!BizTalkCheckmkPulse.Setup.TaskSchedulerService.IsSuccessfulCompletion( 3, 0, boundary.AddSeconds(-3), boundary), "old successful task must not pass"); } private static void TaskFailureIsDetectedImmediately() { var boundary = DateTime.UtcNow; Assert(BizTalkCheckmkPulse.Setup.TaskSchedulerService.IsFreshCompletedFailure( 3, 8, boundary.AddSeconds(1), boundary), "fresh failed task must be detected"); Assert(!BizTalkCheckmkPulse.Setup.TaskSchedulerService.IsFreshCompletedFailure( 4, 8, boundary.AddSeconds(1), boundary), "running task must not be treated as completed failure"); Assert(!BizTalkCheckmkPulse.Setup.TaskSchedulerService.IsFreshCompletedFailure( 3, 8, boundary.AddSeconds(-3), boundary), "old task failure must not fail a new validation run"); var description = BizTalkCheckmkPulse.Setup.TaskSchedulerService.DescribeResult(8); Assert(description.Contains("0x00000008"), "task result must include hexadecimal code"); } private static RuntimeValidationResult ValidateRuntimeArtifacts( DateTime boundaryUtc, DateTime snapshotUtc, DateTime? catalogUtc, string snapshotIdentity, string expectedIdentity, bool probeEndpoints, string[] snapshotLines) { var directory = Path.Combine(Path.GetTempPath(), "BizTalkCheckmkPulse.RuntimeValidationTests." + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); try { var options = new MonitoringOptions { EnvironmentName = "ACC", SnapshotPath = Path.Combine(directory, "snapshot.txt"), EndpointCatalogPath = Path.Combine(directory, "endpoints.xml"), ProbeEndpointConnectivity = probeEndpoints }; var formatter = new CheckmkLocalFormatter(options); new SnapshotStore(options.SnapshotPath, options.SnapshotMaxBytes).Write( snapshotLines ?? formatter.FormatSelfTest().ToArray(), snapshotUtc, snapshotIdentity); if (catalogUtc.HasValue) { new EndpointCatalogStore( options.EndpointCatalogPath, options.EndpointCatalogMaxBytes, options.EndpointCatalogMaxEntries) .Write(new EndpointCatalog { EnvironmentName = options.EnvironmentName, SynchronizedUtc = catalogUtc.Value }); } return RuntimeValidator.Validate( options, formatter, boundaryUtc, expectedIdentity, boundaryUtc.AddMinutes(1)); } finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } } private static void SnapshotRejectsTampering() { WithTemporarySnapshot((path, store) => { var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); store.Write(lines, DateTime.UtcNow, "DOMAIN\\collector$"); var content = File.ReadAllText(path, Encoding.UTF8); File.WriteAllText(path, content.Replace("Self test OK", "Tampered output"), new UTF8Encoding(false)); var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3)); Assert(!result.IsSuccess, "tampered snapshot must be rejected"); Assert(result.Error.IndexOf("SHA-256", StringComparison.OrdinalIgnoreCase) >= 0, "tamper reason should mention SHA-256"); }); } private static void SnapshotRejectsStaleData() { WithTemporarySnapshot((path, store) => { var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); var generated = DateTime.UtcNow.AddMinutes(-10); store.Write(lines, generated, "DOMAIN\\collector$"); var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3)); Assert(!result.IsSuccess, "stale snapshot must be rejected"); Assert(result.Error.IndexOf("stale", StringComparison.OrdinalIgnoreCase) >= 0, "stale reason missing"); }); } private static void SnapshotRejectsDifferentMachine() { WithTemporarySnapshot((path, store) => { var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray(); store.Write(lines, DateTime.UtcNow, "DOMAIN\\collector$"); var content = File.ReadAllText(path, Encoding.UTF8); var currentMachine = Convert.ToBase64String(Encoding.UTF8.GetBytes(Environment.MachineName)); var otherMachine = Convert.ToBase64String(Encoding.UTF8.GetBytes("OTHER-SERVER")); File.WriteAllText( path, content.Replace("machineBase64=" + currentMachine, "machineBase64=" + otherMachine), new UTF8Encoding(false)); var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3)); Assert(!result.IsSuccess, "snapshot for another machine must be rejected"); Assert(result.Error.IndexOf("different machine", StringComparison.OrdinalIgnoreCase) >= 0, "machine mismatch reason missing"); }); } private static void SnapshotReportsMissingFile() { WithTemporarySnapshot((path, store) => { var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3)); Assert(!result.IsSuccess, "missing snapshot must be rejected"); Assert(result.Error.IndexOf("does not exist", StringComparison.OrdinalIgnoreCase) >= 0, "missing file reason missing"); }); } private static void SnapshotFailureEmitsStableUnknownServices() { var lines = new CheckmkLocalFormatter(new MonitoringOptions()) .FormatSnapshotFailure("Snapshot file does not exist.") .ToArray(); AssertEqual(9, lines.Length, "snapshot failure stable service count"); Assert(lines.All(x => x.StartsWith("3 \"BizTalk ", StringComparison.Ordinal)), "snapshot failure must be UNKNOWN"); Assert(lines.All(x => x.Contains("Scheduled Task")), "snapshot failure must contain provider action"); } private static void WithTemporarySnapshot(Action test) { var directory = Path.Combine(Path.GetTempPath(), "BizTalkCheckmkPulse.Tests." + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); var path = Path.Combine(directory, "snapshot.txt"); try { test(path, new SnapshotStore(path, 1048576)); } finally { if (Directory.Exists(directory)) { Directory.Delete(directory, true); } } } private static ProbeResult CreateSuspensionResult(string applicationName) { var result = new ProbeResult(); result.Platform.SuspendedInstancesDataAvailable = true; result.SuspendedInstances.Add(new SuspendedInstance { ApplicationName = applicationName, ServiceName = "TestService", Kind = SuspendedKind.Resumable }); return result; } private static string FindServiceLine( ProbeResult result, string serviceSuffix, MonitoringOptions options = null) { var effectiveOptions = options ?? new MonitoringOptions(); var token = "\"" + effectiveOptions.ServiceName(serviceSuffix) + "\""; return new CheckmkLocalFormatter(effectiveOptions) .Format(result) .Single(x => x.Contains(token)); } private static void Run(string name, Action test) { ExecutedTests++; try { test(); } catch (Exception ex) { Failures.Add(name + ": " + ex.Message); } } private static void Assert(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } private static void AssertEqual(int expected, int actual, string label) { if (expected != actual) { throw new InvalidOperationException(label + ": expected " + expected + ", actual " + actual); } } private static void AssertEqual(DiagnosticCategory expected, DiagnosticCategory actual, string label) { if (expected != actual) { throw new InvalidOperationException(label + ": expected " + expected + ", actual " + actual); } } private static void AssertEqual(EndpointResolutionStatus expected, EndpointResolutionStatus actual, string label) { if (expected != actual) { throw new InvalidOperationException(label + ": expected " + expected + ", actual " + actual); } } private static void AssertEqual(string expected, string actual, string label) { if (!string.Equals(expected, actual, StringComparison.Ordinal)) { throw new InvalidOperationException(label + ": expected " + expected + ", actual " + actual); } } } }