test: add comprehensive ts2lua-unreal TS/Lua 5.4 test suites and upgrade to v0.2.2

This commit is contained in:
szy73711 committed 2026-11-29 03:35:49 +08:00
1 parent ee2e62bb34
commit 3dd61c32a9
75 files changed
+9929 -10

No files matched your search

@@ -0,0 +1,161 @@
/** @noSelfInFile */
import {
Suite,
Test,
AssertEqual,
AssertTrue,
AssertFalse,
AssertNotNil,
AssertNil,
AssertArrayEqual,
} from "../Harness/TestRunner";
import { CreateBoundInstance, ResetMockState } from "../Harness/MockUnLuaRuntime";
import * as Bootstrap from "../../Framework/Bootstrap";
import * as EventBus from "../../Framework/EventBus";
import * as HotReload from "../../Framework/HotReload";
import LuaDemoActor from "../../Game/LuaDemoActor";
export function RunHotReloadAndFrameworkTests(): void {
Suite("Extra.FrameworkAndHotReload", () => {
Test("EventBus: dedup, owner dispatch, mid-emit unsubscribe, OffAllForOwner and error isolation", () => {
EventBus.Clear();
const received: string[] = [];
interface OwnerObj {
tag: string;
OnEvent(this: OwnerObj, msg: string): void;
}
const ownerA: OwnerObj = {
tag: "A",
OnEvent(this: OwnerObj, msg: string) {
received[received.length] = `${this.tag}:${msg}`;
},
};
const ownerB: OwnerObj = {
tag: "B",
OnEvent(this: OwnerObj, msg: string) {
received[received.length] = `${this.tag}:${msg}`;
// 在回调执行期间取消自己
EventBus.Off("Test.Ping", this.OnEvent, this);
},
};
// 重复注册应自动去重
EventBus.On("Test.Ping", ownerA.OnEvent, ownerA);
EventBus.On("Test.Ping", ownerA.OnEvent, ownerA);
EventBus.On("Test.Ping", ownerB.OnEvent, ownerB);
// 注册一个会抛错的监听者,验证 EventBus 内 pcall 隔离不影响其他监听者
EventBus.On("Test.Ping", () => {
error("intentional listener error");
});
let afterErrorCalled = false;
EventBus.On("Test.Ping", () => {
afterErrorCalled = true;
});
EventBus.Emit("Test.Ping", "hello");
AssertArrayEqual(received, ["A:hello", "B:hello"]);
AssertTrue(afterErrorCalled);
// 第二次 Emit:ownerB 已自退订
EventBus.Emit("Test.Ping", "world");
AssertArrayEqual(received, ["A:hello", "B:hello", "A:world"]);
// OffAllForOwner 清理 ownerA
EventBus.OffAllForOwner(ownerA);
EventBus.Emit("Test.Ping", "ignored");
AssertArrayEqual(received, ["A:hello", "B:hello", "A:world"]);
EventBus.Clear();
});
Test("Bootstrap Init/Shutdown lifecycle and _G.GameFramework registration", () => {
const fakeGI = CreateBoundInstance<UE.ULuaGameInstance>({}, "ULuaGameInstance");
Bootstrap.Init(fakeGI);
AssertTrue(Bootstrap.IsInitialized);
AssertEqual(Bootstrap.GameInstance, fakeGI);
AssertNotNil(_G.GameFramework);
Bootstrap.Shutdown();
AssertFalse(Bootstrap.IsInitialized);
AssertNil(Bootstrap.GameInstance);
AssertNil(_G.GameFramework);
});
Test("HotReload.ReloadModule validates arguments and emits Before/After events", () => {
EventBus.Clear();
const [badOk, badErr] = HotReload.ReloadModule("");
AssertFalse(badOk);
AssertEqual(badErr, "Invalid module name");
const order: string[] = [];
EventBus.On(HotReload.EVENT_BEFORE_RELOAD, (modName: string) => {
order[order.length] = "before:" + modName;
});
EventBus.On(HotReload.EVENT_AFTER_RELOAD, (modName: string) => {
order[order.length] = "after:" + modName;
});
const [ok] = HotReload.ReloadModule("Framework.Log");
AssertTrue(ok);
AssertArrayEqual(order, ["before:Framework.Log", "after:Framework.Log"]);
EventBus.Clear();
});
Test("LuaDemoActor full integration: BeginPlay, Tick, Ping color cycle, HotReload event & EndPlay cleanup", () => {
ResetMockState();
EventBus.Clear();
let lastStatusText = "";
let colorApplyCount = 0;
let rotationAddCount = 0;
let lastVerticalOffset = 0;
const demoActor = CreateBoundInstance<LuaDemoActor>(
LuaDemoActor as unknown as Record<string, any>,
"ALuaDemoActor",
{
SpinSpeed: 90,
BobAmplitude: 20,
BobFrequency: 2,
SetStatusText(this: unknown, text: string) {
lastStatusText = text;
},
SetCubeColor(this: unknown, _color: UE.FLinearColor) {
colorApplyCount++;
},
AddCubeLocalRotation(this: unknown, _delta: UE.FRotator) {
rotationAddCount++;
},
SetCubeVerticalOffset(this: unknown, zOffset: number) {
lastVerticalOffset = zOffset;
},
}
);
demoActor.ReceiveBeginPlay();
AssertEqual(colorApplyCount, 1);
AssertTrue(string.find(lastStatusText, "Pings: 0", 1, true)[0] !== undefined);
demoActor.ReceiveTick(0.25);
AssertEqual(rotationAddCount, 1);
AssertTrue(lastVerticalOffset !== 0);
EventBus.Emit("Demo.Ping", "TestSuite");
AssertEqual(colorApplyCount, 2);
AssertTrue(string.find(lastStatusText, "Pings: 1", 1, true)[0] !== undefined);
EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, "Game.LuaDemoActor");
AssertTrue(string.find(lastStatusText, "Reloads: 1", 1, true)[0] !== undefined);
// EndPlay 后不再响应 EventBus
demoActor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
EventBus.Emit("Demo.Ping", "AfterEndPlay");
AssertEqual(colorApplyCount, 2);
EventBus.Clear();
});
});
}
@@ -0,0 +1,83 @@
/** @noSelfInFile */
import {
Suite,
Test,
AssertEqual,
AssertTrue,
AssertFalse,
AssertNil,
AssertArrayEqual,
} from "../Harness/TestRunner";
import {
AdvanceMockTime,
CreateBoundInstance,
GetMockState,
ResetMockState,
} from "../Harness/MockUnLuaRuntime";
import * as EventBus from "../../Framework/EventBus";
import LifecycleSafetyActor from "./LifecycleSafetyActor";
export function RunLifecycleAndMemoryTests(): void {
Suite("Extra.LifecycleAndMemorySafety", () => {
Test("multiple @unlua instances maintain isolated state (no shared class-table arrays)", () => {
ResetMockState();
EventBus.Clear();
const cls = LifecycleSafetyActor as unknown as Record<string, any>;
const a = CreateBoundInstance<LifecycleSafetyActor>(cls, "AActor");
const b = CreateBoundInstance<LifecycleSafetyActor>(cls, "AActor");
a.ReceiveBeginPlay();
b.ReceiveBeginPlay();
a.PushItem("only_in_a");
b.PushItem("only_in_b");
AssertArrayEqual(a.GetItems(), ["only_in_a"]);
AssertArrayEqual(b.GetItems(), ["only_in_b"]);
a.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
b.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
EventBus.Clear();
});
Test("paired cleanup on ReceiveEndPlay prevents leaked EventBus, Delegate, Timer & manual Ref", () => {
ResetMockState();
EventBus.Clear();
const actor = CreateBoundInstance<LifecycleSafetyActor>(
LifecycleSafetyActor as unknown as Record<string, any>,
"AActor"
);
const asset = UE.UObject.Load("/Game/Data/DA_Config.DA_Config")!;
const weak = UE.FWeakObjectPtr();
weak.Set(actor);
actor.ReceiveBeginPlay();
actor.HoldManualRef(asset);
AssertEqual(GetMockState().manualRefs.get(asset as unknown as object), 1);
EventBus.Emit("Lifecycle.Broadcast", "msg1");
actor.OnTakeAnyDamage.Broadcast(actor, 25, undefined, undefined, undefined);
AdvanceMockTime(1.0);
AssertEqual(actor.GetReceivedEvents(), 3);
AssertTrue(weak.IsValid());
// 触发 EndPlay 与销毁
actor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed);
actor.K2_DestroyActor();
AssertFalse(actor.OnTakeAnyDamage.IsBound());
AssertFalse(weak.IsValid());
AssertNil(weak.Get());
AssertNil(GetMockState().manualRefs.get(asset as unknown as object));
// 销毁后再次广播事件/推进时间,计数不应再增长
EventBus.Emit("Lifecycle.Broadcast", "msg2");
AdvanceMockTime(3.0);
AssertEqual(actor.GetReceivedEvents(), 3);
EventBus.Clear();
});
});
}
@@ -0,0 +1,78 @@
import * as EventBus from "../../Framework/EventBus";
/**
* 演示多实例隔离、配对清理(EventBus + Delegate + Timer + UnLua.Ref)与销毁后安全防护的 @unlua Actor。
*/
@unlua
export default class LifecycleSafetyActor extends UE.AActor {
private items!: string[];
private receivedEvents!: number;
private timerHandle!: UE.FTimerHandle;
private keptRef!: UE.UObject | undefined;
ReceiveBeginPlay(): void {
super.ReceiveBeginPlay();
// 每个实例独立初始化,严禁类字段初始化导致多实例共享表
this.items = [];
this.receivedEvents = 0;
EventBus.On("Lifecycle.Broadcast", this.OnBroadcast, this);
this.OnTakeAnyDamage.Add(this, this.OnDamaged);
this.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate(
UnLua.Delegate(this, this.OnHeartbeat),
1.0,
true
);
}
PushItem(item: string): void {
this.items[this.items.length] = item;
}
GetItems(): string[] {
return this.items;
}
HoldManualRef(asset: UE.UObject): void {
this.keptRef = asset;
UnLua.Ref(asset);
}
OnBroadcast(tag: string): void {
if (!UE.UKismetSystemLibrary.IsValid(this)) return;
this.receivedEvents++;
this.items[this.items.length] = tag;
}
OnDamaged(
_DamagedActor: UE.AActor | undefined,
Damage: number,
_DamageType: UE.UDamageType | undefined,
_InstigatedBy: UE.AController | undefined,
_DamageCauser: UE.AActor | undefined
): void {
if (!UE.UKismetSystemLibrary.IsValid(this)) return;
this.receivedEvents++;
this.items[this.items.length] = `dmg:${Damage}`;
}
OnHeartbeat(): void {
if (!UE.UKismetSystemLibrary.IsValid(this)) return;
this.receivedEvents++;
}
GetReceivedEvents(): number {
return this.receivedEvents;
}
ReceiveEndPlay(EndPlayReason: UE.EEndPlayReason): void {
EventBus.OffAllForOwner(this);
this.OnTakeAnyDamage.Remove(this, this.OnDamaged);
UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(this, this.timerHandle);
if (this.keptRef !== undefined) {
UnLua.Unref(this.keptRef);
this.keptRef = undefined;
}
super.ReceiveEndPlay(EndPlayReason);
}
}
@@ -0,0 +1,142 @@
/** @noSelfInFile */
import {
Suite,
Test,
AssertEqual,
AssertTrue,
AssertFalse,
AssertNear,
AssertArrayEqual,
} from "../Harness/TestRunner";
function EscapeLuaPattern(literal: string): string {
const [escaped] = string.gsub(literal, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1");
return escaped;
}
function DeepCloneTable<T>(src: T, seen?: LuaTable<object, unknown>): T {
if (type(src) !== "table") {
return src;
}
const visited = seen ?? new LuaTable<object, unknown>();
const existing = visited.get(src as unknown as object);
if (existing !== undefined) {
return existing as T;
}
const copy: Record<any, any> = {};
visited.set(src as unknown as object, copy);
for (const [k, v] of pairs(src as unknown as Record<any, any>)) {
copy[DeepCloneTable(k, visited)] = DeepCloneTable(v, visited);
}
return copy as T;
}
export function RunLua54PitfallsTests(): void {
Suite("Extra.Lua54PitfallsAndEdgeCases", () => {
Test("Lua truthiness vs JS: explicit checks for 0 and empty string, ?? vs ||", () => {
const zero = 0;
const empty = "";
// 在 Lua 中 0 和 "" 均为 truthy!业务代码必须使用显式比较
AssertTrue(zero === 0);
AssertTrue(empty === "");
AssertTrue((zero as unknown as boolean) ? true : false);
AssertTrue((empty as unknown as boolean) ? true : false);
// ?? 在 TSTL 中安全地仅判断 == nil,不会误替换 0 / "" / false
const optZero: number | undefined = 0;
const optEmpty: string | undefined = "";
const optFalse: boolean | undefined = false;
const optNil: number | undefined = undefined;
AssertEqual(optZero ?? 100, 0);
AssertEqual(optEmpty ?? "fallback", "");
AssertEqual(optFalse ?? true, false);
AssertEqual(optNil ?? 100, 100);
});
Test("Lua 5.4 UTF-8 character counting for CJK game text vs byte length", () => {
const cnText = "你好UE5世界";
// UTF-8 字节数: 4 个汉字 * 3 + 3 ASCII = 15
AssertEqual(cnText.length, 15);
// utf8.len 返回 Unicode 码点数 = 7
const charCount = utf8.len(cnText);
AssertEqual(charCount, 7);
// utf8.codepoint 提取全部码点
const codes = [...utf8.codepoint(cnText, 1, -1)];
AssertEqual(codes.length, 7);
AssertEqual(codes[0], 0x4f60); // '你'
AssertEqual(codes[2], 85); // 'U'
});
Test("Lua pattern magic character escaping for literal search & replace", () => {
const raw = "Item[Epic]+10 (50.5%)";
const escaped = EscapeLuaPattern("[Epic]+10 (50.5%)");
const [startIdx] = string.find(raw, escaped);
AssertTrue(startIdx !== undefined);
// 注意:string.gsub 的 replacement 字符串中字面量 % 同样需要转义为 %%
const [replaced] = string.gsub(raw, EscapeLuaPattern("(50.5%)"), "(100%%)");
AssertEqual(replaced, "Item[Epic]+10 (100%)");
});
Test("0-based TS array vs 1-based UE.TArray interop without sparse holes", () => {
const tsArr: string[] = ["first", "second", "third"];
const ueArr = UE.TArray<string>(UE.FString);
for (let i = 0; i < tsArr.length; i++) {
ueArr.Add(tsArr[i]);
}
AssertEqual(ueArr.Length(), tsArr.length);
AssertEqual(ueArr.Get(1), tsArr[0]);
AssertEqual(ueArr.Get(3), tsArr[2]);
// Swap-remove O(1) 删除保持紧凑数组无空洞
const dense = [10, 20, 30, 40];
const removeIdx = 1; // 移除 20
dense[removeIdx] = dense[dense.length - 1];
table.remove(dense);
AssertEqual(dense.length, 3);
AssertArrayEqual(dense, [10, 40, 30]);
});
Test("deep clone plain tables safely including circular references", () => {
interface Node {
name: string;
tags: string[];
selfRef?: Node;
}
const original: Node = { name: "Root", tags: ["a", "b"] };
original.selfRef = original;
const cloned = DeepCloneTable(original);
AssertEqual(cloned.name, "Root");
AssertArrayEqual(cloned.tags, ["a", "b"]);
AssertTrue(cloned !== original);
AssertTrue(cloned.tags !== original.tags);
AssertEqual(cloned.selfRef, cloned);
cloned.tags.push("c");
AssertEqual(original.tags.length, 2);
AssertEqual(cloned.tags.length, 3);
});
Test("zero-GC hot-path Tick simulation with cached FVector/FRotator (10,000 frames)", () => {
const pos = UE.FVector(0, 0, 0);
const vel = UE.FVector(10, 20, -5);
const dt = 0.016;
for (let frame = 0; frame < 10000; frame++) {
pos.X += vel.X * dt;
pos.Y += vel.Y * dt;
pos.Z += vel.Z * dt;
}
AssertNear(pos.X, 1600, 0.1);
AssertNear(pos.Y, 3200, 0.1);
AssertNear(pos.Z, -800, 0.1);
});
});
}