/* * ThreadPilot - process monitor manager unit tests. */ namespace ThreadPilot.Core.Tests { using System.Collections.ObjectModel; using System.Diagnostics; using System.Threading; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using ThreadPilot.Models; using ThreadPilot.Services; public sealed class ProcessMonitorManagerServiceTests { [Theory] [InlineData(false)] [InlineData(true)] public async Task Start_AppliesRulesToAlreadyRunningProcesses_AndRecoveryReevaluatesSnapshot(bool manual) { var process = new ProcessModel { ProcessId = 41, Name = "game" }; var monitor = new FakeProcessMonitorService(); monitor.RunningProcesses.Add(process); var autoApply = CreateAutoApplyService(); using var manager = CreateService( monitor, CreateAssociationService(new ProcessMonitorConfiguration()), CreatePowerPlanService(), CreateNotificationService(), CreateProcessService(), CreateCoreMaskService(), CreateAffinityApplyService(), autoApply); if (manual) { await manager.SetAutomationMonitoringEnabledAsync(true); } else { await manager.StartAsync(); } autoApply.Verify( x => x.ApplyForDiscoveredProcessesAsync( It.Is>(ps => ps.Any(p => p.ProcessId == 41)), It.IsAny()), Times.Once); autoApply.Verify(x => x.MarkProcessExited(41), Times.Once); var applied = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); autoApply.Setup(x => x.ApplyForDiscoveredProcessesAsync( It.Is>(ps => ps.Any(p => p.ProcessId == 42)), It.IsAny())) .Callback(() => applied.TrySetResult()) .ReturnsAsync(Array.Empty()); monitor.RunningProcesses.Add(new ProcessModel { ProcessId = 42, Name = "missed-during-sleep" }); monitor.RaiseSnapshotRefreshed(); await applied.Task.WaitAsync(TimeSpan.FromSeconds(3)); autoApply.Verify(x => x.MarkProcessExited(41), Times.Exactly(2)); autoApply.Verify(x => x.MarkProcessExited(42), Times.Once); } [Fact] public async Task StartAsync_WhenFileLoggingCannotInitialize_StillStartsMonitoring() { var monitor = new FakeProcessMonitorService(); var diagnostics = CreateEnhancedLogger(); diagnostics.Setup(x => x.InitializeAsync()).ThrowsAsync(new IOException("Log directory unavailable")); using var manager = CreateService( monitor, CreateAssociationService(new ProcessMonitorConfiguration()), CreatePowerPlanService(), CreateNotificationService(), CreateProcessService(), CreateCoreMaskService(), CreateAffinityApplyService(), enhancedLogger: diagnostics); await manager.StartAsync(); Assert.True(manager.IsRunning); Assert.True(monitor.IsMonitoring); } [Fact] public async Task StartAsync_InitializesPersistentLoggingBeforeMonitoring() { var monitor = new FakeProcessMonitorService(); var diagnostics = CreateEnhancedLogger(); var initialized = false; diagnostics.Setup(x => x.InitializeAsync()) .Callback(() => initialized = true) .Returns(Task.CompletedTask); diagnostics.Setup(x => x.LogSystemEventAsync( It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => Assert.True(initialized)) .Returns(Task.CompletedTask); using var manager = CreateService( monitor, CreateAssociationService(new ProcessMonitorConfiguration()), CreatePowerPlanService(), CreateNotificationService(), CreateProcessService(), CreateCoreMaskService(), CreateAffinityApplyService(), enhancedLogger: diagnostics); await manager.StartAsync(); diagnostics.Verify(x => x.InitializeAsync(), Times.Once); Assert.True(monitor.IsMonitoring); } [Fact] public async Task StartAsync_LoadsConfiguration_AndStartsMonitoring() { var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); Assert.True(manager.IsRunning); Assert.Equal("Running", manager.Status); Assert.Equal(1, processMonitor.StartCalls); associationService.Verify(x => x.LoadConfigurationAsync(), Times.Once); } [Fact] public async Task SetAutomationMonitoringEnabledAsync_StopsAndPersistsDisabledState() { var processMonitor = new FakeProcessMonitorService(); var settings = new ApplicationSettingsModel(); var manager = CreateService( processMonitor, CreateAssociationService(new ProcessMonitorConfiguration()), CreatePowerPlanService(), CreateNotificationService(), CreateProcessService(), CreateCoreMaskService(), CreateAffinityApplyService(), settings: settings); await manager.StartAsync(); await manager.SetAutomationMonitoringEnabledAsync(false); Assert.False(manager.IsRunning); Assert.Equal(1, processMonitor.StopCalls); Assert.False(settings.EnableAutomationMonitoring); } [Fact] public async Task SetAutomationMonitoringEnabledAsync_StartsAndPersistsEnabledState() { var processMonitor = new FakeProcessMonitorService(); var settings = new ApplicationSettingsModel { EnableAutomationMonitoring = false }; var manager = CreateService( processMonitor, CreateAssociationService(new ProcessMonitorConfiguration()), CreatePowerPlanService(), CreateNotificationService(), CreateProcessService(), CreateCoreMaskService(), CreateAffinityApplyService(), settings: settings); await manager.SetAutomationMonitoringEnabledAsync(true); Assert.True(manager.IsRunning); Assert.Equal(1, processMonitor.StartCalls); Assert.True(settings.EnableAutomationMonitoring); } [Fact] public async Task StartAsync_SelectsHighestPriorityAssociation() { var processMonitor = new FakeProcessMonitorService { RunningProcesses = { new ProcessModel { ProcessId = 1, Name = "game-low" }, new ProcessModel { ProcessId = 2, Name = "game-high" }, }, }; var configuration = new ProcessMonitorConfiguration { Associations = { new ProcessPowerPlanAssociation("game-low", "plan-low", "Low") { Priority = 1 }, new ProcessPowerPlanAssociation("game-high", "plan-high", "High") { Priority = 10 }, }, PowerPlanChangeDelayMs = 0, }; var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); powerPlanService.Verify( x => x.SetActivePowerPlanByGuidAsync("plan-high", true), Times.Once); notificationService.Verify( x => x.ShowPowerPlanChangeNotificationAsync("Balanced", "plan-high-name", "game-high"), Times.Once); } [Fact] public async Task PersistentRuleAndAssociation_OrderIsObservable() { var process = new ProcessModel { ProcessId = 10, Name = "game", Priority = ProcessPriorityClass.Normal }; var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration { PowerPlanChangeDelayMs = 0, Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") { ProcessPriority = ProcessPriorityClass.Normal.ToString(), }, }, }; var autoApply = CreateAutoApplyService(); autoApply .Setup(x => x.ApplyForProcessStartAsync(process, It.IsAny())) .ReturnsAsync(() => { process.Priority = ProcessPriorityClass.High; return [ new PersistentRuleAutoApplyResult { Success = true, RuleId = "persistent-high", ProcessId = process.ProcessId, ProcessName = process.Name, RequestedPriority = ProcessPriorityClass.High, ObservedPriority = ProcessPriorityClass.High, PriorityVerified = true, }, ]; }); var processService = CreateProcessService(); processService.Setup(x => x.TrackPriorityChange(process.ProcessId, ProcessPriorityClass.High)); processService .Setup(x => x.SetProcessPriority(process, ProcessPriorityClass.Normal, ProcessPriorityWriteSource.PowerPlanAssociation)) .Returns(() => { process.Priority = ProcessPriorityClass.Normal; return Task.CompletedTask; }); var manager = CreateService( processMonitor, CreateAssociationService(configuration), CreatePowerPlanService(), CreateNotificationService(), processService, CreateCoreMaskService(), CreateAffinityApplyService(), autoApply); await manager.StartAsync(); processMonitor.RaiseProcessStarted(process); await Task.Delay(50); Assert.Equal(ProcessPriorityClass.Normal, process.Priority); autoApply.Verify(x => x.ApplyForProcessStartAsync(process, It.IsAny()), Times.Once); processService.Verify(x => x.SetProcessPriority(process, ProcessPriorityClass.Normal, ProcessPriorityWriteSource.PowerPlanAssociation), Times.Once); } [Fact] public async Task ProcessStarted_WithDelay_TriggersSingleReevaluation() { var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration { PowerPlanChangeDelayMs = 25, Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 5 }, }, }; var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 10, Name = "game" }); processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 11, Name = "game" }); await Task.Delay(150); powerPlanService.Verify( x => x.SetActivePowerPlanByGuidAsync("plan-game", true), Times.Once); } [Fact] public async Task ProcessStarted_SamePlanRequest_IsSuppressedWithinDuplicateWindow() { var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration { PowerPlanChangeDelayMs = 0, Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 5 }, }, }; var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 10, Name = "game" }); processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 11, Name = "game" }); await Task.Delay(100); powerPlanService.Verify( x => x.SetActivePowerPlanByGuidAsync("plan-game", true), Times.Once); } [Fact] public async Task ProcessStarted_WhenPowerPlanChangeFails_DoesNotRetrySamePlanImmediately() { var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration { PowerPlanChangeDelayMs = 0, Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 5 }, }, }; var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); powerPlanService .Setup(x => x.SetActivePowerPlanByGuidAsync("plan-game", true)) .ReturnsAsync(false); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 10, Name = "game" }); processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 11, Name = "game" }); await Task.Delay(100); powerPlanService.Verify( x => x.SetActivePowerPlanByGuidAsync("plan-game", true), Times.Once); notificationService.Verify( x => x.ShowPowerPlanChangeNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public async Task StopAsync_RestoresDefaultPowerPlan_WhenConfigured() { var processMonitor = new FakeProcessMonitorService { RunningProcesses = { new ProcessModel { ProcessId = 21, Name = "game" }, }, }; var configuration = new ProcessMonitorConfiguration { DefaultPowerPlanGuid = "plan-default", DefaultPowerPlanName = "Balanced", PowerPlanChangeDelayMs = 0, Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 1 }, }, }; var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); await manager.StopAsync(); powerPlanService.Verify( x => x.SetActivePowerPlanByGuidAsync("plan-default", true), Times.AtLeastOnce); processService.Verify(x => x.UntrackProcess(21), Times.Once); coreMaskService.Verify(x => x.UnregisterMaskApplication(21), Times.Once); } [Fact] public async Task ProcessStarted_AppliesConfiguredCoreMaskForMatchingProcess() { var process = new ProcessModel { ProcessId = 31, Name = "game" }; var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration { PowerPlanChangeDelayMs = 0, Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") { CoreMaskId = "mask-game", Priority = 5, }, }, }; var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); processService.Setup(x => x.TrackAppliedMask(31, "mask-game")); var coreMaskService = CreateCoreMaskService(); coreMaskService.SetupGet(x => x.AvailableMasks).Returns(new ObservableCollection { new() { Id = "mask-game", Name = "Game Mask", BoolMask = new ObservableCollection { true, false }, }, }); coreMaskService.Setup(x => x.RegisterMaskApplication(31, "mask-game")); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); processMonitor.RaiseProcessStarted(process); await Task.Delay(100); affinityApplyService.Verify(x => x.ApplyAsync(process, 1), Times.Once); processService.Verify(x => x.TrackAppliedMask(31, "mask-game"), Times.Once); coreMaskService.Verify(x => x.RegisterMaskApplication(31, "mask-game"), Times.Once); } [Fact] public async Task ProcessStarted_AppliesPersistentRulesThroughCoordinator() { var process = new ProcessModel { ProcessId = 41, Name = "game.exe" }; var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var autoApplyService = CreateAutoApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService, autoApplyService); await manager.StartAsync(); processMonitor.RaiseProcessStarted(process); await Task.Delay(100); autoApplyService.Verify( x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), It.IsAny()), Times.Once); autoApplyService.Verify( x => x.ApplyForProcessStartAsync(process, It.IsAny()), Times.Once); } [Fact] public async Task EvaluateCurrentProcessesAsync_WhenPersistentRuleSnapshotApplyCancels_DoesNotLogWarning() { var processMonitor = new FakeProcessMonitorService { RunningProcesses = { new ProcessModel { ProcessId = 42, Name = "game.exe" }, }, }; var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var autoApplyService = CreateAutoApplyService(); autoApplyService .Setup(x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), It.IsAny())) .ThrowsAsync(new OperationCanceledException()); var logger = new CapturingLogger(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService, autoApplyService, logger); await manager.StartAsync(); await manager.EvaluateCurrentProcessesAsync(); Assert.Empty(logger.WarningMessages); } [Fact] public async Task ProcessStarted_WhenPersistentRuleAutoApplyCancels_DoesNotLogWarning() { var process = new ProcessModel { ProcessId = 43, Name = "game.exe" }; var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var autoApplyService = CreateAutoApplyService(); autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, It.IsAny())) .ThrowsAsync(new OperationCanceledException()); var logger = new CapturingLogger(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService, autoApplyService, logger); await manager.StartAsync(); processMonitor.RaiseProcessStarted(process); await Task.Delay(100); Assert.Empty(logger.WarningMessages); } [Fact] public async Task EvaluateCurrentProcessesAsync_WhenPersistentRuleAutoApplyThrows_LogsWarningWithoutBreakingRefresh() { var processMonitor = new FakeProcessMonitorService { RunningProcesses = { new ProcessModel { ProcessId = 44, Name = "game.exe" }, }, }; var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var autoApplyService = CreateAutoApplyService(); autoApplyService .Setup(x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("auto apply failed")); var logger = new CapturingLogger(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService, autoApplyService, logger); await manager.StartAsync(); await manager.EvaluateCurrentProcessesAsync(); Assert.Contains( logger.WarningMessages, message => message.Contains("snapshot refresh", StringComparison.OrdinalIgnoreCase)); Assert.True(manager.IsRunning); } [Fact] public async Task ProcessStarted_WhenPersistentRuleAutoApplyThrows_LogsWarningWithoutBreakingStartHandling() { var process = new ProcessModel { ProcessId = 45, Name = "game.exe" }; var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var autoApplyService = CreateAutoApplyService(); autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, It.IsAny())) .ThrowsAsync(new InvalidOperationException("auto apply failed")); var logger = new CapturingLogger(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService, autoApplyService, logger); await manager.StartAsync(); processMonitor.RaiseProcessStarted(process); await Task.Delay(100); Assert.Contains( logger.WarningMessages, message => message.Contains("Persistent rule auto-apply failed", StringComparison.OrdinalIgnoreCase)); Assert.True(manager.IsRunning); } [Fact] public async Task ProcessStarted_WhenPersistentRuleAutoApplySucceeds_LogsEnhancedMonitoringEvent() { var process = new ProcessModel { ProcessId = 46, Name = "game.exe" }; var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var autoApplyService = CreateAutoApplyService(); autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, It.IsAny())) .ReturnsAsync(new[] { new PersistentRuleAutoApplyResult { Success = true, RuleId = "rule-game", ProcessId = process.ProcessId, ProcessName = process.Name, UserMessage = "Persistent rule applied.", }, }); var enhancedLogger = CreateEnhancedLogger(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService, autoApplyService, enhancedLogger: enhancedLogger); await manager.StartAsync(); processMonitor.RaiseProcessStarted(process); await Task.Delay(100); enhancedLogger.Verify( x => x.LogProcessMonitoringEventAsync( LogEventTypes.ProcessMonitoring.AssociationTriggered, process.Name, process.ProcessId, It.Is(message => message.Contains("Persistent rule 'rule-game' applied automatically", StringComparison.Ordinal))), Times.Once); } [Fact] public async Task ProcessStarted_WhenPersistentRuleAutoApplyReturnsFailure_DoesNotNotifyOrThrow() { var process = new ProcessModel { ProcessId = 47, Name = "game.exe" }; var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var autoApplyService = CreateAutoApplyService(); autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, It.IsAny())) .ReturnsAsync(new[] { new PersistentRuleAutoApplyResult { Success = false, RuleId = "rule-game", ProcessId = process.ProcessId, ProcessName = process.Name, UserMessage = ProcessOperationUserMessages.AccessDenied, IsAccessDenied = true, }, }); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService, autoApplyService); await manager.StartAsync(); processMonitor.RaiseProcessStarted(process); await Task.Delay(100); Assert.True(manager.IsRunning); notificationService.Verify( x => x.ShowNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); notificationService.Verify( x => x.ShowErrorNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public async Task ProcessStarted_WithoutRelevantAssociation_DoesNotEnrichOrPersistEventLog() { var processMonitor = new FakeProcessMonitorService(); var configuration = new ProcessMonitorConfiguration(); var processService = CreateProcessService(); var enhancedLogger = CreateEnhancedLogger(); var manager = CreateService( processMonitor, CreateAssociationService(configuration), CreatePowerPlanService(), CreateNotificationService(), processService, CreateCoreMaskService(), CreateAffinityApplyService(), enhancedLogger: enhancedLogger); await manager.StartAsync(); enhancedLogger.Invocations.Clear(); processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 42, Name = "irrelevant" }); await Task.Delay(100); processService.Verify( service => service.RefreshProcessInfo(It.IsAny()), Times.Never); enhancedLogger.Verify( logger => logger.LogProcessMonitoringEventAsync( It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public async Task ProcessStopped_AlwaysClearsPidCaches() { var processMonitor = new FakeProcessMonitorService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var autoApplyService = CreateAutoApplyService(); var manager = CreateService( processMonitor, CreateAssociationService(new ProcessMonitorConfiguration()), CreatePowerPlanService(), CreateNotificationService(), processService, coreMaskService, CreateAffinityApplyService(), autoApplyService); await manager.StartAsync(); processMonitor.RaiseProcessStopped(new ProcessModel { ProcessId = 73, Name = "short-lived" }); await Task.Delay(100); autoApplyService.Verify(service => service.MarkProcessExited(73), Times.Once); coreMaskService.Verify(service => service.UnregisterMaskApplication(73), Times.Once); processService.Verify(service => service.UntrackProcess(73), Times.Once); } [Fact] public async Task Dispose_CompletesOnBlockingSynchronizationContext() { var processMonitor = new FakeProcessMonitorService { StopMonitoringAsyncImpl = async () => { await Task.Yield(); }, }; var configuration = new ProcessMonitorConfiguration(); var associationService = CreateAssociationService(configuration); var powerPlanService = CreatePowerPlanService(); var notificationService = CreateNotificationService(); var processService = CreateProcessService(); var coreMaskService = CreateCoreMaskService(); var affinityApplyService = CreateAffinityApplyService(); var manager = CreateService( processMonitor, associationService, powerPlanService, notificationService, processService, coreMaskService, affinityApplyService); await manager.StartAsync(); Exception? disposeException = null; using var completed = new ManualResetEventSlim(false); var disposeThread = new Thread(() => { SynchronizationContext.SetSynchronizationContext(new BlockingSynchronizationContext()); try { manager.Dispose(); } catch (Exception ex) { disposeException = ex; } finally { completed.Set(); } }); disposeThread.Start(); Assert.True(completed.Wait(TimeSpan.FromSeconds(1)), "Dispose did not complete promptly."); Assert.Null(disposeException); Assert.Equal(1, processMonitor.StopCalls); Assert.Equal(1, processMonitor.DisposeCalls); } [Fact] public async Task StopAsync_CancelsUnassociatedAutomationAndRestartGetsFreshLifetime() { var monitor = new FakeProcessMonitorService(); var automation = CreateAutoApplyService(); var tokens = new List(); automation.Setup(x => x.ApplyForProcessStartAsync( It.IsAny(), It.IsAny())) .Callback((_, token) => tokens.Add(token)) .ReturnsAsync(Array.Empty()); using var manager = CreateService( monitor, CreateAssociationService(new ProcessMonitorConfiguration()), CreatePowerPlanService(), CreateNotificationService(), CreateProcessService(), CreateCoreMaskService(), CreateAffinityApplyService(), automation); await manager.StartAsync(); monitor.RaiseProcessStarted(new ProcessModel { ProcessId = 42, Name = "game" }); Assert.Single(tokens); Assert.True(tokens[0].CanBeCanceled); Assert.False(tokens[0].IsCancellationRequested); await manager.StopAsync(); Assert.True(tokens[0].IsCancellationRequested); await manager.StartAsync(); monitor.RaiseProcessStarted(new ProcessModel { ProcessId = 43, Name = "game" }); Assert.Equal(2, tokens.Count); Assert.False(tokens[1].IsCancellationRequested); await manager.StopAsync(); Assert.True(tokens[1].IsCancellationRequested); } private static ProcessMonitorManagerService CreateService( FakeProcessMonitorService processMonitorService, Mock associationService, Mock powerPlanService, Mock notificationService, Mock processService, Mock coreMaskService, Mock affinityApplyService, Mock? autoApplyService = null, ILogger? logger = null, Mock? enhancedLogger = null, ApplicationSettingsModel? settings = null) { var resolvedEnhancedLogger = enhancedLogger ?? CreateEnhancedLogger(); var persistedSettings = settings ?? new ApplicationSettingsModel(); var settingsService = new Mock(MockBehavior.Loose); settingsService.SetupGet(x => x.Settings).Returns(() => persistedSettings); settingsService .Setup(x => x.UpdateSettingsAsync(It.IsAny())) .Callback(updated => persistedSettings.CopyFrom(updated)) .Returns(Task.CompletedTask); return new ProcessMonitorManagerService( processMonitorService, associationService.Object, powerPlanService.Object, notificationService.Object, settingsService.Object, processService.Object, coreMaskService.Object, affinityApplyService.Object, (autoApplyService ?? CreateAutoApplyService()).Object, new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => DateTimeOffset.UtcNow), logger ?? NullLogger.Instance, resolvedEnhancedLogger.Object); } private static Mock CreateEnhancedLogger() { var enhancedLogger = new Mock(MockBehavior.Loose); enhancedLogger .Setup(x => x.LogSystemEventAsync(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); enhancedLogger .Setup(x => x.LogProcessMonitoringEventAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); enhancedLogger .Setup(x => x.LogErrorAsync(It.IsAny(), It.IsAny(), It.IsAny?>())) .Returns(Task.CompletedTask); return enhancedLogger; } private static Mock CreateAssociationService(ProcessMonitorConfiguration configuration) { var associationService = new Mock(MockBehavior.Strict); associationService.SetupGet(x => x.Configuration).Returns(configuration); associationService.Setup(x => x.LoadConfigurationAsync()).ReturnsAsync(true); return associationService; } private static Mock CreatePowerPlanService() { var powerPlanService = new Mock(MockBehavior.Strict); powerPlanService.Setup(x => x.GetActivePowerPlan()).ReturnsAsync(new PowerPlanModel { Guid = "balanced", Name = "Balanced" }); powerPlanService.Setup(x => x.SetActivePowerPlanByGuidAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); powerPlanService.Setup(x => x.GetPowerPlanByGuidAsync(It.IsAny())) .ReturnsAsync((string guid) => new PowerPlanModel { Guid = guid, Name = $"{guid}-name" }); return powerPlanService; } private static Mock CreateNotificationService() { var notificationService = new Mock(MockBehavior.Strict); notificationService.SetupGet(x => x.NotificationHistory).Returns(Array.Empty()); notificationService.Setup(x => x.ShowPowerPlanChangeNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); notificationService.Setup(x => x.ShowErrorNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); notificationService.Setup(x => x.ShowNotificationAsync(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); return notificationService; } private static Mock CreateProcessService() { var processService = new Mock(MockBehavior.Strict); processService.Setup(x => x.UntrackProcess(It.IsAny())); return processService; } private static Mock CreateCoreMaskService() { var coreMaskService = new Mock(MockBehavior.Strict); coreMaskService.SetupGet(x => x.AvailableMasks).Returns(new ObservableCollection()); coreMaskService.Setup(x => x.UnregisterMaskApplication(It.IsAny())); return coreMaskService; } private static Mock CreateAffinityApplyService() { var affinityApplyService = new Mock(MockBehavior.Strict); affinityApplyService .Setup(x => x.ApplyAsync(It.IsAny(), It.IsAny())) .ReturnsAsync((ProcessModel process, long affinity) => AffinityApplyResult.Succeeded(affinity, affinity)); return affinityApplyService; } private static Mock CreateAutoApplyService() { var autoApplyService = new Mock(MockBehavior.Strict); autoApplyService .Setup(x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), It.IsAny())) .ReturnsAsync(Array.Empty()); autoApplyService .Setup(x => x.ApplyForProcessStartAsync( It.IsAny(), It.IsAny())) .ReturnsAsync(Array.Empty()); autoApplyService.Setup(x => x.MarkProcessExited(It.IsAny())); return autoApplyService; } private sealed class FakeProcessMonitorService : IProcessMonitorService { public event EventHandler? ProcessStarted; public event EventHandler? ProcessStopped; public event EventHandler? MonitoringStatusChanged; public void RaiseSnapshotRefreshed() => this.MonitoringStatusChanged?.Invoke( this, new MonitoringStatusEventArgs(true, true, false, snapshotRefreshed: true)); public List RunningProcesses { get; } = new(); public int StartCalls { get; private set; } public int StopCalls { get; private set; } public int DisposeCalls { get; private set; } public bool IsMonitoring { get; private set; } public bool IsWmiAvailable => false; public bool IsFallbackPollingActive => false; public Func? StopMonitoringAsyncImpl { get; init; } public Task StartMonitoringAsync() { this.StartCalls++; this.IsMonitoring = true; return Task.CompletedTask; } public Task StopMonitoringAsync() { this.StopCalls++; this.IsMonitoring = false; return this.StopMonitoringAsyncImpl?.Invoke() ?? Task.CompletedTask; } public Task> GetRunningProcessesAsync() => Task.FromResult>(this.RunningProcesses.ToList()); public Task IsProcessRunningAsync(string executableName) => Task.FromResult(this.RunningProcesses.Any(x => string.Equals(x.Name, executableName, StringComparison.OrdinalIgnoreCase))); public void UpdateSettings() { } public void RaiseProcessStarted(ProcessModel process) => this.ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); public void RaiseProcessStopped(ProcessModel process) => this.ProcessStopped?.Invoke(this, new ProcessEventArgs(process)); public void Dispose() { this.DisposeCalls++; } } private sealed class BlockingSynchronizationContext : SynchronizationContext { public override void Post(SendOrPostCallback d, object? state) { // Intentionally do not pump posted work to emulate a blocked UI thread. } } private sealed class CapturingLogger : ILogger { public List WarningMessages { get; } = new(); public IDisposable? BeginScope(TState state) where TState : notnull => NullScope.Instance; public bool IsEnabled(LogLevel logLevel) => true; public void Log( LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (logLevel == LogLevel.Warning) { this.WarningMessages.Add(formatter(state, exception)); } } private sealed class NullScope : IDisposable { public static readonly NullScope Instance = new(); public void Dispose() { } } } } }