|
| 1 | +using System.Reflection; |
| 2 | +using System.Runtime.CompilerServices; |
| 3 | +using Microsoft.UI.Reactor; |
| 4 | +using Microsoft.UI.Reactor.Core; |
| 5 | +using Xunit; |
| 6 | + |
| 7 | +namespace Reactor.Tests; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Regression test for issue #264: ensures public record types documented as |
| 11 | +/// "immutable" truly have init-only setters (not plain set). |
| 12 | +/// </summary> |
| 13 | +public class ImmutableRecordContractTests |
| 14 | +{ |
| 15 | + /// <summary> |
| 16 | + /// At the IL level, an <c>init</c> setter is a <c>set</c> method whose |
| 17 | + /// return type carries <c>modreq(IsExternalInit)</c>. This helper detects that. |
| 18 | + /// </summary> |
| 19 | + private static bool IsInitOnly(PropertyInfo property) |
| 20 | + { |
| 21 | + var setter = property.GetSetMethod(nonPublic: true); |
| 22 | + if (setter is null) |
| 23 | + return false; // read-only (no setter at all) — still immutable |
| 24 | + |
| 25 | + var returnParam = setter.ReturnParameter; |
| 26 | + return returnParam.GetRequiredCustomModifiers() |
| 27 | + .Any(t => t.FullName == "System.Runtime.CompilerServices.IsExternalInit"); |
| 28 | + } |
| 29 | + |
| 30 | + public static TheoryData<Type> ImmutableRecordTypes => new() |
| 31 | + { |
| 32 | + { typeof(TrayIconSpec) }, |
| 33 | + { typeof(WindowSpec) }, |
| 34 | + { typeof(Command) }, |
| 35 | + { typeof(Command<>) }, |
| 36 | + }; |
| 37 | + |
| 38 | + [Theory] |
| 39 | + [MemberData(nameof(ImmutableRecordTypes))] |
| 40 | + public void All_Public_Properties_Are_InitOnly(Type type) |
| 41 | + { |
| 42 | + var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) |
| 43 | + .Where(p => p.GetSetMethod(nonPublic: true) is not null); |
| 44 | + |
| 45 | + foreach (var prop in properties) |
| 46 | + { |
| 47 | + Assert.True( |
| 48 | + IsInitOnly(prop), |
| 49 | + $"{type.Name}.{prop.Name} has a plain 'set' accessor — " + |
| 50 | + $"expected 'init' to preserve immutability contract."); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + [Theory] |
| 55 | + [MemberData(nameof(ImmutableRecordTypes))] |
| 56 | + public void Has_At_Least_One_Public_Property(Type type) |
| 57 | + { |
| 58 | + // Sanity check: ensure the test is actually verifying something. |
| 59 | + var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); |
| 60 | + Assert.NotEmpty(props); |
| 61 | + } |
| 62 | +} |
0 commit comments