Files
ThreadPilot/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs
Prime Build 9a4baba19a feat: release 1.7.7 stable without experimental Game Boost
* feat: back up persistent rules and resolve rule precedence deterministically

- Configuration export now includes persistent process rules (schema 3.0),
  stays compatible with 2.0 bundles, validates before writing, previews
  what an import replaces and rolls back on failure.
- Matching rules apply broad-to-specific (name, wildcard path, exact path,
  then most recently edited), shared by the engine and the process summary,
  which now lists the apply order and flags conflicting values.
- Localized the new strings in all seven languages.

* feat: clearer process and rule editors

- Process details: CPU, memory and I/O priority pickers with an explicit
  Apply, undo of the last manual priority change (guarded against reused
  PIDs), adaptive side/bottom details panel.
- Manual process control stays available while automation is paused, with
  a persistent notice instead of an overlay.
- Saved-rule editor stages all edits (including the core mask) and saves
  them together, showing pending changes.
- Localized the new strings in all seven languages.

* fix: one save path for a saved rule's cores

The rules editor's core mask went through a new update path that reported
success without saving when no affinity payload was built, and kept a
legacy mask next to a CPU selection. Merge it with the old single-purpose
method (now unused), keep its checks, and localize the undo message.

* feat: per-process efficiency mode (EcoQoS) for live processes and rules

Closes #66.

- Native: SetProcessInformation/GetProcessInformation with
  ProcessPowerThrottling (EXECUTION_SPEED), three states: Windows decides,
  On (EcoQoS), Off (never throttle / HighQoS).
- Process tab: context menu entries, a picker with Apply in the details
  panel, current state in the summary, undo of the last change, included
  when saving current settings as a rule (only if explicitly set).
- Rules: EfficiencyMode + ApplyEfficiencyModeOnStart, applied by the rules
  engine, editable in the saved-rule editor, validated on import and part
  of conflict detection.
- The summary flags when the global Power Throttling tweak voids it. CPU
  priority is left alone, unlike Task Manager's efficiency mode.
- Localized in all seven languages.

* chore: keep CRLF line endings in SelectedProcessSummaryViewModel

* feat: clearer navigation, process page and rules editor

- Navigation pane open with short labels instead of seven bare icons.
- Processes: one toolbar row (search with placeholder, Filters and
  Columns menus, sort, refresh); details split into Process, Priority,
  CPU cores and Rule cards; pickers start from the process's current
  values and stay empty when a value cannot be read; help paragraphs
  moved into tooltips; core picker always visible.
- Rules: process rules first, clearer tab names, localized choices in the
  saved-rule editor instead of internal enum names.
- Shorter page titles and subtitles in all seven languages; removed the
  strings this made unused.

No data format changes.

* feat: settings and tweaks as Windows 11 rows, localized rule list

- Settings: one column of rows (what it is on the left, its switch on the
  right), most used sections first, Save as the primary action.
- Tweaks: one tweak per row with its status dot and switch.
- Rule list: 'Applies' and 'Mode' columns use the same localized labels as
  the editor and refresh on language change.
- Removed 76 strings no code referenced, from all seven languages.

* fix: issues found testing the beta in a clean Windows 11 VM

- Process counter could show more visible processes than the total
  ('157 / 151'): the batch total was a snapshot from the first load.
- Narrow windows (or 150% scaling): toolbar buttons move under the search
  box instead of squeezing it to a few letters.
- Rules list keeps the 'Applies' column readable when narrow.
- Settings status message gets its own line instead of being cut.

Tested in a Hyper-V Windows 11 VM: clean install, upgrade, uninstall,
light and dark theme, 100% and 150% scaling.

* feat: remember layout choices; Windows 11 toggles in Tweaks

- The navigation pane, window size/position/maximized state, and the
  process list filters, sort and columns now survive a restart. They live
  in ui-state.json, apart from settings.json, so they never mark the
  Settings page as unsaved or travel in exported configurations. A corrupt
  file falls back to defaults; tests write to a temp file.
- Fixes the pane re-opening on every start (it was hard-coded open).
- Tweaks use a native-looking Windows 11 switch (40x20 track, sliding
  thumb) with On/Off written beside it.
- New test: every on/off setting survives save and reload.

* docs: handoff for the 1.7.7 PR stack and beta test

* fix: P/E cores from the highest EfficiencyClass, AMD CCDs from real L3 groups

The legacy topology treated the lowest EfficiencyClass as the performance
core, swapping P- and E-cores on hybrid Intel CPUs. AMD CCDs were guessed
as 8 cores each, which split 6+6 parts (7900X3D, 9900X3D) into 8+4; they now
come from the L3 groups Windows reports, with the guess kept only as a
fallback. The topology snapshot also keeps each L3 group's size.

* feat: Game Boost, CPU Sets for the game and selected background apps

While a detected game runs, Game Boost sets process default CPU Sets from
the CPU topology: on AMD X3D with one larger L3 the game goes to the V-Cache
CCD, on Intel hybrid CPUs to the P-cores, and selected background apps
(browsers, sync clients, updaters, launchers) to the other cores. On dual-CCD
parts with equal L3 only the background moves, unless Isolation mode also
keeps the game on CCD0. Single-L3 and unreadable topologies are left to
Windows. Above Normal priority for the game is optional; never High.

Each change is written to a journal before it is made and undone when the
game exits, Game Boost is turned off or ThreadPilot closes, and on the next
start after a crash. Only values still exactly as Game Boost set them are
restored, never one a user rule or a manual change has taken over since.
Persistent rules and Game Boost share one apply gate, and a rule always
wins over Game Boost for the setting it covers.

The switch, mode and lists are on the Tweaks page, off by default, and take
effect without a restart.

* fix: Game Boost background entries with a full path never matched

The background list compared full-path entries against an empty path, so
only bare process names worked. Found by a new integration test that runs
the real services on two copies of PING.EXE: CPU Sets and priority are set
and read back through Windows, removed when Game Boost is turned off, and
undone from the journal after a simulated crash. The topology is simulated
from this machine's CPU Set IDs, so the test also runs on CPUs where Game
Boost would not act; it skips itself below 8 cores.

* feat: report Game Boost sessions and restore results in Activity

* test: diagnose EcoQoS read failures on Windows Server

* chore: prepare 1.7.7-beta.2 and keep prereleases out of stable channels

* test: use native full-query access mask in EcoQoS diagnostic

* docs: update beta handoff and prerelease publication policy

* ci: run native EcoQoS tests on a Windows 11-era kernel

Windows Server 2022 build 20348 rejects GetProcessInformation(ProcessPowerThrottling) with ERROR_INVALID_PARAMETER (87), with both limited and full query handles. Windows 11 local tests pass. Use Server 2025 for CI/release tests and smoke testing; keep the real round-trip assertions, remove temporary probes.

* test: lock beta publication and native runner contracts

* chore: separate stable 1.7.7 from experimental Game Boost

Stable retains the validated EcoQoS/rules/UI stack. Preserve the complete local Game Boost implementation at ef2ec24 for the separate 1.7.8-beta.1 prerelease; no experimental Game Boost/topology changes ship in stable. Keep channel-aware publication and Windows 11-era native CI tests.
2026-10-16 12:03:54 +02:00

549 lines
22 KiB
C#

namespace ThreadPilot.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using ThreadPilot.Models;
using ThreadPilot.Services;
using ThreadPilot.Services.Abstractions;
public sealed class ApplicationSettingsServiceTests
{
[Fact]
public async Task LoadSettingsAsync_CreatesDefaults_WhenFileIsMissing()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.True(storage.Writes.ContainsKey(TestPaths.SettingsFilePath));
Assert.Equal(3000, service.Settings.NotificationDisplayDurationMs);
Assert.Equal(5000, service.Settings.BalloonNotificationTimeoutMs);
Assert.True(service.Settings.EnableSelfLowImpactMode);
Assert.False(service.Settings.EnableSelfAffinityLimit);
Assert.True(service.Settings.AutostartWithWindows);
Assert.False(service.Settings.StartMinimized);
Assert.Equal("en-US", service.Settings.Language);
}
[Fact]
public async Task LoadSettingsAsync_DefaultsAutomationMonitoringEnabled_ForOlderSettingsJson()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = "{}";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.True(service.Settings.EnableAutomationMonitoring);
Assert.Equal(CpuAssignmentMode.AffinityMask, service.Settings.DefaultCpuAssignmentMode);
}
[Fact]
public async Task LoadSettingsAsync_PersistsCompletionForANonAutomaticProfile()
{
// Without this the policy re-runs on every launch, and a later deliberate switch back
// to Automatic would be silently undone by a second migration.
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] =
"{\"defaultCpuAssignmentMode\": 3, \"language\": \"en-US\"}";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.CpuSets, service.Settings.DefaultCpuAssignmentMode);
Assert.True(service.Settings.HasMigratedCpuAssignmentModeDefault);
Assert.True(service.Settings.HasSeenCpuAssignmentModeChangeNotice);
Assert.True(storage.Writes.ContainsKey(TestPaths.SettingsFilePath));
var reloaded = CreateService(storage);
await reloaded.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.CpuSets, reloaded.Settings.DefaultCpuAssignmentMode);
Assert.True(reloaded.Settings.HasMigratedCpuAssignmentModeDefault);
}
[Fact]
public async Task LoadSettingsAsync_RepairsACorruptModeWithoutAnnouncingAChange()
{
// A value out of the enum range is not a choice the user made, so telling them their
// Automatic setting was changed would be a lie.
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] =
"{\"defaultCpuAssignmentMode\": 99, \"language\": \"en-US\"}";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.AffinityMask, service.Settings.DefaultCpuAssignmentMode);
Assert.True(service.Settings.HasSeenCpuAssignmentModeChangeNotice);
}
[Fact]
public async Task LoadSettingsAsync_KeepsTheMigratedProfileWhenPersistingItFails()
{
// Falling into the outer catch would replace everything the user configured with
// defaults and mark the notice seen, hiding the change entirely.
var storage = new FakeSettingsStorage { FailWrites = true };
storage.Files[TestPaths.SettingsFilePath] =
"{\"defaultCpuAssignmentMode\": 0, \"maxNotificationHistoryItems\": 42, \"language\": \"en-US\"}";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.AffinityMask, service.Settings.DefaultCpuAssignmentMode);
Assert.Equal(42, service.Settings.MaxNotificationHistoryItems);
Assert.False(service.Settings.HasSeenCpuAssignmentModeChangeNotice);
}
[Fact]
public async Task LoadSettingsAsync_MigratesAnUpgradedProfileOffAutomaticAndPersistsIt()
{
// A profile written by 1.7.0 or earlier: Automatic was the shipped default then, and the
// persisted value kept winning over the new one after the 1.7.1 upgrade.
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] =
"{\"defaultCpuAssignmentMode\": 0, \"language\": \"en-US\"}";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.AffinityMask, service.Settings.DefaultCpuAssignmentMode);
Assert.True(service.Settings.HasMigratedCpuAssignmentModeDefault);
Assert.False(service.Settings.HasSeenCpuAssignmentModeChangeNotice);
// Must be written back, or the migration would run again on every launch.
Assert.True(storage.Writes.ContainsKey(TestPaths.SettingsFilePath));
var reloaded = CreateService(storage);
await reloaded.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.AffinityMask, reloaded.Settings.DefaultCpuAssignmentMode);
Assert.True(reloaded.Settings.HasMigratedCpuAssignmentModeDefault);
Assert.False(reloaded.Settings.HasSeenCpuAssignmentModeChangeNotice);
}
[Fact]
public async Task LoadSettingsAsync_DoesNotAnnounceAnythingToAFreshProfile()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.AffinityMask, service.Settings.DefaultCpuAssignmentMode);
Assert.True(service.Settings.HasMigratedCpuAssignmentModeDefault);
Assert.True(service.Settings.HasSeenCpuAssignmentModeChangeNotice);
}
[Fact]
public async Task LoadSettingsAsync_KeepsAutomaticChosenAfterTheMigration()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] =
"{\"defaultCpuAssignmentMode\": 0, \"hasMigratedCpuAssignmentModeDefault\": true, " +
"\"hasSeenCpuAssignmentModeChangeNotice\": true, \"language\": \"en-US\"}";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.Automatic, service.Settings.DefaultCpuAssignmentMode);
}
[Fact]
public async Task UpdateSettingsAsync_RoundTripsDefaultCpuAssignmentMode()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage);
await service.LoadSettingsAsync();
var settings = service.Settings;
settings.DefaultCpuAssignmentMode = CpuAssignmentMode.CpuSets;
await service.UpdateSettingsAsync(settings);
var reloaded = CreateService(storage);
await reloaded.LoadSettingsAsync();
Assert.Equal(CpuAssignmentMode.CpuSets, reloaded.Settings.DefaultCpuAssignmentMode);
}
[Fact]
public async Task UpdateSettingsAsync_EveryOptionSurvivesARestart()
{
// Flip every on/off option, save, and read it back with a fresh service: nothing may silently
// fall back to its default. Migration markers are excluded because loading rewrites them on purpose.
var storage = new FakeSettingsStorage();
var service = CreateService(storage);
await service.LoadSettingsAsync();
var settings = service.Settings;
var flags = typeof(ApplicationSettingsModel).GetProperties()
.Where(property => property.PropertyType == typeof(bool) && property.CanWrite &&
!property.Name.StartsWith("HasMigrated", StringComparison.Ordinal))
.ToList();
var expected = flags.ToDictionary(property => property.Name, property => !(bool)property.GetValue(settings)!);
foreach (var property in flags)
{
property.SetValue(settings, expected[property.Name]);
}
settings.Language = "de-DE";
await service.UpdateSettingsAsync(settings);
var reloaded = CreateService(storage);
await reloaded.LoadSettingsAsync();
var lost = flags.Where(property => (bool)property.GetValue(reloaded.Settings)! != expected[property.Name])
.Select(property => property.Name)
.ToList();
Assert.Empty(lost);
Assert.Equal("de-DE", reloaded.Settings.Language);
}
[Fact]
public async Task UpdateSettingsAsync_PersistsAutomationMonitoringDisabled()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage);
await service.LoadSettingsAsync();
var settings = service.Settings;
settings.EnableAutomationMonitoring = false;
await service.UpdateSettingsAsync(settings);
var reloaded = CreateService(storage);
await reloaded.LoadSettingsAsync();
Assert.False(reloaded.Settings.EnableAutomationMonitoring);
}
[Fact]
public async Task LoadSettingsAsync_UsesAndPersistsWindowsLanguage_WhenFileIsMissing()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage, "it-CH");
await service.LoadSettingsAsync();
Assert.Equal("it-IT", service.Settings.Language);
Assert.Contains("\"language\": \"it-IT\"", storage.Writes[TestPaths.SettingsFilePath], StringComparison.Ordinal);
}
[Fact]
public async Task LoadSettingsAsync_FallsBackToDefaults_WhenJsonIsMalformed()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = "{ invalid json";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.Equal(3000, service.Settings.NotificationDisplayDurationMs);
Assert.Equal(string.Empty, service.Settings.CustomTrayIconPath);
Assert.True(service.Settings.EnableSelfLowImpactMode);
Assert.False(service.Settings.EnableSelfAffinityLimit);
}
[Fact]
public async Task LoadSettingsAsync_EnablesSafeSelfLowImpactDefault_ForOlderSettingsJson()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"notificationDisplayDurationMs": 3000,
"balloonNotificationTimeoutMs": 5000
}
""";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.True(service.Settings.EnableSelfLowImpactMode);
Assert.False(service.Settings.EnableSelfAffinityLimit);
}
[Fact]
public async Task LoadSettingsAsync_PreservesExplicitSelfLowImpactOptOut()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"enableSelfLowImpactMode": false,
"enableSelfAffinityLimit": true
}
""";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.False(service.Settings.EnableSelfLowImpactMode);
Assert.True(service.Settings.EnableSelfAffinityLimit);
}
[Fact]
public async Task LoadSettingsAsync_DefaultsStartMinimizedFalse_ForOlderAutostartSettingsJson()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"autostartWithWindows": true
}
""";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.True(service.Settings.AutostartWithWindows);
Assert.False(service.Settings.StartMinimized);
}
[Fact]
public async Task LoadSettingsAsync_PreservesExplicitStartMinimizedOptOut()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"autostartWithWindows": true,
"startMinimized": false
}
""";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.True(service.Settings.AutostartWithWindows);
Assert.False(service.Settings.StartMinimized);
}
[Fact]
public async Task LoadSettingsAsync_PreservesExplicitStartMinimizedOptIn()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"autostartWithWindows": true,
"startMinimized": true
}
""";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.True(service.Settings.AutostartWithWindows);
Assert.True(service.Settings.StartMinimized);
}
[Fact]
public async Task LoadSettingsAsync_PreservesStartupMinimizedSuggestionDismissal()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"hasSeenStartupMinimizedSuggestion": true
}
""";
var service = CreateService(storage);
await service.LoadSettingsAsync();
Assert.True(service.Settings.HasSeenStartupMinimizedSuggestion);
}
[Theory]
[InlineData("en-US")]
[InlineData("zh-CN")]
[InlineData("it-IT")]
[InlineData("fr-FR")]
[InlineData("de-DE")]
[InlineData("es-ES")]
[InlineData("ru-RU")]
public async Task LoadSettingsAsync_PreservesSupportedLanguage(string language)
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = $$"""
{
"language": "{{language}}"
}
""";
var service = CreateService(storage, "it-IT");
await service.LoadSettingsAsync();
Assert.Equal(language, service.Settings.Language);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("pt-BR")]
[InlineData("zh")]
public async Task LoadSettingsAsync_UsesAndPersistsWindowsLanguage_WhenLanguageIsInvalid(string language)
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = $$"""
{
"language": "{{language}}"
}
""";
var service = CreateService(storage, "ru-KZ");
await service.LoadSettingsAsync();
Assert.Equal("ru-RU", service.Settings.Language);
Assert.Contains("\"language\": \"ru-RU\"", storage.Writes[TestPaths.SettingsFilePath], StringComparison.Ordinal);
}
[Fact]
public async Task LoadSettingsAsync_UsesWindowsLanguage_WhenLanguagePropertyIsMissing()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"startMinimized": true
}
""";
var service = CreateService(storage, "fr-CA");
await service.LoadSettingsAsync();
Assert.Equal("fr-FR", service.Settings.Language);
Assert.Contains("\"language\": \"fr-FR\"", storage.Writes[TestPaths.SettingsFilePath], StringComparison.Ordinal);
}
[Fact]
public async Task LoadSettingsAsync_NormalizesAndPersistsSupportedLanguageCasing()
{
var storage = new FakeSettingsStorage();
storage.Files[TestPaths.SettingsFilePath] = """
{
"language": "IT-it"
}
""";
var service = CreateService(storage, "ru-RU");
await service.LoadSettingsAsync();
Assert.Equal("it-IT", service.Settings.Language);
Assert.Contains("\"language\": \"it-IT\"", storage.Writes[TestPaths.SettingsFilePath], StringComparison.Ordinal);
}
[Fact]
public async Task ResetToDefaultsAsync_UsesWindowsLanguage()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage, "de-AT");
await service.ResetToDefaultsAsync();
Assert.Equal("de-DE", service.Settings.Language);
}
[Fact]
public async Task ImportSettingsAsync_UsesWindowsLanguage_WhenLanguageIsInvalid()
{
const string ImportPath = "import-settings.json";
var storage = new FakeSettingsStorage();
storage.Files[ImportPath] = """
{
"language": "unsupported"
}
""";
var service = CreateService(storage, "es-MX");
await service.ImportSettingsAsync(ImportPath);
Assert.Equal("es-ES", service.Settings.Language);
}
[Fact]
public async Task ImportSettingsAsync_Throws_WhenFileIsMissing()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage);
await Assert.ThrowsAsync<FileNotFoundException>(() => service.ImportSettingsAsync("missing-settings.json"));
}
[Fact]
public async Task ValidateAndFixSettings_DisablesMissingCustomTrayIcon()
{
var storage = new FakeSettingsStorage();
var service = CreateService(storage);
var updatedSettings = new ApplicationSettingsModel
{
UseCustomTrayIcon = true,
CustomTrayIconPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.ico"),
};
await service.UpdateSettingsAsync(updatedSettings);
Assert.False(service.Settings.UseCustomTrayIcon);
}
private static ApplicationSettingsService CreateService(
FakeSettingsStorage storage,
string systemUiCultureName = "en-US")
{
return new ApplicationSettingsService(
NullLogger<ApplicationSettingsService>.Instance,
storage,
TestPaths.SettingsFilePath,
legacySettingsPath: null,
() => new CultureInfo(systemUiCultureName));
}
private static class TestPaths
{
public const string SettingsFilePath = "settings-under-test.json";
}
private sealed class FakeSettingsStorage : ISettingsStorage
{
public Dictionary<string, string> Files { get; } = new(StringComparer.OrdinalIgnoreCase);
public Dictionary<string, string> Writes { get; } = new(StringComparer.OrdinalIgnoreCase);
public void Copy(string sourcePath, string destinationPath, bool overwrite)
{
if (!this.Files.TryGetValue(sourcePath, out var content))
{
throw new FileNotFoundException("Source file not found.", sourcePath);
}
if (!overwrite && this.Files.ContainsKey(destinationPath))
{
throw new IOException("Destination already exists.");
}
this.Files[destinationPath] = content;
}
public void EnsureDirectoryForFile(string path)
{
}
public bool Exists(string path)
{
return this.Files.ContainsKey(path);
}
public Task<string?> ReadAsync(string path)
{
this.Files.TryGetValue(path, out var content);
return Task.FromResult<string?>(content);
}
public bool FailWrites { get; init; }
public Task WriteAsync(string path, string content)
{
if (this.FailWrites)
{
throw new IOException("Simulated write failure.");
}
this.Files[path] = content;
this.Writes[path] = content;
return Task.CompletedTask;
}
}
}
}