Files
linuxdistro-roguelite/Assets/Tests/EditMode/ReadabilityTests.cs
T
2026-11-18 19:42:44 +01:00

295 lines
15 KiB
C#

using System;
using System.Collections;
using System.Reflection;
using KernelPanic.UI;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;
public class ReadabilityTests
{
private string _testKey;
private bool _motion;
private UITextSize _size;
private UILayoutDensity _density;
private int _soundVolume;
private const BindingFlags InternalStatic = BindingFlags.NonPublic | BindingFlags.Static;
[SetUp]
public void SetUp()
{
_testKey = "KernelPanic.UI.Tests." + Guid.NewGuid().ToString("N");
_motion = UIPreferences.ReducedMotion;
_size = UIPreferences.TextSize;
_density = UIPreferences.Density;
_soundVolume = UIPreferences.SoundVolume;
}
[TearDown]
public void TearDown()
{
UIPreferences.ReducedMotion = _motion;
UIPreferences.TextSize = _size;
UIPreferences.Density = _density;
UIPreferences.SoundVolume = _soundVolume;
PlayerPrefs.DeleteKey(_testKey);
}
[TestCase(false, UITextSize.Standard, UILayoutDensity.Compact)]
[TestCase(true, UITextSize.Large, UILayoutDensity.Compact)]
[TestCase(false, UITextSize.Standard, UILayoutDensity.Comfortable)]
[TestCase(true, UITextSize.Large, UILayoutDensity.Comfortable)]
public void PreferencesRoundTripWithoutChangingTheProgressionSaveOrPersistingTemporaryOverrides(
bool motion, UITextSize size, UILayoutDensity density)
{
string productionKey = (string)typeof(UIPreferences).GetField("StorageKey", InternalStatic).GetRawConstantValue();
string productionBefore = PlayerPrefs.GetString(productionKey, "<absent>");
UIPreferences.ReducedMotion = motion;
UIPreferences.TextSize = size;
UIPreferences.Density = density;
InvokeStore("SaveToKey");
string stored = PlayerPrefs.GetString(_testKey);
UIPreferences.ReducedMotion = !motion;
UIPreferences.TextSize = size == UITextSize.Standard ? UITextSize.Large : UITextSize.Standard;
UIPreferences.Density = density == UILayoutDensity.Compact ? UILayoutDensity.Comfortable : UILayoutDensity.Compact;
Assert.That(PlayerPrefs.GetString(_testKey), Is.EqualTo(stored), "Transient overrides must not write preferences.");
InvokeStore("LoadFromKey");
Assert.That(UIPreferences.ReducedMotion, Is.EqualTo(motion));
Assert.That(UIPreferences.TextSize, Is.EqualTo(size));
Assert.That(UIPreferences.Density, Is.EqualTo(density));
Assert.That(PlayerPrefs.GetString(productionKey, "<absent>"), Is.EqualTo(productionBefore), "Fixtures never save to the player's preference key.");
}
[TestCase(null)]
[TestCase("not-json")]
[TestCase("{\"version\":99,\"reducedMotion\":true,\"textSize\":1,\"density\":1}")]
[TestCase("{\"version\":1,\"textSize\":38,\"density\":-7}")]
public void ExistingPlayersAndUnknownPreferenceValuesUseReadableDefaults(string json)
{
if (json != null) PlayerPrefs.SetString(_testKey, json);
UIPreferences.ReducedMotion = true;
UIPreferences.TextSize = UITextSize.Large;
UIPreferences.Density = UILayoutDensity.Comfortable;
InvokeStore("LoadFromKey");
Assert.That(UIPreferences.ReducedMotion, Is.False);
Assert.That(UIPreferences.TextSize, Is.EqualTo(UITextSize.Standard));
Assert.That(UIPreferences.Density, Is.EqualTo(UILayoutDensity.Compact));
Assert.That(PlayerPrefs.GetString(_testKey, "<absent>"), Is.EqualTo(json ?? "<absent>"), "Loading must not rewrite old or unknown preferences.");
}
[TestCase(0)]
[TestCase(25)]
[TestCase(100)]
public void SoundVolumeRoundTripsAndMuteIsPreserved(int volume)
{
UIPreferences.SoundVolume = volume;
InvokeStore("SaveToKey");
UIPreferences.SoundVolume = 75;
InvokeStore("LoadFromKey");
Assert.That(UIPreferences.SoundVolume, Is.EqualTo(volume));
UIPreferences.SoundVolume = -1;
Assert.That(UIPreferences.SoundVolume, Is.Zero);
UIPreferences.SoundVolume = 999;
Assert.That(UIPreferences.SoundVolume, Is.EqualTo(100));
}
[UnityTest]
public IEnumerator PreferencesUpdateEveryAttachedRootAndDetachSubscriptionsAreReleased()
{
RequireGraphics();
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
try
{
window.Show();
var first = new VisualElement();
var second = new VisualElement();
window.rootVisualElement.Add(first);
window.rootVisualElement.Add(second);
UIPreferences.ReducedMotion = false;
UIPreferences.TextSize = UITextSize.Standard;
UIPreferences.Density = UILayoutDensity.Compact;
Attach(first);
Attach(second);
Attach(first); // Repeated screen binding must not add duplicate subscriptions or sheets.
UIPreferences.ReducedMotion = true;
UIPreferences.TextSize = UITextSize.Large;
UIPreferences.Density = UILayoutDensity.Comfortable;
yield return null;
foreach (var root in new[] { first, second })
{
Assert.That(root.ClassListContains("reduced-motion"), Is.True);
Assert.That(root.ClassListContains("text-large"), Is.True);
Assert.That(root.ClassListContains("density-comfortable"), Is.True);
Assert.That(root.styleSheets.count, Is.EqualTo(2));
}
second.RemoveFromHierarchy();
UIPreferences.ReducedMotion = false;
UIPreferences.TextSize = UITextSize.Standard;
UIPreferences.Density = UILayoutDensity.Compact;
Assert.That(first.ClassListContains("text-large"), Is.False);
Assert.That(second.ClassListContains("text-large"), Is.True, "A detached screen must not remain subscribed.");
window.rootVisualElement.Add(second);
Assert.That(second.ClassListContains("text-large"), Is.False, "Reattached screens immediately receive current preferences.");
Assert.That(second.ClassListContains("density-comfortable"), Is.False);
Assert.That(second.ClassListContains("reduced-motion"), Is.False);
}
finally { window.Close(); }
}
[UnityTest]
public IEnumerator SettingsRemainReadableAndKeyboardReachableAtEveryTextAndSpacingPreset()
{
RequireGraphics();
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
try
{
window.minSize = new Vector2(100, 100);
window.Show();
var root = window.rootVisualElement;
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
Attach(root);
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/SettingsScreen.uxml").CloneTree();
var settings = template.Q("SettingsPanel");
settings.RemoveFromClassList("hidden");
root.Add(settings);
var scroll = settings.Q<ScrollView>();
foreach (var viewport in new[] { new Vector2(960, 600), new Vector2(390, 600) })
foreach (UITextSize size in Enum.GetValues(typeof(UITextSize)))
foreach (UILayoutDensity density in Enum.GetValues(typeof(UILayoutDensity)))
{
window.position = new Rect(24, 24, viewport.x, viewport.y);
root.style.width = viewport.x;
root.style.height = viewport.y;
UIPreferences.TextSize = size;
UIPreferences.Density = density;
for (int frame = 0; frame < 5; frame++) yield return null;
string context = $"{viewport}, {size}, {density}";
foreach (var label in settings.Query<Label>().ToList())
{
if (string.IsNullOrWhiteSpace(label.text)) continue;
Assert.That(label.worldBound.xMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.xMin - 1), context + ": " + label.text);
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.xMax + 1), context + ": " + label.text);
float measured = label.MeasureTextSize(label.text, label.contentRect.width,
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
Assert.That(label.contentRect.height, Is.GreaterThanOrEqualTo(measured - 1), context + ": clipped " + label.text);
}
Assert.That(settings.Q<Label>(className: "settings-description").resolvedStyle.fontSize,
Is.EqualTo(size == UITextSize.Large ? 17 : 15), context);
foreach (var control in new VisualElement[] { settings.Q<Toggle>("ReducedMotionToggle"), settings.Q<Button>("TextSizeButton"), settings.Q<Button>("DensityButton"), settings.Q<SliderInt>("SoundVolumeSlider") })
{
Assert.That(control.focusable, Is.True, context);
control.Focus();
yield return null;
Assert.That(root.focusController.focusedElement, Is.SameAs(control), context);
Assert.That(control.worldBound.xMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.xMax + 1), context);
}
}
LogAssert.NoUnexpectedReceived();
}
finally { window.Close(); }
}
[UnityTest]
public IEnumerator RunArchiveActionsWrapInsideNarrowScreensAtBothTextSizes()
{
RequireGraphics();
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
var owner = new GameObject("run archive layout fixture");
owner.SetActive(false);
try
{
var controller = owner.AddComponent<MainMenuController>();
const BindingFlags privateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
window.minSize = new Vector2(100, 100);
window.Show();
var root = window.rootVisualElement;
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
Attach(root);
var menu = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
var archive = menu.Q("RunArchivePanel");
archive.RemoveFromClassList("hidden");
root.Add(archive);
new ScreenFrameController().Bind(archive, "$ history --runs", "[esc] back [tab/enter] actions", () => { });
typeof(MainMenuController).GetField("_runArchivePanel", privateInstance).SetValue(controller, archive);
typeof(MainMenuController).GetMethod("RefreshRunActions", privateInstance).Invoke(controller, null);
var scroll = archive.Q<ScrollView>();
var actions = archive.Q("RunArchiveActions");
foreach (var viewport in new[] { new Vector2(960, 600), new Vector2(390, 600) })
foreach (UITextSize size in Enum.GetValues(typeof(UITextSize)))
{
window.position = new Rect(24, 24, viewport.x, viewport.y);
root.style.width = viewport.x;
root.style.height = viewport.y;
UIPreferences.TextSize = size;
UIPreferences.Density = UILayoutDensity.Comfortable;
for (int frame = 0; frame < 5; frame++) yield return null;
string context = $"{viewport}, {size}";
foreach (var element in actions.Query<TextElement>().ToList())
{
if (string.IsNullOrWhiteSpace(element.text)) continue;
Assert.That(element.worldBound.xMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.xMin - 1), context + ": " + element.text);
Assert.That(element.worldBound.xMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.xMax + 1), context + ": " + element.text);
float measured = element.MeasureTextSize(element.text, element.contentRect.width,
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
Assert.That(element.contentRect.height, Is.GreaterThanOrEqualTo(measured - 1), context + ": clipped " + element.text);
}
var history = actions.Q<Button>("RecentRunsButton");
history.Focus();
yield return null;
Assert.That(root.focusController.focusedElement, Is.SameAs(history), context);
Assert.That(archive.Q<Button>(className: "screen-back").worldBound.yMax,
Is.LessThanOrEqualTo(root.worldBound.yMax + 1), context);
}
LogAssert.NoUnexpectedReceived();
}
finally
{
window.Close();
UnityEngine.Object.DestroyImmediate(owner);
}
}
[UnityTest]
public IEnumerator TooltipsNeverCreateAnAutomaticBottomPanel()
{
RequireGraphics();
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
try
{
window.minSize = new Vector2(100, 100);
window.position = new Rect(24, 24, 390, 300);
window.Show();
var root = window.rootVisualElement;
root.style.width = 390;
root.style.height = 300;
UIPreferences.TextSize = UITextSize.Large;
Attach(root);
var owner = new Button { text = "Inspect live card" };
owner.tooltip = "Compilation and equipment modify this card.";
root.Add(owner);
owner.Focus();
double waitUntil = EditorApplication.timeSinceStartup + 0.35;
while (EditorApplication.timeSinceStartup < waitUntil) yield return null;
Assert.That(root.Q(className: "runtime-hint"), Is.Null);
Assert.That(root.childCount, Is.EqualTo(1));
Assert.That(owner.tooltip, Is.EqualTo("Compilation and equipment modify this card."));
Assert.That(root.focusController.focusedElement, Is.SameAs(owner));
LogAssert.NoUnexpectedReceived();
}
finally { window.Close(); }
}
private void InvokeStore(string method) => typeof(UIPreferences).GetMethod(method, InternalStatic).Invoke(null, new object[] { _testKey });
private static void Attach(VisualElement root) => typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme")
.GetMethod("Attach").Invoke(null, new object[] { root });
private static void RequireGraphics()
{
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
Assert.Ignore("Readability layout verification needs a graphical editor panel.");
}
}