Files
2026-10-29 22:54:29 +01:00

711 lines
38 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
using KernelPanic.UI;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;
using Random = UnityEngine.Random;
public class GachaRevealTests
{
private bool _motion;
private UITextSize _textSize;
[SetUp] public void SetUp()
{
_motion = UIPreferences.ReducedMotion;
_textSize = UIPreferences.TextSize;
UIPreferences.ReducedMotion = false;
UIPreferences.TextSize = UITextSize.Standard;
}
[TearDown] public void TearDown()
{
UIPreferences.ReducedMotion = _motion;
UIPreferences.TextSize = _textSize;
}
[TestCase(false, false, 3)]
[TestCase(false, true, 3)]
[TestCase(false, false, 4)]
[TestCase(false, true, 5)]
[TestCase(true, false, 4)]
[TestCase(true, true, 4)]
[TestCase(true, false, 5)]
[TestCase(true, true, 5)]
public void SingleRewardsShowActualIdentityAndExactConversion(bool distro, bool duplicate, int stars)
{
var reward = Reward(1, distro, duplicate, stars);
var root = new VisualElement();
using var view = new GachaRevealView(root, Receipt(reward), () => { });
view.RevealAll();
Assert.That(view.IsComplete, Is.True);
Assert.That(view.SelectedIndex, Is.Zero);
var detail = root.Q("PullRewardDetail");
Assert.That(detail.Q(className: distro ? "distribution-detail" : "package-detail"), Is.Not.Null);
Assert.That(detail.Q(className: distro ? "package-detail" : "distribution-detail"), Is.Null);
string text = Copy(detail);
if (duplicate)
{
Assert.That(text, Does.Contain("DUPLICATE CONVERTED"));
Assert.That(text, Does.Contain("137 " + (distro ? "Merges" : "Cache")), "Use receipt values, not tuning constants.");
}
else Assert.That(text, Does.Contain("Added to your collection."));
if (distro)
{
Assert.That(detail.Q<Label>(className: "reveal-art").text, Is.EqualTo(reward.DisplayData.Distro.AsciiArt.text));
Assert.That(text, Does.Contain(DistroPresentation.FormatLanguages(reward.DisplayData.Distro)));
Assert.That(text, Does.Contain(DistroVersionCatalog.GetReleaseLabel(reward.DisplayData.Distro.Id, 3)));
}
else
{
Assert.That(text, Does.Contain(reward.DisplayData.Package.Description));
Assert.That(text, Does.Contain(reward.DisplayData.Package.Slot.DisplayName().ToUpperInvariant()));
Assert.That(detail.Q(className: "reveal-art"), Is.Null);
}
}
[TestCase(false)]
[TestCase(true)]
public void TenPullsKeepOrderAndFeatureDistributions(bool mixed)
{
var rewards = Enumerable.Range(1, 10).Select(i => Reward(i, mixed && (i == 4 || i == 6), i % 2 == 0, i == 6 ? 5 : i % 3 + 3)).ToArray();
var root = new VisualElement();
using var view = new GachaRevealView(root, new CompletedGachaPull("test", "paid", rewards), () => { });
for (int i = 0; i < 3; i++) view.RevealNext();
Assert.That(view.RevealedCount, Is.EqualTo(3));
Assert.That(root.Q("PullContinue").enabledSelf, Is.False);
Assert.That(root.Q("PullReward-04").ClassListContains("reveal-sealed"), Is.True);
view.RevealAll();
Assert.That(view.RevealedCount, Is.EqualTo(10));
Assert.That(root.Q("PullContinue").enabledSelf, Is.True);
if (mixed) Assert.That(view.SelectedIndex, Is.EqualTo(5), "5-star distro is the final focal point.");
for (int i = 0; i < 10; i++)
{
var tile = root.Q($"PullReward-{i + 1:00}");
Assert.That(tile.Q<Label>(className: "reveal-index").text, Is.EqualTo($"{i + 1:00}"));
Assert.That(tile.Q<Label>(className: "reveal-name").text, Is.EqualTo(rewards[i].DisplayName));
view.Select(i);
Assert.That(view.SelectedIndex, Is.EqualTo(i));
}
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("10 pulls"));
view.RevealNext(); view.RevealAll();
Assert.That(view.RevealedCount, Is.EqualTo(10));
}
[Test]
public void ReducedMotionCompletesImmediatelyAndMissingMetadataNeverClaimsInstallation()
{
UIPreferences.ReducedMotion = true;
var root = new VisualElement();
var missing = new CompletedGachaReward(1, 5, "unavailable", GachaRewardType.Distro, PullOutcomeKind.Invalid, 0, null, true, false);
using var view = new GachaRevealView(root, Receipt(missing), () => { });
view.Begin();
Assert.That(view.IsComplete, Is.True);
Assert.That(Copy(root), Does.Contain("NOT GRANTED"));
Assert.That(Copy(root), Does.Not.Contain("UNIT INSTALLED"));
Assert.That(root.Q(className: "just-unpacked"), Is.Null);
}
[Test]
public void PackagePreviewKeepsExactRulesAndInspectorShowsFullPassive()
{
var root = new VisualElement();
var package = Reward(1, false, true, 4);
var distro = Reward(2, true, false, 5);
using var view = new GachaRevealView(root, Receipt(package, distro), () => { });
view.RevealAll();
Assert.That(root.Q("PullReward-01").Q<Label>(className: "reveal-package-role").text,
Is.EqualTo(package.DisplayData.Package.Description), "Clip the visual preview, never rewrite the rules.");
Assert.That(Copy(root.Q("PullRewardDetail")), Does.Contain(distro.DisplayData.Distro.Passive.RulesText));
Assert.That(root.Q("PullReward-02").Q(className: "reveal-body"), Is.Null);
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("+137 Cache"));
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("highest 5★"));
}
[TestCase(false)]
[TestCase(true)]
public void FiveStarSignatureIsDistinctSkippableAndDoesNotGrantAnything(bool duplicate)
{
var root = new VisualElement();
var reward = Reward(1, true, duplicate, 5);
int continued = 0;
using var view = new GachaRevealView(root, Receipt(reward), () => continued++);
view.RevealNext();
Assert.That(view.IsSignatureRevealing, Is.True);
Assert.That(view.IsComplete, Is.False, "The last signature must finish before Continue is enabled.");
Assert.That(root.Q("PullContinue").enabledSelf, Is.False);
var signature = root.Q("DistributionSignature");
Assert.That(signature, Is.Not.Null);
Assert.That(signature.Q<Label>(className: "reveal-art").text, Is.EqualTo(reward.DisplayData.Distro.AsciiArt.text));
Assert.That(Copy(signature), Does.Contain(duplicate ? "DISTRIBUTION ALREADY INSTALLED" : "UNIT INSTALLED"));
if (duplicate) Assert.That(Copy(signature), Does.Not.Contain("UNIT INSTALLED"));
view.RevealNext(); // Space skips the current signature, not another reward.
Assert.That(view.IsSignatureRevealing, Is.False);
Assert.That(view.IsComplete, Is.True);
Assert.That(root.Q("DistributionSignature"), Is.Null);
Assert.That(continued, Is.Zero);
view.RevealAll(); view.RevealNext();
Assert.That(view.RevealedCount, Is.EqualTo(1));
}
[TestCase(true, false)]
[TestCase(true, true)]
[TestCase(false, false)]
[TestCase(false, true)]
public void AcquisitionStateDoesNotReplaceTypeOrRarity(bool distro, bool duplicate)
{
var root = new VisualElement();
using var view = new GachaRevealView(root, Receipt(Reward(1, distro, duplicate, 5)), () => { });
view.RevealAll();
var tile = root.Q("PullReward-01");
Assert.That(tile.ClassListContains("rarity-5"), Is.True);
Assert.That(tile.ClassListContains(distro ? "reveal-distribution" : "reveal-package"), Is.True);
Assert.That(tile.ClassListContains("acquisition-new"), Is.EqualTo(!duplicate));
Assert.That(tile.ClassListContains("acquisition-duplicate"), Is.EqualTo(duplicate));
string status = tile.Q<Label>(className: "reveal-outcome").text;
Assert.That(status, Does.Contain(duplicate ? "DUPLICATE" : distro ? "NEW DISTRO" : "NEW PACKAGE"));
if (duplicate) Assert.That(status, Does.Contain(distro ? "+137 Merges" : "+137 Cache"));
}
[UnityTest]
public IEnumerator LongPackagePreviewEndsAtWordBoundaryAndExpandsWithAvailableWidth()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
var package = UnityEngine.Object.Instantiate(AssetDatabase.LoadAssetAtPath<PackageDefinition>("Assets/Data/Packages/SnapStore.asset"));
GachaRevealView view = null;
try
{
window.Show();
var root = window.rootVisualElement;
Attach(root);
root.style.width = 1093; root.style.height = 614;
string full = package.Description + " Additional fixture rules remain available in the full inspector, without cutting a word in half.";
typeof(PackageDefinition).GetField("description", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(package, full);
var longReward = new CompletedGachaReward(1,4,"A deliberately long runtime package name",GachaRewardType.Package,PullOutcomeKind.Granted,0,null,false,false,new GachaRewardDisplayData(null,package,1,0));
view = new GachaRevealView(root, Receipt(new[] { longReward }.Concat(Enumerable.Range(2,9).Select(i => Reward(i,false,true,3))).ToArray()), () => { });
view.RevealAll();
for (int frame = 0; frame < 8; frame++) yield return null;
var preview = root.Q("PullReward-01").Q<Label>(className: "reveal-package-role");
string small = preview.text;
Assert.That(small, Does.EndWith(" …"));
Assert.That(full, Does.StartWith(small.Substring(0,small.Length-2) + " "), "Only whole words from the actual rules are shown.");
Assert.That(preview.tooltip, Is.EqualTo(full));
Assert.That(preview.resolvedStyle.fontSize, Is.GreaterThanOrEqualTo(15));
Assert.That(preview.MeasureTextSize(preview.text,preview.contentRect.width-1,VisualElement.MeasureMode.AtMost,0,VisualElement.MeasureMode.Undefined).y, Is.LessThanOrEqualTo(preview.layout.height+1));
view.Select(0);
Assert.That(Copy(root.Q("PullRewardDetail")), Does.Contain(full));
root.style.width = 1920;
for (int frame = 0; frame < 8; frame++) yield return null;
Assert.That(preview.text.Length, Is.GreaterThan(small.Length));
Assert.That(package.Description, Is.EqualTo(full));
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); UnityEngine.Object.DestroyImmediate(package); }
}
[UnityTest]
public IEnumerator DistroArtworkFitsItsFrameAndFocusDoesNotResizeTiles()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.Show();
var root = window.rootVisualElement;
root.style.width = 1093; root.style.height = 614;
Attach(root);
var rewards = new[] { "Arch", "Mint", "Fedora", "Ubuntu" }.Select((id,i) =>
{
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>($"Assets/Data/Distros/{id}.asset");
return new CompletedGachaReward(i+1,i==0?5:4,distro.DisplayName,GachaRewardType.Distro,PullOutcomeKind.Granted,0,null,false,false,new GachaRewardDisplayData(distro,null,1,0));
}).Concat(Enumerable.Range(5,6).Select(i => Reward(i,false,false,3))).ToArray();
view = new GachaRevealView(root, Receipt(rewards), () => { });
view.RevealAll();
for (int frame = 0; frame < 8; frame++) yield return null;
for (int i = 0; i < 4; i++)
{
var tile = root.Q<Button>($"PullReward-{i+1:00}");
float width = tile.layout.width, height = tile.layout.height;
tile.Focus();
for (int frame = 0; frame < 4; frame++) yield return null;
Assert.That(view.SelectedIndex, Is.EqualTo(i));
Assert.That(tile.layout.width, Is.EqualTo(width).Within(1));
Assert.That(tile.layout.height, Is.EqualTo(height).Within(1));
var art = tile.Q<Label>(className: "reveal-mini-art");
Assert.That(art.text, Is.EqualTo(rewards[i].DisplayData.Distro.AsciiArt.text));
var inspectorArt = root.Q("PullRewardDetail").Q<Label>(className:"reveal-art");
foreach (var fitted in new[] { art, inspectorArt })
{
Vector2 measured = fitted.MeasureTextSize(fitted.text,0,VisualElement.MeasureMode.Undefined,0,VisualElement.MeasureMode.Undefined);
Assert.That(measured.y, Is.LessThanOrEqualTo(fitted.contentRect.height+1), "All ASCII rows fit with actual font line spacing.");
Assert.That(measured.x, Is.LessThanOrEqualTo(fitted.contentRect.width+1), "ASCII columns fit without changing their spacing.");
}
Assert.That(inspectorArt.resolvedStyle.fontSize, Is.GreaterThan(art.resolvedStyle.fontSize));
Assert.That(Copy(root.Q("PullRewardDetail")), Does.Contain(rewards[i].DisplayName));
}
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
[UnityTest]
public IEnumerator SkipRestoresFocusWithoutArmingContinueForHeldSpace()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.Show();
var root = window.rootVisualElement;
Attach(root);
int continued = 0;
view = new GachaRevealView(root, Receipt(Reward(1,true,true,5)), () => continued++);
var skip = root.Query<Button>().ToList().First(b => b.text == "[R] reveal all");
Assert.That(root.Q<Label>(className: "reveal-help").text, Does.Contain("[Esc] reveal all"));
skip.Focus();
yield return null;
Key(root,KeyCode.R);
Assert.That(root.focusController.focusedElement, Is.SameAs(root));
Assert.That(root.Q<Label>(className: "reveal-help").text, Does.Contain("[Esc] back"));
Key(root,KeyCode.Space);
Assert.That(continued, Is.Zero);
Key(root,KeyCode.Return);
Assert.That(continued, Is.EqualTo(1));
}
finally { view?.Dispose(); window.Close(); }
}
[Test]
public void EnablingReducedMotionDuringSignatureCancelsAllPresentationDelays()
{
var root = new VisualElement();
using var view = new GachaRevealView(root, Receipt(Reward(1, true, true, 5), Reward(2, false, false, 3)), () => { });
view.RevealNext();
UIPreferences.ReducedMotion = true;
view.Begin();
Assert.That(view.IsComplete, Is.True);
Assert.That(root.ClassListContains("reduced-motion"), Is.True);
Assert.That(root.Q("DistributionSignature"), Is.Null);
Assert.That(root.Q(className: "just-unpacked"), Is.Null);
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("+137 Merges"));
}
[Test]
public void RevealAllCancelsSignatureAndAllPendingTileTransitions()
{
var root = new VisualElement();
using var view = new GachaRevealView(root, Receipt(Reward(1, true, true, 5), Reward(2, false, false, 3)), () => { });
view.RevealNext();
view.RevealAll();
Assert.That(view.IsComplete, Is.True);
Assert.That(root.Q(className: "signature-active"), Is.Null);
Assert.That(root.Q(className: "just-unpacked"), Is.Null);
Assert.That(root.Q("DistributionSignature"), Is.Null);
Assert.That(view.SelectedIndex, Is.Zero);
}
[UnityTest]
public IEnumerator SignatureAdvancesThroughVerificationAndResumesUnpacking()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.Show();
var root = window.rootVisualElement;
Attach(root);
view = new GachaRevealView(root, Receipt(Reward(1, true, false, 5), Reward(2, false, true, 4)), () => { });
view.RevealNext();
Assert.That(root.Q("DistributionSignature").ClassListContains("signature-verified"), Is.False);
double deadline = EditorApplication.timeSinceStartup + 4;
bool verified = false, resolved = false;
while (!view.IsComplete && EditorApplication.timeSinceStartup < deadline)
{
var signature = root.Q("DistributionSignature");
verified |= signature?.ClassListContains("signature-verified") == true;
resolved |= signature?.ClassListContains("signature-resolved") == true;
yield return null;
}
Assert.That(verified, Is.True);
Assert.That(resolved, Is.True);
Assert.That(view.IsComplete, Is.True);
Assert.That(view.RevealedCount, Is.EqualTo(2));
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
[UnityTest]
public IEnumerator EnterDoesNotBothRevealAndContinueOrRepeatWhileHeld()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.Show();
var root = window.rootVisualElement;
Attach(root);
int continued = 0;
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3)), () => continued++);
root.Focus();
yield return null;
Key(root, KeyCode.Return);
using (var submit = NavigationSubmitEvent.GetPooled()) { submit.target = root; root.SendEvent(submit); }
Assert.That(view.IsComplete, Is.True);
Assert.That(continued, Is.Zero);
yield return null;
Key(root, KeyCode.Return);
Assert.That(continued, Is.Zero, "A held Enter must not dismiss newly completed results.");
using (var release = KeyUpEvent.GetPooled('\0', KeyCode.Return, EventModifiers.None)) { release.target = root; root.SendEvent(release); }
yield return null;
Key(root, KeyCode.Return);
Assert.That(continued, Is.EqualTo(1));
}
finally { view?.Dispose(); window.Close(); }
}
[UnityTest]
public IEnumerator SingleReceiptsUseAvailableWidthWithoutHidingSummaryOrContinue()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.Show();
var root = window.rootVisualElement;
Attach(root);
foreach (var size in new[] { new Vector2(1536,864), new Vector2(1093,614), new Vector2(1024,576), new Vector2(819,614), new Vector2(312,675) })
foreach (bool distro in new[] { false, true })
{
view?.Dispose(); root.Clear();
root.style.width = size.x; root.style.height = size.y;
view = new GachaRevealView(root, Receipt(Reward(1, distro, true, 5)), () => { });
view.RevealAll();
for (int frame = 0; frame < 5; frame++) yield return null;
var detail = root.Q<ScrollView>("PullRewardDetail");
Assert.That(detail.worldBound.xMax, Is.LessThanOrEqualTo(root.worldBound.xMax + 1));
Assert.That(detail.horizontalScroller.highValue, Is.LessThanOrEqualTo(1));
Assert.That(root.Q("PullContinue").worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax + 1));
Assert.That(root.Q("PullSummaryTotals").worldBound.width, Is.GreaterThan(250));
if (size.x >= 760) Assert.That(detail.worldBound.width, Is.GreaterThan(400), "Use the space released by the single-result grid.");
}
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
[UnityTest]
public IEnumerator LayoutMatrixKeepsOrderReadableTilesAndAccessibleControls()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.position = new Rect(0, 0, 1150, 800);
window.Show();
var root = window.rootVisualElement;
Attach(root);
// Include the 125% DPI logical sizes used by the actual runtime panel.
foreach (var size in new[] { new Vector2(1920,1080), new Vector2(1366,768), new Vector2(1280,720), new Vector2(1024,768), new Vector2(390,844), new Vector2(740,480), new Vector2(1093,614), new Vector2(1024,576), new Vector2(819,614), new Vector2(312,675) })
foreach (int units in new[] { 0, 1, 3, 10 })
{
view?.Dispose(); root.Clear();
root.style.width = size.x; root.style.height = size.y;
view = new GachaRevealView(root, Receipt(Enumerable.Range(1,10).Select(i =>
{
bool distro = units == 10 || units == 1 && i == 6 || units == 3 && (i == 4 || i == 6 || i == 9);
return Reward(i, distro, i % 2 == 0, distro ? 5 : i % 3 + 3);
}).ToArray()), () => { });
view.RevealAll();
for (int frame = 0; frame < 5; frame++) yield return null;
string context = $"{size}, {units} distributions";
var next = root.Q("PullContinue");
Assert.That(next.worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax + 1), context);
Assert.That(next.worldBound.xMax, Is.LessThanOrEqualTo(root.worldBound.xMax + 1), context);
var grid = root.Q<ScrollView>("PullRewardScroll");
var detail = root.Q<ScrollView>("PullRewardDetail");
Assert.That(detail.contentViewport.worldBound.height, Is.GreaterThan(60), context);
Assert.That(detail.horizontalScroller.highValue, Is.LessThanOrEqualTo(1), context);
if (size.x >= 760) Assert.That(grid.horizontalScroller.highValue, Is.LessThanOrEqualTo(1), context);
if (size.x >= 760) Assert.That(grid.scrollOffset.y, Is.EqualTo(0).Within(1), "Overview starts at pull 01: " + context);
if (size.x >= 1024)
{
Assert.That(root.Q("PullReward-01").worldBound.y, Is.EqualTo(root.Q("PullReward-05").worldBound.y).Within(1), "Five columns: " + context);
Assert.That(root.Q("PullReward-06").worldBound.y, Is.GreaterThan(root.Q("PullReward-01").worldBound.y), context);
}
for (int i = 1; i <= 10; i++)
{
var tile = root.Q($"PullReward-{i:00}");
var rarity = tile.Q(className: "reveal-stars");
Assert.That(rarity.worldBound.xMax, Is.LessThanOrEqualTo(tile.worldBound.xMax + 1), "Rarity fits: " + context);
var art = tile.Q<Label>(className: "reveal-mini-art");
if (art != null && size.x >= 760)
{
Assert.That(art.worldBound.xMax, Is.LessThanOrEqualTo(tile.worldBound.xMax + 1), "ASCII frame stays inside its card: " + context);
Vector2 measured = art.MeasureTextSize(art.text,0,VisualElement.MeasureMode.Undefined,0,VisualElement.MeasureMode.Undefined);
Assert.That(measured.x, Is.LessThanOrEqualTo(art.contentRect.width + 1), "All ASCII columns fit: " + context);
Assert.That(measured.y, Is.LessThanOrEqualTo(art.contentRect.height + 1), "All ASCII rows fit: " + context);
}
}
}
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
[UnityTest]
public IEnumerator TileHeadersKeepFullIndexAndFiveStarRarityWithoutOverlapAtBothTextSizes()
{
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.position = new Rect(0, 0, 1150, 800);
window.Show();
var root = window.rootVisualElement;
Attach(root);
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
foreach (var size in new[] { new Vector2(1366, 768), new Vector2(1024, 768), new Vector2(819, 614), new Vector2(312, 675) })
{
view?.Dispose(); root.Clear();
UIPreferences.TextSize = textSize;
root.style.width = size.x; root.style.height = size.y;
view = new GachaRevealView(root, Receipt(Enumerable.Range(1, 10)
.Select(i => Reward(i, i % 2 == 0, i % 3 == 0, 5)).ToArray()), () => { });
view.RevealAll();
for (int frame = 0; frame < 5; frame++) yield return null;
string context = $"{size}, {textSize}";
for (int i = 1; i <= 10; i++)
{
var tile = root.Q($"PullReward-{i:00}");
var header = tile.Q(className: "reveal-tile-top");
var index = header.Q<Label>(className: "reveal-index");
var rarity = header.Q<Label>(className: "reveal-stars");
Assert.That(index.text, Is.EqualTo($"{i:00}"), context);
Assert.That(rarity.text, Is.EqualTo("[" + RarityPresentation.ForStars(5).Stars + "]"), context);
foreach (var label in new[] { index, rarity })
{
Assert.That(label.worldBound.xMin, Is.GreaterThanOrEqualTo(header.worldBound.xMin - 1), context);
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(header.worldBound.xMax + 1), context);
Assert.That(label.worldBound.yMax, Is.LessThanOrEqualTo(header.worldBound.yMax + 1), context);
var measured = label.MeasureTextSize(label.text, 0, VisualElement.MeasureMode.Undefined,
0, VisualElement.MeasureMode.Undefined);
Assert.That(measured.x, Is.LessThanOrEqualTo(label.contentRect.width + 1), "Full header text fits: " + context);
}
Assert.That(index.worldBound.Overlaps(rarity.worldBound), Is.False, "Index and rarity never overlap: " + context);
Assert.That(tile.Q(className: "reveal-kind").worldBound.yMin,
Is.GreaterThanOrEqualTo(header.worldBound.yMax - 1), "Wrapped rarity does not overlap reward kind: " + context);
}
}
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
[Test]
public void GrantingAndPresentingPackagesAreSeparateAndIdempotent()
{
var database = ScriptableObject.CreateInstance<PackageDatabase>();
var package = AssetDatabase.LoadAssetAtPath<PackageDefinition>("Assets/Data/Packages/Zram.asset");
typeof(PackageDatabase).GetField("allPackages", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(database, new List<PackageDefinition> { package });
var random = Random.state;
try
{
var save = SaveData.CreateDefault();
var collection = new PlayerCollection();
var grant = typeof(GamblingSceneController).GetMethod("GrantRandomPackageByRarity", BindingFlags.Static | BindingFlags.NonPublic);
var args = new object[] { database, collection, save, 3, false, 0 };
grant.Invoke(null, args);
Assert.That(args[4], Is.EqualTo(false));
Assert.That(collection.OwnedPackageInstances.Count, Is.EqualTo(1));
grant.Invoke(null, args);
Assert.That(args[4], Is.EqualTo(true));
Assert.That(args[5], Is.EqualTo(PackageTuning.GetCacheForRarity(3)));
int cache = save.cacheBalance;
string committed = JsonUtility.ToJson(save);
var stateAfterGrant = Random.state;
var reward = new CompletedGachaReward(1, 3, package.DisplayName, GachaRewardType.Package, PullOutcomeKind.Dupe,
(int)args[5], null, false, false, new GachaRewardDisplayData(null, package, 1, 0));
for (int repeat = 0; repeat < 3; repeat++)
{
using var view = new GachaRevealView(new VisualElement(), Receipt(reward), () => { });
view.RevealNext(); view.RevealAll(); view.Select(0); view.RevealAll();
}
Assert.That(JsonUtility.ToJson(save), Is.EqualTo(committed));
Assert.That(save.cacheBalance, Is.EqualTo(cache));
Assert.That(collection.OwnedPackageInstances.Count, Is.EqualTo(1));
Assert.That(JsonUtility.ToJson(Random.state), Is.EqualTo(JsonUtility.ToJson(stateAfterGrant)));
}
finally { Random.state = random; UnityEngine.Object.DestroyImmediate(database); }
}
[Test]
public void EmptyReceiptsAndRebuildingDoNotReplayTransactions()
{
var root = new VisualElement();
using (var empty = new GachaRevealView(root, Receipt(), () => { }))
{
empty.Begin();
Assert.That(empty.IsComplete, Is.True);
Assert.That(root.Q("PullContinue").enabledSelf, Is.True);
}
root.Clear();
var rewards = new List<CompletedGachaReward> { Reward(1, false, false, 3) };
using var view = new GachaRevealView(root, new CompletedGachaPull("test", "paid", rewards), () => { });
rewards.Clear();
view.RevealAll();
Assert.That(view.RevealedCount, Is.EqualTo(1), "Presentation owns a snapshot of the receipt order.");
}
[UnityTest]
public IEnumerator NarrowReceiptUsesAResultStripAndKeepsContinueVisible()
{
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null) Assert.Ignore("Requires an editor panel.");
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.position = new Rect(0, 0, 1150, 800);
window.Show();
var root = window.rootVisualElement;
root.style.width = 390;
root.style.height = 720;
Attach(root);
view = new GachaRevealView(root, Receipt(Enumerable.Range(1, 10).Select(i => Reward(i, i == 6, i % 2 == 0, i == 6 ? 5 : 3)).ToArray()), () => { });
view.RevealAll();
for (int frame = 0; frame < 5; frame++) yield return null;
Assert.That(root.Q<ScrollView>("PullRewardScroll").mode, Is.EqualTo(ScrollViewMode.Horizontal));
var next = root.Q<Button>("PullContinue");
Assert.That(next.worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax));
Assert.That(next.worldBound.xMax, Is.LessThanOrEqualTo(root.worldBound.xMax));
Assert.That(root.Q<ScrollView>("PullRewardDetail").horizontalScroller.highValue, Is.LessThanOrEqualTo(1));
root.style.width = 1100;
for (int frame = 0; frame < 5; frame++) yield return null;
Assert.That(root.Q<ScrollView>("PullRewardScroll").mode, Is.EqualTo(ScrollViewMode.Vertical));
Assert.That(root.Q<ScrollView>("PullRewardScroll").horizontalScroller.highValue, Is.LessThanOrEqualTo(1));
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
[Test]
public void DistroNewDuplicateAndMaxReleaseConversionsComeFromResolver()
{
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Mint.asset");
var save = SaveData.CreateDefault();
var owned = new PlayerCollection();
var context = new PullResolutionContext(save, owned, focusUnitId: distro.Id);
var first = PullResolver.Resolve(new[] { distro, distro }, context);
Assert.That(first.Outcomes[0].Kind, Is.EqualTo(PullOutcomeKind.Granted));
Assert.That(first.Outcomes[1].Kind, Is.EqualTo(PullOutcomeKind.Dupe));
save.FindOwnedUnit(distro.Id).version = GachaTuning.MaxVersion;
var overflow = PullResolver.Resolve(new[] { distro }, context).Outcomes[0];
Assert.That(overflow.Kind, Is.EqualTo(PullOutcomeKind.DupeOverflow));
var reward = new CompletedGachaReward(1, 4, distro.DisplayName, GachaRewardType.Distro, overflow.Kind,
overflow.MergesAwarded, overflow.LanguagesNewlyUnlocked, false, false, new GachaRewardDisplayData(distro, null, 5, 0));
string committed = JsonUtility.ToJson(save);
var root = new VisualElement();
using var view = new GachaRevealView(root, Receipt(reward), () => { });
view.RevealAll(); view.RevealAll();
Assert.That(Copy(root), Does.Contain($"+{overflow.MergesAwarded} Merges"));
Assert.That(Copy(root), Does.Contain("Maximum release already installed."));
Assert.That(JsonUtility.ToJson(save), Is.EqualTo(committed));
}
[UnityTest]
public IEnumerator RevealControlsSupportKeyboardInspectionAndDoNotExitOnArrowsOrTab()
{
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null) Assert.Ignore("Requires an editor panel.");
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.position = new Rect(0, 0, 1000, 700);
window.Show();
var root = window.rootVisualElement;
Attach(root);
int continued = 0;
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3), Reward(2, true, true, 5)), () => continued++);
root.Focus();
yield return null;
Key(root, KeyCode.Space);
Assert.That(view.RevealedCount, Is.EqualTo(1));
Assert.That(continued, Is.Zero);
Key(root, KeyCode.Escape);
Assert.That(view.IsComplete, Is.True);
Key(root, KeyCode.Escape);
Assert.That(continued, Is.Zero, "Holding skip must not immediately dismiss the receipt.");
using (var release = KeyUpEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None)) { release.target = root; root.SendEvent(release); }
Key(root, KeyCode.R);
Key(root, KeyCode.LeftArrow);
Assert.That(view.SelectedIndex, Is.Zero);
Key(root, KeyCode.Tab);
Assert.That(continued, Is.Zero);
var button = root.Q<Button>("PullReward-02");
button.Focus();
using (var submit = NavigationSubmitEvent.GetPooled()) { submit.target = button; button.SendEvent(submit); }
Assert.That(view.SelectedIndex, Is.EqualTo(1));
Assert.That(continued, Is.Zero);
Key(root, KeyCode.Escape);
Key(root, KeyCode.Escape);
Assert.That(continued, Is.EqualTo(1));
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
[UnityTest]
public IEnumerator AutoRevealCompletesAndDisposalCancelsPendingWork()
{
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null) Assert.Ignore("Requires an editor panel.");
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
GachaRevealView view = null;
try
{
window.Show();
var root = window.rootVisualElement;
Attach(root);
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3), Reward(2, true, false, 4)), () => { });
view.Begin();
double until = EditorApplication.timeSinceStartup + 5;
while (!view.IsComplete && EditorApplication.timeSinceStartup < until) yield return null;
Assert.That(view.IsComplete, Is.True);
view.Dispose();
root.Clear();
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3)), () => { });
view.Begin();
view.Dispose();
view.RevealNext(); view.RevealAll();
Assert.That(view.RevealedCount, Is.Zero);
LogAssert.NoUnexpectedReceived();
}
finally { view?.Dispose(); window.Close(); }
}
private static CompletedGachaPull Receipt(params CompletedGachaReward[] rewards) => new("fixture", "spent fixture currency", rewards);
private static CompletedGachaReward Reward(int index, bool distro, bool duplicate, int stars)
{
var unit = distro ? AssetDatabase.LoadAssetAtPath<DistroDefinition>($"Assets/Data/Distros/{(stars == 5 ? "Arch" : "Mint")}.asset") : null;
var package = distro ? null : AssetDatabase.LoadAssetAtPath<PackageDefinition>($"Assets/Data/Packages/{(stars == 5 ? "Apt" : stars == 4 ? "Aur" : "Zram")}.asset");
return new CompletedGachaReward(index, stars, distro ? unit.DisplayName : package.DisplayName, distro ? GachaRewardType.Distro : GachaRewardType.Package,
duplicate ? PullOutcomeKind.Dupe : PullOutcomeKind.Granted, duplicate ? 137 : 0, Array.Empty<Language>(), false, false,
new GachaRewardDisplayData(unit, package, 3, 2));
}
private static string Copy(VisualElement root) => string.Join("\n", root.Query<Label>().ToList().Select(l => l.text));
private static void Key(VisualElement target, KeyCode key) { using var evt = KeyDownEvent.GetPooled('\0', key, EventModifiers.None); evt.target = target; target.SendEvent(evt); }
private static void Attach(VisualElement root)
{
root.styleSheets.Add(Resources.Load<StyleSheet>("GamblingScene"));
root.styleSheets.Add(Resources.Load<StyleSheet>("RarityPresentation"));
typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme").GetMethod("Attach").Invoke(null, new object[] { root });
}
}