Files
PrimeBuild-pc 6506d4a65f perf: Game Boost idles when off and power plan switches spawn fewer powercfg
- The Game Boost timer runs only while Game Boost is on (off by default);
  turning it off still restores everything through ReapplyAsync.
- A foreground process just rejected as not-a-game is not rebuilt into a full
  process model every 3 s; it is looked at again after 30 s or on a settings
  change.
- Switching power plans reads one /list for the previous and target plans and
  reuses it after /setactive: 3 powercfg.exe starts instead of 5 (2 when
  duplicate prevention is off).
2026-10-22 10:54:37 +02:00

295 lines
12 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* ThreadPilot - power plan service unit tests.
*/
namespace ThreadPilot.Core.Tests
{
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using ThreadPilot.Services;
using ThreadPilot.Services.Abstractions;
public sealed class PowerPlanServiceTests
{
[Fact]
public async Task GetActivePowerPlan_ParsesPowerCfgOutput()
{
const string guid = "381b4222-f694-41f0-9685-ff5bb260df2e";
var runner = new RecordingProcessRunner
{
ResultFactory = _ => new ProcessRunResult(
0,
$"Power Scheme GUID: {guid} (Balanced)",
string.Empty),
};
var service = CreateService(runner);
var result = await service.GetActivePowerPlan();
Assert.NotNull(result);
Assert.Equal(guid, result.Guid);
Assert.Equal("Balanced", result.Name);
Assert.True(result.IsActive);
}
[Fact]
public async Task GetActivePowerPlan_PreservesParenthesesInDisplayName()
{
const string guid = "381b4222-f694-41f0-9685-ff5bb260df2e";
var runner = new RecordingProcessRunner
{
ResultFactory = _ => new ProcessRunResult(
0,
$"Power Scheme GUID: {guid} (Ultimate Performance (AMD)) *",
string.Empty),
};
var service = CreateService(runner);
var result = await service.GetActivePowerPlan();
Assert.NotNull(result);
Assert.Equal("Ultimate Performance (AMD)", result.Name);
}
[Fact]
public async Task GetPowerPlansAsync_ParsesActiveMarkerWithOnePowerCfgCall()
{
const string activeGuid = "381b4222-f694-41f0-9685-ff5bb260df2e";
const string otherGuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
var runner = new RecordingProcessRunner
{
ResultFactory = _ => new ProcessRunResult(
0,
$"Power Scheme GUID: {activeGuid} (Balanced) *{Environment.NewLine}" +
$"Power Scheme GUID: {otherGuid} (Ultimate Performance (AMD))",
string.Empty),
};
var service = CreateService(runner);
var plans = await service.GetPowerPlansAsync();
Assert.Equal(2, plans.Count);
Assert.True(plans.Single(plan => plan.Guid == activeGuid).IsActive);
Assert.False(plans.Single(plan => plan.Guid == otherGuid).IsActive);
Assert.Equal("Ultimate Performance (AMD)", plans.Single(plan => plan.Guid == otherGuid).Name);
Assert.Equal(new[] { "/list" }, Assert.Single(runner.Invocations).Arguments);
}
[Fact]
public async Task GetPowerPlansAsync_ParsesLocalizedOutput()
{
const string activeGuid = "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c";
var runner = new RecordingProcessRunner
{
ResultFactory = _ => new ProcessRunResult(
0,
"Modes de gestion de l’alimentation existants (* Actif)\n" +
"GUID du mode de gestion de l’alimentation : 381b4222-f694-41f0-9685-ff5bb260df2e (Utilisation normale)\n" +
$"GUID du mode de gestion de l’alimentation : {activeGuid} (Haute performance) *",
string.Empty),
};
var service = CreateService(runner);
var plans = await service.GetPowerPlansAsync();
Assert.Equal(2, plans.Count);
Assert.Equal("Haute performance", plans.Single(plan => plan.Guid == activeGuid).Name);
Assert.True(plans.Single(plan => plan.Guid == activeGuid).IsActive);
}
[Fact]
public async Task SetActivePowerPlanByGuidAsync_SkipsChange_WhenAlreadyActive()
{
const string guid = "381b4222-f694-41f0-9685-ff5bb260df2e";
var runner = new RecordingProcessRunner
{
ResultFactory = _ => new ProcessRunResult(
0,
$"Power Scheme GUID: {guid} (Balanced)",
string.Empty),
};
var service = CreateService(runner);
var result = await service.SetActivePowerPlanByGuidAsync(guid, preventDuplicateChanges: true);
Assert.True(result);
var invocation = Assert.Single(runner.Invocations);
Assert.Equal(Path.Combine(Environment.SystemDirectory, "powercfg.exe"), invocation.FileName);
Assert.Equal(new[] { "/getactivescheme" }, invocation.Arguments);
}
[Fact]
public async Task SetActivePowerPlanByGuidAsync_SwitchesWithOneListAndOneSetActive()
{
const string balanced = "381b4222-f694-41f0-9685-ff5bb260df2e";
const string ultimate = "e9a42b02-d5df-448d-aa00-03f14749eb61";
var runner = new RecordingProcessRunner
{
ResultFactory = invocation => invocation.Arguments[0] == "/list"
? new ProcessRunResult(
0,
string.Join(
Environment.NewLine,
"Existing Power Schemes (* Active)",
"-----------------------------------",
$"Power Scheme GUID: {balanced} (Balanced) *",
$"Power Scheme GUID: {ultimate} (Ultimate Performance)"),
string.Empty)
: new ProcessRunResult(0, string.Empty, string.Empty),
};
var service = CreateService(runner);
PowerPlanChangedEventArgs? changed = null;
service.PowerPlanChanged += (_, e) => changed = e;
var result = await service.SetActivePowerPlanByGuidAsync(ultimate, preventDuplicateChanges: false);
Assert.True(result);
Assert.Equal(
new[] { new[] { "/list" }, new[] { "/setactive", ultimate } },
runner.Invocations.Select(invocation => invocation.Arguments.ToArray()));
Assert.Equal("Balanced", changed?.PreviousPowerPlan?.Name);
Assert.Equal("Ultimate Performance", changed?.NewPowerPlan?.Name);
}
[Fact]
public async Task DeletePowerPlanAsync_InvokesPowerCfgDelete_WhenPlanIsNotActive()
{
const string activeGuid = "381b4222-f694-41f0-9685-ff5bb260df2e";
const string deleteGuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
var runner = new RecordingProcessRunner
{
ResultFactory = invocation =>
invocation.Arguments.SequenceEqual(new[] { "/getactivescheme" })
? new ProcessRunResult(
0,
$"Power Scheme GUID: {activeGuid} (Balanced)",
string.Empty)
: new ProcessRunResult(0, string.Empty, string.Empty),
};
var service = CreateService(runner);
var result = await service.DeletePowerPlanAsync(deleteGuid);
Assert.True(result);
Assert.Contains(runner.Invocations, invocation =>
invocation.Arguments.SequenceEqual(new[] { "/delete", deleteGuid }));
}
[Fact]
public async Task DeletePowerPlanAsync_DoesNotDeleteActivePlan()
{
const string activeGuid = "381b4222-f694-41f0-9685-ff5bb260df2e";
var runner = new RecordingProcessRunner
{
ResultFactory = _ => new ProcessRunResult(
0,
$"Power Scheme GUID: {activeGuid} (Balanced)",
string.Empty),
};
var service = CreateService(runner);
var result = await service.DeletePowerPlanAsync(activeGuid);
Assert.False(result);
Assert.DoesNotContain(runner.Invocations, invocation =>
invocation.Arguments.Contains("/delete", StringComparer.OrdinalIgnoreCase));
}
[Fact]
public async Task AddCustomPowerPlanFileAsync_RenamesOnCollision()
{
var tempRoot = Path.Combine(Path.GetTempPath(), $"threadpilot-powerplans-{Guid.NewGuid():N}");
var managedDirectory = Path.Combine(tempRoot, "managed");
var sourceDirectory = Path.Combine(tempRoot, "source");
Directory.CreateDirectory(managedDirectory);
Directory.CreateDirectory(sourceDirectory);
var sourcePath = Path.Combine(sourceDirectory, "gaming.pow");
var existingPath = Path.Combine(managedDirectory, "gaming.pow");
await File.WriteAllTextAsync(sourcePath, "source");
await File.WriteAllTextAsync(existingPath, "existing");
try
{
var service = CreateService(
new RecordingProcessRunner(),
powerPlansPathProvider: () => managedDirectory);
var result = await service.AddCustomPowerPlanFileAsync(sourcePath);
Assert.True(result);
var renamedPath = Path.Combine(managedDirectory, "gaming_1.pow");
Assert.True(File.Exists(renamedPath));
Assert.Equal("source", await File.ReadAllTextAsync(renamedPath));
}
finally
{
if (Directory.Exists(tempRoot))
{
Directory.Delete(tempRoot, recursive: true);
}
}
}
[Fact]
public async Task GetCustomPowerPlansAsync_DiscoversBundledPlansRecursively()
{
var tempRoot = Path.Combine(Path.GetTempPath(), $"threadpilot-powerplans-{Guid.NewGuid():N}");
var nestedDirectory = Path.Combine(tempRoot, "nested");
Directory.CreateDirectory(nestedDirectory);
var rootPlanPath = Path.Combine(tempRoot, "root.pow");
var nestedPlanPath = Path.Combine(nestedDirectory, "nested.pow");
await File.WriteAllTextAsync(rootPlanPath, "root");
await File.WriteAllTextAsync(nestedPlanPath, "nested");
try
{
var service = CreateService(
new RecordingProcessRunner(),
powerPlansPathProvider: () => tempRoot);
var result = await service.GetCustomPowerPlansAsync();
Assert.Contains(result, plan => plan.Name == "root" && plan.FilePath == rootPlanPath);
Assert.Contains(result, plan => plan.Name == "nested" && plan.FilePath == nestedPlanPath);
}
finally
{
if (Directory.Exists(tempRoot))
{
Directory.Delete(tempRoot, recursive: true);
}
}
}
private static PowerPlanService CreateService(
IProcessRunner runner,
Func<string>? powerPlansPathProvider = null)
{
var enhancedLogger = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
return new PowerPlanService(
NullLogger<PowerPlanService>.Instance,
enhancedLogger.Object,
runner,
powerPlansPathProvider);
}
private sealed class RecordingProcessRunner : IProcessRunner
{
public List<ProcessInvocation> Invocations { get; } = new();
public Func<ProcessInvocation, ProcessRunResult>? ResultFactory { get; init; }
public Task<ProcessRunResult> RunAsync(string fileName, IReadOnlyList<string> arguments, TimeSpan timeout)
{
var invocation = new ProcessInvocation(fileName, arguments.ToList(), timeout);
this.Invocations.Add(invocation);
return Task.FromResult(this.ResultFactory?.Invoke(invocation) ?? new ProcessRunResult(0, string.Empty, string.Empty));
}
}
private sealed record ProcessInvocation(string FileName, List<string> Arguments, TimeSpan Timeout);
}
}