Files
UnrealLuaDemo/Script/ts/src/tests/ue/run_ue_tests.ts
T

488 lines
27 KiB
TypeScript

/** @noSelfInFile */
import { GetGameInstanceContext } from "../../framework/context/game_context";
import * as Json from "../../framework/core/json";
import { ASSET_KEYS, BASE_ASSET_PATHS } from "../../framework/resource/asset_catalog";
import type { ResourceService } from "../../framework/resource/resource_service";
import { LocalSaveManager } from "../../framework/storage/local_save";
import { UEStorageBackend } from "../../framework/storage/storage_backend";
import type { UIDelegateBridge } from "../../framework/ui/ui_delegate_bridge";
import { MiniSettingsWindow } from "../../game/setting/mini_settings_window";
import { SettingService } from "../../game/setting/setting_service";
import { DemoHubWindow } from "../../game/demo/demo_hub_window";
import { OpenDemoHub, OpenUIDemoMain } from "../../game/demo/demo_router";
import {
UIDemoCachedWindow,
UIDemoFullscreenWindow,
UIDemoModalWindow,
UIDemoMultiWindow,
UIDemoNormalWindow,
UIDemoSystemWindow,
UIDemoToastWindow,
} from "../../game/demo/ui_demo/ui_demo_windows";
import { GetPrimaryUIManager } from "../../game/startup";
import { ScopedObject } from "../../share/base/scoped_object";
import { Assert, AssertEqual, FormatReport, RunSuites, type TestSuite, type TestSummary } from "../harness/test_runner";
function PumpUEFrames(frames: number, dt = 0.02): void {
if (__UE_TEST_TICK === undefined) {
return;
}
for (let i = 0; i < frames; i++) {
__UE_TEST_TICK(dt);
}
}
export function RunAllUETests(
gameInstance: UE.ULuaGameInstance | undefined,
world: UE.UWorld | undefined
): TestSummary {
const suites: TestSuite[] = [
{
name: "UE.NativeJson",
cases: [
{
name: "ue_json native C++ module is active and preserves 64-bit integers and UTF-8",
fn: () => {
Assert(Json.IsNativeBackend(), "expected native ue_json backend inside UE");
const bigInt = tonumber("9007199254740993") as number; // true Lua 5.4 int64 (2^53 + 1)
AssertEqual(math.type(bigInt), "integer", "bigInt is Lua 5.4 integer");
const input = {
version: 2,
roleId: bigInt,
title: "UE5.8中文测试",
enabled: true,
list: [10, 20, 30],
empty: Json.GetEmptyArray(),
};
const [encoded, encErr] = Json.Encode(input);
AssertEqual(encErr, undefined, "encode error");
Assert(type(encoded) === "string", "encoded string");
const [decoded, decErr] = Json.Decode(encoded as string);
AssertEqual(decErr, undefined, "decode error");
const obj = decoded as Record<string, any>;
AssertEqual(obj.version, 2);
AssertEqual(obj.roleId, bigInt, "int64 lossless round-trip");
AssertEqual(obj.title, "UE5.8中文测试");
AssertEqual(obj.enabled, true);
const list = obj.list as number[];
AssertEqual(list[0], 10);
AssertEqual(list[2], 30);
const [badVal, badErr] = Json.Decode("{broken");
AssertEqual(badVal, undefined);
Assert(badErr !== undefined && badErr !== "", "malformed JSON returns error");
},
},
],
},
{
name: "UE.LocalStorage",
cases: [
{
name: "ULuaStorageLibrary + ULuaSaveGame: debounce save, cold-start readback, and corruption recovery",
fn: () => {
Assert(gameInstance !== undefined, "gameInstance required");
const ctx = GetGameInstanceContext(gameInstance!)!;
Assert(ctx !== undefined, "GameInstanceContext must be initialized");
const slotId = "ue_test_slot";
const fullSlotName = "sdata_" + slotId;
UE.ULuaStorageLibrary.DeleteSlot(fullSlotName, 0, true);
const backend = new UEStorageBackend();
const saveMgr = new LocalSaveManager(backend, ctx.scheduler);
const settings = new SettingService(saveMgr, slotId);
AssertEqual(settings.GetStore().GetLastLoadStatus(), "not_found");
AssertEqual(settings.GetSoundEnabled(), true, "missing slot returns default");
// Debounced save triggered by real UE FTSTicker -> GameInstanceContext.Tick
settings.SetSoundEnabled(false);
PumpUEFrames(8, 0.02); // 0.16s > 0.1s debounce
AssertEqual(settings.GetStore().IsDirty(), false, "debounced save flushed to UE SaveGame");
Assert(UE.ULuaStorageLibrary.DoesSlotExist(fullSlotName, 0), "SaveGame file created on disk");
// Write a second value so first value (false) moves to .bak
settings.SetSoundEnabled(true);
AssertEqual(settings.Flush(), "ok");
settings.Dispose();
saveMgr.Dispose();
// Cold-start readback
const saveMgr2 = new LocalSaveManager(backend, ctx.scheduler);
const settings2 = new SettingService(saveMgr2, slotId);
AssertEqual(settings2.GetStore().GetLastLoadStatus(), "ok");
AssertEqual(settings2.GetSoundEnabled(), true, "cold-start reads latest value");
settings2.Dispose();
saveMgr2.Dispose();
// Inject corrupted primary bytes -> preserves .corrupt and recovers .bak (false)
Assert(
UE.ULuaStorageLibrary.WriteCorruptRawSlotForTest(fullSlotName, "CORRUPTED_SAV_DATA", 0),
"corrupt injection succeeded"
);
const saveMgr3 = new LocalSaveManager(backend, ctx.scheduler);
const settings3 = new SettingService(saveMgr3, slotId);
AssertEqual(settings3.GetStore().GetLastLoadStatus(), "ok");
Assert(settings3.GetStore().WasRecoveredFromBackup(), "recovered from .bak");
AssertEqual(settings3.GetSoundEnabled(), false, "recovered previous valid value");
Assert(
UE.ULuaStorageLibrary.DoesCorruptBackupExist(fullSlotName, 0),
".corrupt evidence preserved"
);
settings3.Dispose();
saveMgr3.Dispose();
UE.ULuaStorageLibrary.DeleteSlot(fullSlotName, 0, true);
},
},
],
},
{
name: "UE.ResourceManager",
cases: [
{
name: "ULuaResourceSubsystem: PIE Content load, PatchManifest override, coalesced cancel, and GC ref-count",
fn: () => {
Assert(gameInstance !== undefined, "gameInstance required");
const ctx = GetGameInstanceContext(gameInstance!)!;
const resSvc = ctx.GetService<ResourceService>("resource")!;
const sub = UE.ULuaResourceSubsystem.GetFromGameInstance(gameInstance!)!;
Assert(resSvc !== undefined && sub !== undefined, "ResourceService & Subsystem ready");
Assert(resSvc.DoesAssetExist(ASSET_KEYS.MINI_SETTINGS_ICON), "T_MiniSettingsIcon exists");
Assert(resSvc.DoesAssetExist(ASSET_KEYS.MINI_SETTINGS_WIDGET), "WBP_MiniSettings exists");
Assert(!resSvc.DoesAssetExist("/Game/DoesNotExist/MissingAsset"), "missing asset returns false");
// PatchManifest logical key override precedence
const aliasKey = "tex.patch_alias_icon";
Assert(
sub.ApplyPatchManifest(
string.format('{"%s":"%s"}', aliasKey, BASE_ASSET_PATHS[ASSET_KEYS.MINI_SETTINGS_ICON])
),
"ApplyPatchManifest succeeded"
);
AssertEqual(
resSvc.ResolveAssetPath(aliasKey),
BASE_ASSET_PATHS[ASSET_KEYS.MINI_SETTINGS_ICON],
"PatchOverlay resolves alias key"
);
// Concurrent async load of Texture + Widget Class + coalesced duplicate with independent cancel
const owner1 = new ScopedObject();
const owner2 = new ScopedObject();
const owner3 = new ScopedObject();
let tex1: UE.UTexture2D | undefined;
let tex2: UE.UTexture2D | undefined;
let cancelledFired = false;
let widgetCls: UE.UClass | undefined;
let missingCalls = 0;
let missingOk = true;
resSvc.LoadTextureAsync(ASSET_KEYS.MINI_SETTINGS_ICON, owner1, (ok, asset) => {
if (ok) tex1 = asset;
});
const hCancel = resSvc.LoadTextureAsync(aliasKey, owner3, () => {
cancelledFired = true;
});
resSvc.LoadTextureAsync(aliasKey, owner2, (ok, asset) => {
if (ok) tex2 = asset;
});
resSvc.LoadClassAsync(ASSET_KEYS.MINI_SETTINGS_WIDGET, owner1, (ok, cls) => {
if (ok) widgetCls = cls;
});
resSvc.LoadObjectAsync("/Game/DoesNotExist/MissingAsset", owner1, (ok) => {
missingCalls = missingCalls + 1;
missingOk = ok;
});
// Cancel consumer #3 while #1 & #2 still wait
hCancel.Cancel();
PumpUEFrames(15, 0.02);
Assert(!cancelledFired, "cancelled caller must not receive callback");
Assert(tex1 !== undefined && UE.UKismetSystemLibrary.IsValid(tex1), "tex1 loaded & valid");
Assert(tex2 !== undefined && UE.UKismetSystemLibrary.IsValid(tex2), "tex2 loaded & valid");
Assert(widgetCls !== undefined && UE.UKismetSystemLibrary.IsValid(widgetCls), "WBP_MiniSettings class loaded");
AssertEqual(missingCalls, 1, "missing asset delivers exactly once");
AssertEqual(missingOk, false, "missing asset reports ok=false");
// Same underlying texture held by 2 logical keys: release owner1 + force UE GC -> owner2 still valid!
owner1.Dispose();
if (__UE_TEST_GC !== undefined) {
__UE_TEST_GC();
}
Assert(UE.UKismetSystemLibrary.IsValid(tex2!), "tex2 survives GC while owner2 holds ref");
AssertEqual(sub.GetAssetRefCount(ASSET_KEYS.MINI_SETTINGS_ICON), 1, "refcount decremented to 1");
// Release last owner -> counts return cleanly to 0
owner2.Dispose();
owner3.Dispose();
sub.ClearPatchManifest();
if (__UE_TEST_GC !== undefined) {
__UE_TEST_GC();
}
const diag = resSvc.GetDiagnostics();
AssertEqual(diag.tsPendingRequests, 0, "tsPending back to 0");
AssertEqual(diag.nativeInFlight, 0, "nativeInFlight back to 0");
AssertEqual(diag.nativeRetainedAssets, 0, "nativeRetained back to 0");
AssertEqual(diag.nativeTotalRefCount, 0, "nativeTotalRefCount back to 0");
},
},
],
},
{
name: "UE.MiniSettingsUMG",
cases: [
{
name: "Real WBP_MiniSettings open, async icon, button click delegate, SaveGame persist, and clean baseline teardown",
fn: () => {
Assert(gameInstance !== undefined && world !== undefined, "GI & World required");
const ctx = GetGameInstanceContext(gameInstance!)!;
const uiMgr = GetPrimaryUIManager(ctx)!;
const settingSvc = ctx.GetService<SettingService>("setting")!;
const resSvc = ctx.GetService<ResourceService>("resource")!;
const uiBridge = ctx.GetService<UIDelegateBridge>("uiDelegateBridge")!;
// Ensure clean initial slot
UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true);
settingSvc.GetStore().Reload();
AssertEqual(settingSvc.GetSoundEnabled(), true, "initial sound ON");
// Attach real UWorld to context so UWidgetBlueprintLibrary.Create has a valid WorldContext
ctx.OnWorldCleanup(world);
let openedOk = false;
const win = uiMgr.ShowUI(MiniSettingsWindow, undefined, (ok) => {
openedOk = ok;
});
Assert(win !== undefined, "MiniSettingsWindow controller created");
// Pump frames for async Widget Blueprint class + icon texture load
PumpUEFrames(20, 0.02);
Assert(openedOk, "MiniSettingsWindow opened callback fired");
Assert(win!.IsLoaded(), "widget loaded");
Assert(win!.iconLoaded, "T_MiniSettingsIcon loaded and applied to ImgIcon");
Assert(win!.btnToggle !== undefined && win!.btnClose !== undefined, "named UMG buttons bound");
// Simulate real UE UButton::OnClicked broadcast
Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(win!.btnToggle), "SimulateButtonClick BtnToggle");
AssertEqual(win!.toggleClickCount, 1, "toggle click handled exactly once");
AssertEqual(settingSvc.GetSoundEnabled(), false, "sound toggled OFF");
// Wait > 0.1s for debounced SaveGame flush
PumpUEFrames(8, 0.02);
AssertEqual(settingSvc.GetStore().IsDirty(), false, "setting persisted to UE SaveGame");
// Simulate clicking Close button
Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(win!.btnClose), "SimulateButtonClick BtnClose");
Assert(win!.IsDisposed(), "MiniSettingsWindow disposed after close");
// Verify zero leaks across UIManager, UIDelegateBridge, and ResourceService
AssertEqual(uiMgr.GetDiagnostics().openWindows, 0, "openWindows back to 0");
AssertEqual(uiBridge.GetActiveBindingCount(), 0, "button delegate bindings back to 0");
AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0, "resource refcount back to 0");
// Verify cold readback from disk
const freshStore = new LocalSaveManager(new UEStorageBackend(), ctx.scheduler);
const freshSettings = new SettingService(freshStore);
AssertEqual(freshSettings.GetSoundEnabled(), false, "cold readback reads OFF");
freshSettings.Dispose();
freshStore.Dispose();
UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true);
},
},
],
},
{
name: "UE.DemoHubAndUIDemo",
cases: [
{
name: "Bootstrap DemoHubWindow loads Chinese UMG cards and cleans up with zero leaks",
fn: () => {
Assert(gameInstance !== undefined && world !== undefined, "GI & World required");
const ctx = GetGameInstanceContext(gameInstance!)!;
const uiMgr = GetPrimaryUIManager(ctx)!;
const resSvc = ctx.GetService<ResourceService>("resource")!;
const uiBridge = ctx.GetService<UIDelegateBridge>("uiDelegateBridge")!;
ctx.OnWorldCleanup(world);
let hubOpened = false;
const hub = OpenDemoHub(ctx, (ok) => {
hubOpened = ok;
});
Assert(hub !== undefined, "DemoHubWindow controller created");
PumpUEFrames(25, 0.02);
Assert(hubOpened && hub!.IsLoaded(), "DemoHubWindow loaded");
Assert(hub!.itemWidgets.length >= 1, "DemoHub dynamically populated demo cards");
Assert(hub!.itemEnterButtons["ui_demo"] !== undefined, "UI Demo entry button created");
hub!.Close();
Assert(hub!.IsDisposed(), "DemoHubWindow disposed cleanly");
AssertEqual(uiMgr.GetDiagnostics().openWindows, 0, "openWindows back to 0");
AssertEqual(uiBridge.GetActiveBindingCount(), 0, "delegate bindings back to 0");
AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0, "resource refs back to 0");
},
},
{
name: "UIDemoMainWindow exercises all UMG widgets and all 7 window types with zero leaks",
fn: () => {
Assert(gameInstance !== undefined && world !== undefined, "GI & World required");
const ctx = GetGameInstanceContext(gameInstance!)!;
const uiMgr = GetPrimaryUIManager(ctx)!;
const resSvc = ctx.GetService<ResourceService>("resource")!;
const uiBridge = ctx.GetService<UIDelegateBridge>("uiDelegateBridge")!;
ctx.OnWorldCleanup(world);
let mainOpened = false;
const mainWin = OpenUIDemoMain(ctx, (ok) => {
mainOpened = ok;
})!;
Assert(mainWin !== undefined, "UIDemoMainWindow created");
PumpUEFrames(30, 0.02);
Assert(mainOpened && mainWin.IsLoaded(), "UIDemoMainWindow loaded");
// 1. Test UMG widget delegates via real UE C++ Simulate* helpers
Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(mainWin.btnDemoAction), "Button click");
Assert(UE.ULuaUIEventSubsystem.SimulateButtonHover(mainWin.btnDemoAction, true), "Button hover");
AssertEqual(mainWin.actionClickCount, 1);
AssertEqual(mainWin.actionHovered, true);
Assert(UE.ULuaUIEventSubsystem.SimulateCheckBoxToggle(mainWin.chkFeature, true), "CheckBox toggle");
AssertEqual(mainWin.checkboxChecked, true);
Assert(UE.ULuaUIEventSubsystem.SimulateSliderValue(mainWin.sliderDemo, 0.75), "Slider value");
Assert(math.abs(mainWin.sliderValue - 0.75) < 0.001, "sliderValue updated");
Assert(UE.ULuaUIEventSubsystem.SimulateSpinBoxValue(mainWin.spinDemo, 250), "SpinBox value");
AssertEqual(mainWin.spinValue, 250);
Assert(
UE.ULuaUIEventSubsystem.SimulateEditableTextChange(mainWin.inputNickname, "星河骑士"),
"EditableText change"
);
AssertEqual(mainWin.draftNickname, "星河骑士");
Assert(
UE.ULuaUIEventSubsystem.SimulateEditableTextCommit(mainWin.inputNickname, "星河骑士", 1),
"EditableText commit"
);
AssertEqual(mainWin.currentNickname, "星河骑士");
Assert(
UE.ULuaUIEventSubsystem.SimulateComboBoxSelect(mainWin.comboTheme, "翡翠绿(稀有)"),
"ComboBox select"
);
AssertEqual(mainWin.selectedTheme, "翡翠绿(稀有)");
// 2. Test dynamic ScrollBox list items & delegate cleanup
const bindingsBeforeList = uiBridge.GetActiveBindingCount();
mainWin.AddDynamicListItems(3);
AssertEqual(mainWin.dynamicItemCount, 3, "3 dynamic items added");
Assert(uiBridge.GetActiveBindingCount() > bindingsBeforeList, "list item button delegates bound");
mainWin.ClearDynamicListItems();
AssertEqual(mainWin.dynamicItemCount, 0, "dynamic items cleared");
AssertEqual(uiBridge.GetActiveBindingCount(), bindingsBeforeList, "list item delegates fully unbound");
// 3. Test all 7 window types
// 3a. Normal singleton
const norm1 = mainWin.OpenNormalDemoWindow()!;
const norm2 = mainWin.OpenNormalDemoWindow()!;
AssertEqual(norm1, norm2, "Normal window is singleton");
// 3b. Fullscreen hides MainWindow and restores it upon close
const fullWin = mainWin.OpenFullscreenDemoWindow()!;
// 3c. Modal popup with confirm callback
let modalConfirmed = false;
const modalWin = uiMgr.ShowUI(UIDemoModalWindow, {
title: "测试弹窗",
message: "测试模态确认",
onConfirm: () => {
modalConfirmed = true;
},
})!;
// 3d. Cached window
const cachedWin = mainWin.OpenCachedDemoWindow()!;
// 3e. Multi-instance (2 distinct controllers)
const multi1 = mainWin.OpenMultiDemoWindow()!;
const multi2 = mainWin.OpenMultiDemoWindow()!;
Assert(multi1 !== multi2, "Multi-instance creates distinct windows");
// 3f. System top layer
const sysWin = mainWin.OpenSystemDemoWindow()!;
// 3g. Toast (tips layer, non-blocking, short duration)
const toastWin = mainWin.ShowToast("自动测试飘字", 0.1)!;
PumpUEFrames(30, 0.02);
// After 0.6s of pumped frames, toast (0.1s) should have auto-closed!
Assert(toastWin.IsDisposed(), "Toast auto-closed via WorldTimer");
Assert(!mainWin.IsVisible(), "MainWindow hidden while Fullscreen is open");
AssertEqual(uiMgr.GetDiagnostics().topWindowName, "UIDemoSystemWindow", "System window on top");
AssertEqual(uiMgr.GetDiagnostics().inputMode, "ui", "Input mode stays UI");
// Confirm modal
Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(modalWin.btnModalConfirm), "Click Modal Confirm");
Assert(modalConfirmed, "Modal confirm callback fired");
Assert(modalWin.IsDisposed(), "Modal disposed after confirm");
// Cached window: click -> close to cache -> reopen -> click strictly once
Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(cachedWin.btnCachedAction), "Cached click #1");
AssertEqual(cachedWin.clickCount, 1);
cachedWin.Close();
Assert(cachedWin.IsCached(), "Cached window moved to cache");
const cachedReused = mainWin.OpenCachedDemoWindow()!;
AssertEqual(cachedReused, cachedWin, "Cached window reused");
AssertEqual(cachedReused.reuseCount, 1, "OnReuseUI invoked once");
Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(cachedReused.btnCachedAction), "Cached click #2");
AssertEqual(cachedReused.clickCount, 2, "Cached click after reuse increments by exactly 1");
// Close fullscreen -> MainWindow automatically restored!
fullWin.Close();
Assert(mainWin.IsVisible(), "MainWindow automatically restored after Fullscreen closed");
// Clean teardown everything -> 0 leaks across UI, Delegates, Resources
uiMgr.CloseAll(true);
AssertEqual(uiMgr.GetDiagnostics().openWindows, 0, "openWindows back to 0");
AssertEqual(uiMgr.GetDiagnostics().cachedWindows, 0, "cachedWindows back to 0");
AssertEqual(uiBridge.GetActiveBindingCount(), 0, "delegate bindings back to 0");
AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0, "resource refcount back to 0");
// Verify unused symbol check stays clean
Assert(
DemoHubWindow !== undefined &&
UIDemoNormalWindow !== undefined &&
UIDemoFullscreenWindow !== undefined &&
UIDemoCachedWindow !== undefined &&
UIDemoMultiWindow !== undefined &&
UIDemoToastWindow !== undefined &&
UIDemoSystemWindow !== undefined,
"all demo window classes registered"
);
},
},
],
},
];
const summary = RunSuites(suites);
print(FormatReport(summary));
return summary;
}