Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions AppDataStorage.Test/NonPublicSetterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.AppDataStorage.Test;

using System.IO.Abstractions.TestingHelpers;
using System.Text.Json.Serialization;

using ktsu.Semantics.Paths;

/// <summary>
/// A public property whose setter is not public is the natural shape for an encapsulated setting, so
/// its stored value has to load back rather than reset to the default.
/// </summary>
[TestClass]
public sealed class NonPublicSetterTests
{
[ClassInitialize]
public static void ClassSetup(TestContext testContext) => AppData.ConfigureForTesting(() => new MockFileSystem());

[TestInitialize]
public void SetupTest() => AppData.ClearCachedFileSystem();

private static AbsoluteDirectoryPath Root(string name) =>
AbsoluteDirectoryPath.Create(OperatingSystem.IsWindows() ? "C:/" : "/") / RelativeDirectoryPath.Create(name);

public sealed class EncapsulatedSettings : AppData<EncapsulatedSettings>
{
public int Volume { get; private set; } = 50;
public string Theme { get; internal set; } = "light";
public int Plain { get; set; } = 1;

[JsonIgnore]
public int Ignored { get; private set; } = 7;

public void Change(int volume, string theme, int ignored)
{
Volume = volume;
Theme = theme;
Ignored = ignored;
}
}

[TestMethod]
public void NonPublicSettersRoundTrip()
{
AbsoluteDirectoryPath root = Root("non_public_setters");
using (EncapsulatedSettings settings = EncapsulatedSettings.LoadOrCreateIn(root))
{
settings.Change(80, "dark", ignored: 9);
settings.Plain = 2;
settings.Save();
}

using EncapsulatedSettings reloaded = EncapsulatedSettings.LoadOrCreateIn(root);
Assert.AreEqual(80, reloaded.Volume, "A private setter should be used when loading.");
Assert.AreEqual("dark", reloaded.Theme, "An internal setter should be used when loading.");
Assert.AreEqual(2, reloaded.Plain, "A public setter should still be used when loading.");
Assert.AreEqual(7, reloaded.Ignored, "A [JsonIgnore] property should still be ignored.");
}

[TestMethod]
public void NextSaveKeepsTheStoredValue()
{
AbsoluteDirectoryPath root = Root("non_public_setters_resave");
using (EncapsulatedSettings settings = EncapsulatedSettings.LoadOrCreateIn(root))
{
settings.Change(80, "dark", ignored: 0);
settings.Save();
}

using (EncapsulatedSettings reloaded = EncapsulatedSettings.LoadOrCreateIn(root))
{
reloaded.Save();
}

using EncapsulatedSettings again = EncapsulatedSettings.LoadOrCreateIn(root);
Assert.AreEqual(80, again.Volume, "Saving a reloaded instance should not erase the stored value.");
}
}
48 changes: 48 additions & 0 deletions AppDataStorage/AppData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

using System.Diagnostics;
using System.IO.Abstractions;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;

using ktsu.CaseConverter;
using ktsu.RoundTripStringJsonConverter;
Expand Down Expand Up @@ -42,13 +44,59 @@
// NaN and the infinities are ordinary settings values ("no limit", "not measured yet").
// Without this they make Save() throw. Finite numbers are still written as JSON numbers.
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers = { UseNonPublicSettersOfAppDataProperties },
},
Converters =
{
new JsonStringEnumConverter(),
new RoundTripStringJsonConverterFactory(),
}
};

/// <summary>
/// Lets deserialization use the non-public setter of a public property on an <see cref="AppData{T}"/> type.
/// </summary>
/// <remarks>
/// System.Text.Json writes a public property whose setter is private, protected or internal, but skips
/// it when reading unless it has <see cref="JsonIncludeAttribute"/>. Nothing fails, so the stored value
/// silently loads back as its default and the next save erases it. <c>{ get; private set; }</c> is the
/// natural shape for an encapsulated setting, so the setter is used instead.
/// </remarks>
/// <param name="typeInfo">The contract being built.</param>
internal static void UseNonPublicSettersOfAppDataProperties(JsonTypeInfo typeInfo)
{
if (typeInfo.Kind != JsonTypeInfoKind.Object || !IsAppDataType(typeInfo.Type))
{
return;
}

foreach (JsonPropertyInfo property in typeInfo.Properties)
{
if (property.Set is null
&& property.AttributeProvider is PropertyInfo clrProperty
&& clrProperty.GetSetMethod(nonPublic: true) is MethodInfo setter
&& !setter.IsPublic)
{
property.Set = (target, value) => setter.Invoke(target, [value]);
}
}
Comment thread
matt-edmondson marked this conversation as resolved.
Resolved
}

private static bool IsAppDataType(Type type)
{
for (Type? current = type.BaseType; current is not null; current = current.BaseType)
{
if (current.IsGenericType && current.GetGenericTypeDefinition() == typeof(AppData<>))
{
return true;
}
}

return false;
}

/// <summary>
/// Thread-local factory for creating file system instances to ensure test isolation.
/// </summary>
Expand Down Expand Up @@ -511,10 +559,10 @@
/// </summary>
#if NET9_0_OR_GREATER
[JsonIgnore]
public static Lock Lock { get; } = new();

Check warning on line 562 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 562 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 562 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 562 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.
#else
[JsonIgnore]
public static object Lock { get; } = new();

Check warning on line 565 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 565 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 565 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 565 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 565 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 565 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.
#endif

internal bool IsSaveQueued()
Expand Down
Loading