acdream/tests/AcDream.Core.Tests/CharGen/ChargenNoChoriziteLeakTests.cs
Erik cb4703e8d5 fix(chargen): CC1 review fix round — Custom is template 0, SkillTable cost fallback, frozen model
Implements all six Opus review findings against 04450041 (Campaign CC
CC1 chargen data layer):

- F1 (HIGH, blocking): ChargenTemplate's doc claimed "Custom" has no
  ChargenTemplate entry and cited two nonexistent addresses. Verified
  against the named retail decomp: gmCGProfessionPage::UpdateProfession
  @ 0x004821b0 resolves BOTH the highlighted button and the description
  string from CharGenState.template_ 0..6, and case 0 is button
  0x100003d9 / ID_CharGen_CustomText. Custom IS template index 0 (the
  "Adventurer" row CC1 already found sitting at the attribute floor).
  CharGenState::SetTemplate @ 0x005C5A60 confirms every button (including
  Custom) calls CharGenState::ApplyTemplate @ 0x005C5080 when committing,
  so selecting Custom resets the sliders/skills to that row rather than
  leaving them untouched.

- F2 (MEDIUM): retail's skill-cost lookup is two-tiered
  (ACCharGenData::GetSkillTrainedCost/GetSkillSpecializedCost @
  0x005C26D0/0x005C27D0 fall through to the global SkillTable,
  portal.dat 0x0E000004, on a heritage-list miss — confirmed against
  ACE's identical PlayerFactory.cs precedence). ChargenTableReader now
  also projects the global SkillTable into
  ChargenOptions.GlobalSkillCostsBySkillId, and
  ChargenSkillCreditMath.ComputeSpent/RemainingCredits check the
  heritage list first and the global list on a miss. Added an
  installed-DAT completeness assertion recording reality: the global
  table prices 38/54 advancement skill ids, every one of the 13
  installed heritages ships exactly one heritage-specific override
  (always also priced globally), and 16 ids are genuinely uncostable in
  both tiers. Also filed a CC7 risk-item note: ACE's own heritage-
  override branch over-deducts on Specialize (PlayerFactory.cs:184-211)
  — a retail-legal build may be rejected by local ACE at the CC7
  connected gate; that is an ACE bug, not an acdream defect.

- F3 (MEDIUM): every collection ChargenTableReader hands into the
  record model is now frozen at projection (ToFrozenDictionary/ToArray,
  matching MagicCatalog's house pattern), including both
  ChargenOptions.Empty dictionaries.

- F4 (LOW): added a reflection guard test
  (ChargenNoChoriziteLeakTests) that walks every public
  AcDream.Core.CharGen member (property/indexer/constructor/method
  types, recursively through generic arguments) and fails if any
  resolves to the DatReaderWriter or a Chorizite* assembly.

- F5 (LOW): ChargenGenderOptions.HasAnyAppearanceOptions's doc now
  states precisely what the installed-DAT gate proves (an OR across
  eight lists, for at least one gender per heritage) rather than the
  stronger claim it previously made, and explicitly calls out the three
  omitted color lists. Added a second installed-DAT gate that records
  per-list reality across every gender of every heritage — found
  complete, no empty lists anywhere in the installed DAT today.

- F6 (LOW): ChargenOptions.TryGetHeritage/TryGetStarterArea now use
  [MaybeNullWhen(false)] instead of null! suppression, matching the
  house pattern already used elsewhere in the test suite. Fixed every
  call site this surfaced (more than the five originally estimated,
  since Content.Tests has TreatWarningsAsErrors).

Core.Tests: 4737 passed / 1 skip (pre-existing, unrelated).
Content.Tests: 145 passed / 0 skip.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 13:33:37 +02:00

150 lines
5.8 KiB
C#

using System.Reflection;
using AcDream.Core.CharGen;
namespace AcDream.Core.Tests.CharGen;
/// <summary>
/// Pins the CC1 no-leak contract with a real assertion rather than a doc
/// comment. AcDream.Core references Chorizite.DatReaderWriter (for
/// <c>TextureHelpers</c>), so "no Chorizite type on any public CharGen
/// member" was convention only until this guard exists — nothing stopped a
/// future edit from putting e.g. a <c>DatReaderWriter.Enums.SkillId</c>
/// directly on a public property. This test walks every public type in the
/// <c>AcDream.Core.CharGen</c> namespace and asserts that no public
/// property, indexer, constructor parameter, or method return/parameter
/// type — nor any of their generic type arguments, recursively — comes
/// from the <c>DatReaderWriter</c> assembly or any assembly whose name
/// starts with <c>Chorizite</c>.
/// </summary>
public sealed class ChargenNoChoriziteLeakTests
{
[Fact]
public void PublicCharGenSurface_NeverExposesChoriziteOrDatReaderWriterTypes()
{
Assembly coreAssembly = typeof(ChargenOptions).Assembly;
Type[] publicCharGenTypes = coreAssembly.GetTypes()
.Where(t => t.IsPublic && t.Namespace == "AcDream.Core.CharGen")
.ToArray();
// Guards the guard: if the namespace ever ends up empty (e.g. a
// rename), this test must fail loudly rather than vacuously pass.
Assert.True(
publicCharGenTypes.Length > 5,
$"Expected multiple public types in AcDream.Core.CharGen, found {publicCharGenTypes.Length}. " +
"Did the namespace get renamed or moved?");
var offenders = new List<string>();
foreach (Type type in publicCharGenTypes)
{
foreach (PropertyInfo property in type.GetProperties(
BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
{
CheckSite(property.PropertyType, $"{type.FullName}.{property.Name} (property)", offenders);
foreach (ParameterInfo indexParam in property.GetIndexParameters())
{
CheckSite(
indexParam.ParameterType,
$"{type.FullName}.{property.Name}[{indexParam.Name}] (indexer parameter)",
offenders);
}
}
foreach (ConstructorInfo ctor in type.GetConstructors(
BindingFlags.Public | BindingFlags.Instance))
{
foreach (ParameterInfo param in ctor.GetParameters())
{
CheckSite(
param.ParameterType,
$"{type.FullName}..ctor({param.Name}) (constructor parameter)",
offenders);
}
}
foreach (MethodInfo method in type.GetMethods(
BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
{
// Property accessors, operators, and other compiler-emitted
// members are IsSpecialName; the property/indexer loop above
// already covers accessor types directly.
if (method.IsSpecialName)
continue;
CheckSite(method.ReturnType, $"{type.FullName}.{method.Name} (return type)", offenders);
foreach (ParameterInfo param in method.GetParameters())
{
CheckSite(
param.ParameterType,
$"{type.FullName}.{method.Name}({param.Name}) (method parameter)",
offenders);
}
}
}
Assert.True(
offenders.Count == 0,
"A Chorizite/DatReaderWriter type leaked onto a public AcDream.Core.CharGen member:\n"
+ string.Join('\n', offenders));
}
private static void CheckSite(Type type, string site, List<string> offenders)
{
foreach (Type candidate in FlattenTypeArguments(type))
{
string? assemblyName = candidate.Assembly.GetName().Name;
if (assemblyName is null)
continue;
bool isForbidden =
assemblyName.Equals("DatReaderWriter", StringComparison.OrdinalIgnoreCase)
|| assemblyName.StartsWith("Chorizite", StringComparison.OrdinalIgnoreCase);
if (isForbidden)
offenders.Add($"{site}: {candidate.FullName} (assembly '{assemblyName}')");
}
}
/// <summary>Yields <paramref name="type"/> itself plus every generic
/// type argument, array element type, and by-ref (out/ref parameter)
/// element type, recursively — so e.g. <c>out IReadOnlyDictionary
/// &lt;uint, ChargenSkillCost&gt;</c> is checked against
/// <c>ChargenSkillCost</c>, not just the outer dictionary type.</summary>
private static IEnumerable<Type> FlattenTypeArguments(Type type)
{
yield return type;
if (type.IsByRef || type.IsPointer)
{
Type? element = type.GetElementType();
if (element is not null)
{
foreach (Type inner in FlattenTypeArguments(element))
yield return inner;
}
yield break;
}
if (type.IsArray)
{
Type? element = type.GetElementType();
if (element is not null)
{
foreach (Type inner in FlattenTypeArguments(element))
yield return inner;
}
yield break;
}
if (type.IsGenericType)
{
foreach (Type argument in type.GetGenericArguments())
{
foreach (Type inner in FlattenTypeArguments(argument))
yield return inner;
}
}
}
}