chore: upgrade ts2lua-unreal to v0.3.1 with lowercase lib/module.lua & lib/class.lua and commit framework refactor

This commit is contained in:
szy73711 committed 2026-11-30 03:43:42 +08:00
1 parent 783dccf53d
commit 3572f2da43
206 files changed
+14442 -13186

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
local ____exports = __module.env
function ____exports.Assert(condition, message)
if not condition then
error(message or "Assertion failed", 2)
end
end
function ____exports.AssertEqual(actual, expected, label)
if actual ~= expected then
local prefix = label ~= nil and label .. ": " or ""
error(
string.format(
"%sexpected %s, got %s",
prefix,
tostring(expected),
tostring(actual)
),
2
)
end
end
function ____exports.AssertNotEqual(actual, unexpected, label)
if actual == unexpected then
local prefix = label ~= nil and label .. ": " or ""
error(
string.format(
"%sexpected value different from %s",
prefix,
tostring(unexpected)
),
2
)
end
end
function ____exports.AssertNear(actual, expected, epsilon, label)
if math.abs(actual - expected) > epsilon then
local prefix = label ~= nil and label .. ": " or ""
error(
string.format(
"%sexpected %s (+/- %s), got %s",
prefix,
tostring(expected),
tostring(epsilon),
tostring(actual)
),
2
)
end
end
function ____exports.AssertArrayEqual(actual, expected, label)
local prefix = label ~= nil and label .. ": " or ""
if #actual ~= #expected then
error(
string.format("%sarray length mismatch: expected %d, got %d", prefix, #expected, #actual),
2
)
end
do
local i = 0
while i < #expected do
if actual[i + 1] ~= expected[i + 1] then
error(
string.format(
"%sarray[%d] mismatch: expected %s, got %s",
prefix,
i,
tostring(expected[i + 1]),
tostring(actual[i + 1])
),
2
)
end
i = i + 1
end
end
end
function ____exports.RunSuites(suites)
local summary = {total = 0, passed = 0, failed = 0, failures = {}}
do
local s = 0
while s < #suites do
local suite = suites[s + 1]
do
local c = 0
while c < #suite.cases do
local testCase = suite.cases[c + 1]
summary.total = summary.total + 1
local ok, err = xpcall(testCase.fn, debug.traceback)
if ok then
summary.passed = summary.passed + 1
else
summary.failed = summary.failed + 1
summary.failures[#summary.failures + 1] = {
suite = suite.name,
name = testCase.name,
error = tostring(err)
}
end
c = c + 1
end
end
s = s + 1
end
end
return summary
end
function ____exports.FormatReport(summary)
local lines = {}
lines[#lines + 1] = string.format("=== Test Summary: %d/%d passed (%d failed) ===", summary.passed, summary.total, summary.failed)
do
local i = 0
while i < #summary.failures do
local f = summary.failures[i + 1]
lines[#lines + 1] = string.format("[FAIL] %s :: %s\n%s", f.suite, f.name, f.error)
i = i + 1
end
end
return table.concat(lines, "\n")
end
function __module.UpdateImports()
end
+39
View File
@@ -0,0 +1,39 @@
local ____exports = __module.env
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local FormatReport = M__tests_harness_test_runner.FormatReport
local RunSuites = M__tests_harness_test_runner.RunSuites
local M__tests_unit_context_and_mgr_test = __MODULE__.Import("tests.unit.context_and_mgr_test", __module)
local CreateContextAndMgrSuite = M__tests_unit_context_and_mgr_test.CreateContextAndMgrSuite
local M__tests_unit_event_hub_test = __MODULE__.Import("tests.unit.event_hub_test", __module)
local CreateEventHubSuite = M__tests_unit_event_hub_test.CreateEventHubSuite
local M__tests_unit_scheduler_test = __MODULE__.Import("tests.unit.scheduler_test", __module)
local CreateSchedulerSuite = M__tests_unit_scheduler_test.CreateSchedulerSuite
local M__tests_unit_smoke_test = __MODULE__.Import("tests.unit.smoke_test", __module)
local CreateSmokeSuite = M__tests_unit_smoke_test.CreateSmokeSuite
local M__tests_unit_storage_and_setting_test = __MODULE__.Import("tests.unit.storage_and_setting_test", __module)
local CreateStorageAndSettingSuite = M__tests_unit_storage_and_setting_test.CreateStorageAndSettingSuite
local M__tests_unit_ui_and_resource_test = __MODULE__.Import("tests.unit.ui_and_resource_test", __module)
local CreateUIAndResourceSuite = M__tests_unit_ui_and_resource_test.CreateUIAndResourceSuite
function ____exports.RunAllUnitTests()
local suites = {
CreateSmokeSuite(),
CreateEventHubSuite(),
CreateSchedulerSuite(),
CreateContextAndMgrSuite(),
CreateStorageAndSettingSuite(),
CreateUIAndResourceSuite()
}
local summary = RunSuites(suites)
print(FormatReport(summary))
return summary
end
function __module.UpdateImports()
FormatReport = M__tests_harness_test_runner.FormatReport
RunSuites = M__tests_harness_test_runner.RunSuites
CreateContextAndMgrSuite = M__tests_unit_context_and_mgr_test.CreateContextAndMgrSuite
CreateEventHubSuite = M__tests_unit_event_hub_test.CreateEventHubSuite
CreateSchedulerSuite = M__tests_unit_scheduler_test.CreateSchedulerSuite
CreateSmokeSuite = M__tests_unit_smoke_test.CreateSmokeSuite
CreateStorageAndSettingSuite = M__tests_unit_storage_and_setting_test.CreateStorageAndSettingSuite
CreateUIAndResourceSuite = M__tests_unit_ui_and_resource_test.CreateUIAndResourceSuite
end
+410
View File
@@ -0,0 +1,410 @@
local ____lualib = require("lualib_bundle")
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module)
local GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext
local Json = __MODULE__.Import("framework.core.json", __module)
local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module)
local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS
local BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS
local M__framework_storage_local_save = __MODULE__.Import("framework.storage.local_save", __module)
local LocalSaveManager = M__framework_storage_local_save.LocalSaveManager
local M__framework_storage_storage_backend = __MODULE__.Import("framework.storage.storage_backend", __module)
local UEStorageBackend = M__framework_storage_storage_backend.UEStorageBackend
local M__game_setting_mini_settings_window = __MODULE__.Import("game.setting.mini_settings_window", __module)
local MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow
local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module)
local SettingService = M__game_setting_setting_service.SettingService
local M__game_startup = __MODULE__.Import("game.startup", __module)
local GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local Assert = M__tests_harness_test_runner.Assert
local AssertEqual = M__tests_harness_test_runner.AssertEqual
local FormatReport = M__tests_harness_test_runner.FormatReport
local RunSuites = M__tests_harness_test_runner.RunSuites
local function PumpUEFrames(frames, dt)
if dt == nil then
dt = 0.02
end
if __UE_TEST_TICK == nil then
return
end
do
local i = 0
while i < frames do
__UE_TEST_TICK(dt)
i = i + 1
end
end
end
function ____exports.RunAllUETests(gameInstance, world)
local suites = {
{
name = "UE.NativeJson",
cases = {{
name = "ue_json native C++ module is active and preserves 64-bit integers and UTF-8",
fn = function()
Assert(
Json.IsNativeBackend(),
"expected native ue_json backend inside UE"
)
local bigInt = tonumber("9007199254740993")
AssertEqual(
math.type(bigInt),
"integer",
"bigInt is Lua 5.4 integer"
)
local input = {
version = 2,
roleId = bigInt,
title = "UE5.8中文测试",
enabled = true,
list = {10, 20, 30},
empty = Json.GetEmptyArray()
}
local encoded, encErr = Json.Encode(input)
AssertEqual(encErr, nil, "encode error")
Assert(
type(encoded) == "string",
"encoded string"
)
local decoded, decErr = Json.Decode(encoded)
AssertEqual(decErr, nil, "decode error")
local obj = decoded
AssertEqual(obj.version, 2)
AssertEqual(obj.roleId, bigInt, "int64 lossless round-trip")
AssertEqual(obj.title, "UE5.8中文测试")
AssertEqual(obj.enabled, true)
local list = obj.list
AssertEqual(list[1], 10)
AssertEqual(list[3], 30)
local badVal, badErr = Json.Decode("{broken")
AssertEqual(badVal, nil)
Assert(badErr ~= nil and badErr ~= "", "malformed JSON returns error")
end
}}
},
{
name = "UE.LocalStorage",
cases = {{
name = "ULuaStorageLibrary + ULuaSaveGame: debounce save, cold-start readback, and corruption recovery",
fn = function()
Assert(gameInstance ~= nil, "gameInstance required")
local ctx = GetGameInstanceContext(gameInstance)
Assert(ctx ~= nil, "GameInstanceContext must be initialized")
local slotId = "ue_test_slot"
local fullSlotName = "sdata_" .. slotId
UE.ULuaStorageLibrary.DeleteSlot(fullSlotName, 0, true)
local backend = __TS__New(UEStorageBackend)
local saveMgr = __TS__New(LocalSaveManager, backend, ctx.scheduler)
local settings = __TS__New(SettingService, saveMgr, slotId)
AssertEqual(
settings:GetStore():GetLastLoadStatus(),
"not_found"
)
AssertEqual(
settings:GetSoundEnabled(),
true,
"missing slot returns default"
)
settings:SetSoundEnabled(false)
PumpUEFrames(8, 0.02)
AssertEqual(
settings:GetStore():IsDirty(),
false,
"debounced save flushed to UE SaveGame"
)
Assert(
UE.ULuaStorageLibrary.DoesSlotExist(fullSlotName, 0),
"SaveGame file created on disk"
)
settings:SetSoundEnabled(true)
AssertEqual(
settings:Flush(),
"ok"
)
settings:Dispose()
saveMgr:Dispose()
local saveMgr2 = __TS__New(LocalSaveManager, backend, ctx.scheduler)
local settings2 = __TS__New(SettingService, saveMgr2, slotId)
AssertEqual(
settings2:GetStore():GetLastLoadStatus(),
"ok"
)
AssertEqual(
settings2:GetSoundEnabled(),
true,
"cold-start reads latest value"
)
settings2:Dispose()
saveMgr2:Dispose()
Assert(
UE.ULuaStorageLibrary.WriteCorruptRawSlotForTest(fullSlotName, "CORRUPTED_SAV_DATA", 0),
"corrupt injection succeeded"
)
local saveMgr3 = __TS__New(LocalSaveManager, backend, ctx.scheduler)
local settings3 = __TS__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)
end
}}
},
{
name = "UE.ResourceManager",
cases = {{
name = "ULuaResourceSubsystem: PIE Content load, PatchManifest override, coalesced cancel, and GC ref-count",
fn = function()
Assert(gameInstance ~= nil, "gameInstance required")
local ctx = GetGameInstanceContext(gameInstance)
local resSvc = ctx:GetService("resource")
local sub = UE.ULuaResourceSubsystem.GetFromGameInstance(gameInstance)
Assert(resSvc ~= nil and sub ~= nil, "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(
not resSvc:DoesAssetExist("/Game/DoesNotExist/MissingAsset"),
"missing asset returns false"
)
local 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"
)
local owner1 = __TS__New(ScopedObject)
local owner2 = __TS__New(ScopedObject)
local owner3 = __TS__New(ScopedObject)
local tex1
local tex2
local cancelledFired = false
local widgetCls
local missingCalls = 0
local missingOk = true
resSvc:LoadTextureAsync(
ASSET_KEYS.MINI_SETTINGS_ICON,
owner1,
function(ok, asset)
if ok then
tex1 = asset
end
end
)
local hCancel = resSvc:LoadTextureAsync(
aliasKey,
owner3,
function()
cancelledFired = true
end
)
resSvc:LoadTextureAsync(
aliasKey,
owner2,
function(ok, asset)
if ok then
tex2 = asset
end
end
)
resSvc:LoadClassAsync(
ASSET_KEYS.MINI_SETTINGS_WIDGET,
owner1,
function(ok, cls)
if ok then
widgetCls = cls
end
end
)
resSvc:LoadObjectAsync(
"/Game/DoesNotExist/MissingAsset",
owner1,
function(ok)
missingCalls = missingCalls + 1
missingOk = ok
end
)
hCancel:Cancel()
PumpUEFrames(15, 0.02)
Assert(not cancelledFired, "cancelled caller must not receive callback")
Assert(
tex1 ~= nil and UE.UKismetSystemLibrary.IsValid(tex1),
"tex1 loaded & valid"
)
Assert(
tex2 ~= nil and UE.UKismetSystemLibrary.IsValid(tex2),
"tex2 loaded & valid"
)
Assert(
widgetCls ~= nil and UE.UKismetSystemLibrary.IsValid(widgetCls),
"WBP_MiniSettings class loaded"
)
AssertEqual(missingCalls, 1, "missing asset delivers exactly once")
AssertEqual(missingOk, false, "missing asset reports ok=false")
owner1:Dispose()
if __UE_TEST_GC ~= nil then
__UE_TEST_GC()
end
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"
)
owner2:Dispose()
owner3:Dispose()
sub:ClearPatchManifest()
if __UE_TEST_GC ~= nil then
__UE_TEST_GC()
end
local 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")
end
}}
},
{
name = "UE.MiniSettingsUMG",
cases = {{
name = "Real WBP_MiniSettings open, async icon, button click delegate, SaveGame persist, and clean baseline teardown",
fn = function()
Assert(gameInstance ~= nil and world ~= nil, "GI & World required")
local ctx = GetGameInstanceContext(gameInstance)
local uiMgr = GetPrimaryUIManager(ctx)
local settingSvc = ctx:GetService("setting")
local resSvc = ctx:GetService("resource")
local uiBridge = ctx:GetService("uiDelegateBridge")
UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true)
settingSvc:GetStore():Reload()
AssertEqual(
settingSvc:GetSoundEnabled(),
true,
"initial sound ON"
)
ctx:OnWorldCleanup(world)
local openedOk = false
local win = uiMgr:ShowUI(
MiniSettingsWindow,
nil,
function(ok)
openedOk = ok
end
)
Assert(win ~= nil, "MiniSettingsWindow controller created")
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 ~= nil and win.btnClose ~= nil, "named UMG buttons bound")
Assert(
UE.ULuaUIEventSubsystem.SimulateButtonClick(win.btnToggle),
"SimulateButtonClick BtnToggle"
)
AssertEqual(win.toggleClickCount, 1, "toggle click handled exactly once")
AssertEqual(
settingSvc:GetSoundEnabled(),
false,
"sound toggled OFF"
)
PumpUEFrames(8, 0.02)
AssertEqual(
settingSvc:GetStore():IsDirty(),
false,
"setting persisted to UE SaveGame"
)
Assert(
UE.ULuaUIEventSubsystem.SimulateButtonClick(win.btnClose),
"SimulateButtonClick BtnClose"
)
Assert(
win:IsDisposed(),
"MiniSettingsWindow disposed after close"
)
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"
)
local freshStore = __TS__New(
LocalSaveManager,
__TS__New(UEStorageBackend),
ctx.scheduler
)
local freshSettings = __TS__New(SettingService, freshStore)
AssertEqual(
freshSettings:GetSoundEnabled(),
false,
"cold readback reads OFF"
)
freshSettings:Dispose()
freshStore:Dispose()
UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true)
end
}}
}
}
local summary = RunSuites(suites)
print(FormatReport(summary))
return summary
end
function __module.UpdateImports()
GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext
ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS
BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS
LocalSaveManager = M__framework_storage_local_save.LocalSaveManager
UEStorageBackend = M__framework_storage_storage_backend.UEStorageBackend
MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow
SettingService = M__game_setting_setting_service.SettingService
GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager
ScopedObject = M__share_base_scoped_object.ScopedObject
Assert = M__tests_harness_test_runner.Assert
AssertEqual = M__tests_harness_test_runner.AssertEqual
FormatReport = M__tests_harness_test_runner.FormatReport
RunSuites = M__tests_harness_test_runner.RunSuites
end
@@ -0,0 +1,188 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module)
local GameInstanceContext = M__framework_context_game_context.GameInstanceContext
local M__framework_module_mgr_base = __MODULE__.Import("framework.module.mgr_base", __module)
local ControllerBase = M__framework_module_mgr_base.ControllerBase
local MgrBase = M__framework_module_mgr_base.MgrBase
local MgrDataBase = M__framework_module_mgr_base.MgrDataBase
local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module)
local EventHub = M__share_event_event_hub.EventHub
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local Assert = M__tests_harness_test_runner.Assert
local AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual
local AssertEqual = M__tests_harness_test_runner.AssertEqual
local SampleData = __TS__DefineClass("SampleData", __module)
SampleData.name = "SampleData"
__TS__ClassExtends(SampleData, MgrDataBase)
function SampleData.prototype.____constructor(self, ...)
MgrDataBase.prototype.____constructor(self, ...)
self.value = 0
self.disposed = false
end
function SampleData.prototype.Dispose(self)
self.disposed = true
end
local SampleSubController = __TS__DefineClass("SampleSubController", __module)
SampleSubController.name = "SampleSubController"
__TS__ClassExtends(SampleSubController, ControllerBase)
function SampleSubController.prototype.____constructor(self, ...)
ControllerBase.prototype.____constructor(self, ...)
self.events = {}
end
function SampleSubController.prototype.OnEnter(self)
self.events[#self.events + 1] = "enter"
end
function SampleSubController.prototype.OnActive(self)
self.events[#self.events + 1] = "active"
end
function SampleSubController.prototype.OnExit(self)
self.events[#self.events + 1] = "exit"
end
local SampleMgr = __TS__DefineClass("SampleMgr", __module)
SampleMgr.name = "SampleMgr"
__TS__ClassExtends(SampleMgr, MgrBase)
function SampleMgr.prototype.____constructor(self, ...)
MgrBase.prototype.____constructor(self, ...)
self.lifecycle = {}
end
function SampleMgr.prototype.OnCreate(self)
self.lifecycle[#self.lifecycle + 1] = "create"
end
function SampleMgr.prototype.OnBindControllers(self)
self.subCtrl = self:AddController(SampleSubController)
end
function SampleMgr.prototype.OnBindEvents(self)
self.lifecycle[#self.lifecycle + 1] = "bind"
end
function SampleMgr.prototype.OnClean(self)
self.lifecycle[#self.lifecycle + 1] = "clean"
end
function ____exports.CreateContextAndMgrSuite()
return {
name = "Step1.ContextAndMgr",
cases = {
{
name = "MgrRegistry creates, looks up by ctor and name, and cleans both indexes on DelMgr",
fn = function()
local ctx = __TS__New(GameInstanceContext)
local mgr = ctx.mgrRegistry:CreateMgr(SampleMgr, "SampleMgr")
local data = ctx.mgrRegistry:CreateMgrData(SampleData)
data.value = 123
AssertEqual(
ctx.mgrRegistry:GetMgr(SampleMgr),
mgr
)
AssertEqual(
ctx.mgrRegistry:GetMgrByName("SampleMgr"),
mgr
)
AssertEqual(
ctx.mgrRegistry:GetMgrData(SampleData),
data
)
AssertArrayEqual(mgr.lifecycle, {"create", "bind"})
Assert(mgr.subCtrl ~= nil, "sub controller attached")
AssertArrayEqual(mgr.subCtrl.events, {"enter", "active"})
ctx.mgrRegistry:DelMgr(SampleMgr)
AssertEqual(
ctx.mgrRegistry:GetMgr(SampleMgr),
nil
)
AssertEqual(
ctx.mgrRegistry:GetMgrByName("SampleMgr"),
nil,
"name index must be cleared"
)
Assert(
mgr:IsDisposed(),
"mgr disposed"
)
AssertArrayEqual(mgr.lifecycle, {"create", "bind", "clean"})
AssertArrayEqual(mgr.subCtrl.events, {"enter", "active", "exit"})
ctx:Dispose()
Assert(data.disposed, "data disposed with context")
end
},
{
name = "Two GameInstanceContexts coexist in one Lua VM; disposing #1 keeps #2 intact",
fn = function()
local ctx1 = __TS__New(GameInstanceContext)
local ctx2 = __TS__New(GameInstanceContext)
local hub1 = __TS__New(EventHub, "Hub1")
local hub2 = __TS__New(EventHub, "Hub2")
ctx1:RegisterService("bizHub", hub1)
ctx2:RegisterService("bizHub", hub2)
local mgr1 = ctx1.mgrRegistry:CreateMgr(SampleMgr, "SampleMgr")
local mgr2 = ctx2.mgrRegistry:CreateMgr(SampleMgr, "SampleMgr")
local log1 = {}
local log2 = {}
hub1.on.Notify(
function(msg)
log1[#log1 + 1] = msg
end,
mgr1
)
hub2.on.Notify(
function(msg)
log2[#log2 + 1] = msg
end,
mgr2
)
ctx1.scheduler:AddMonotonicRepeatTimer(
0.05,
function()
log1[#log1 + 1] = "tick1"
end,
mgr1
)
ctx2.scheduler:AddMonotonicRepeatTimer(
0.05,
function()
log2[#log2 + 1] = "tick2"
end,
mgr2
)
local shutdownOrder = {}
ctx1:AddShutdownHook(function()
shutdownOrder[#shutdownOrder + 1] = "hook1"
end)
ctx1:AddShutdownHook(function()
shutdownOrder[#shutdownOrder + 1] = "hook2"
end)
ctx1:Dispose()
AssertArrayEqual(shutdownOrder, {"hook2", "hook1"}, "shutdown hooks run in reverse order")
Assert(
mgr1:IsDisposed(),
"mgr1 disposed"
)
Assert(
not mgr2:IsDisposed(),
"mgr2 still alive"
)
hub2.emit.Notify("alive")
ctx2:Tick(0.06)
AssertArrayEqual(log1, {})
AssertArrayEqual(log2, {"alive", "tick2"})
ctx2:Dispose()
Assert(
mgr2:IsDisposed(),
"mgr2 disposed cleanly"
)
end
}
}
}
end
function __module.UpdateImports()
GameInstanceContext = M__framework_context_game_context.GameInstanceContext
ControllerBase = M__framework_module_mgr_base.ControllerBase
MgrBase = M__framework_module_mgr_base.MgrBase
MgrDataBase = M__framework_module_mgr_base.MgrDataBase
EventHub = M__share_event_event_hub.EventHub
Assert = M__tests_harness_test_runner.Assert
AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual
AssertEqual = M__tests_harness_test_runner.AssertEqual
end
+216
View File
@@ -0,0 +1,216 @@
local ____lualib = require("lualib_bundle")
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module)
local SetupTracebackHandler = M__share_base_traceback.SetupTracebackHandler
local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module)
local EventHub = M__share_event_event_hub.EventHub
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local Assert = M__tests_harness_test_runner.Assert
local AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual
local AssertEqual = M__tests_harness_test_runner.AssertEqual
function ____exports.CreateEventHubSuite()
return {
name = "Step1.EventHub",
cases = {
{
name = "Duplicate (emitter, event, owner) subscription replaces previous listener",
fn = function()
local hub = __TS__New(EventHub, "DupTest")
local owner = __TS__New(ScopedObject)
local log = {}
hub.on.Ping(
function(a)
log[#log + 1] = "old:" .. tostring(a)
end,
owner
)
hub.on.Ping(
function(a)
log[#log + 1] = "new:" .. tostring(a)
end,
owner
)
AssertEqual(
hub:GetListenerCount("Ping"),
1,
"listener count"
)
hub.emit.Ping(42)
AssertArrayEqual(log, {"new:42"})
owner:Dispose()
AssertEqual(
hub:GetListenerCount("Ping"),
0,
"after dispose"
)
hub:Dispose()
end
},
{
name = "Callback receives exact event args (no owner prepended) and respects Enable/Disable/OffAll",
fn = function()
local hub = __TS__New(EventHub, "ArgsTest")
local owner = __TS__New(ScopedObject)
local received = {}
hub.on.Ping(
function(a, b, c)
received[#received + 1] = string.format(
"%s|%s|%s",
tostring(a),
tostring(b),
tostring(c)
)
end,
owner
)
hub.emit.Ping(7, "hello", 9)
owner:DisableAllEventListeners()
hub.emit.Ping(8, "skip", 10)
owner:EnableAllEventListeners()
hub.emit.Ping(11, nil, 13)
owner:OffAllEventListeners()
hub.emit.Ping(99, "gone")
AssertArrayEqual(received, {"7|hello|9", "11|nil|13"})
hub:Dispose()
end
},
{
name = "Cancelling next listener or disposing next owner during dispatch skips it immediately",
fn = function()
local subB
local hub = __TS__New(EventHub, "MutationTest")
local ownerA = __TS__New(ScopedObject)
local ownerB = __TS__New(ScopedObject)
local ownerC = __TS__New(ScopedObject)
local order = {}
local listenerB = hub.on.Ping(
function()
order[#order + 1] = "B"
end,
ownerB
)
listenerB:Off()
hub.on.Ping(
function()
order[#order + 1] = "A"
subB:Off()
ownerC:Dispose()
end,
ownerA
)
subB = hub.on.Ping(
function()
order[#order + 1] = "B"
end,
ownerB
)
hub.on.Ping(
function()
order[#order + 1] = "C"
end,
ownerC
)
hub.emit.Ping(1)
AssertArrayEqual(order, {"A"})
ownerA:Dispose()
ownerB:Dispose()
hub:Dispose()
end
},
{
name = "Nested Emit and listener error isolation",
fn = function()
local capturedErrors = {}
SetupTracebackHandler({DumpTraceback = function(msg)
capturedErrors[#capturedErrors + 1] = msg
end})
local hub = __TS__New(EventHub, "NestedTest")
local ownerA = __TS__New(ScopedObject)
local ownerB = __TS__New(ScopedObject)
local order = {}
hub.on.Chain(
function(step)
order[#order + 1] = "A:" .. tostring(step)
if step == 1 then
hub.emit.Chain(2)
end
if step == 2 then
error("boom-in-listener")
end
end,
ownerA
)
hub.on.Chain(
function(step)
order[#order + 1] = "B:" .. tostring(step)
end,
ownerB
)
hub.emit.Chain(1)
SetupTracebackHandler(nil)
AssertArrayEqual(order, {"A:1", "A:2", "B:2", "B:1"})
Assert(#capturedErrors == 1, "expected 1 isolated error")
ownerA:Dispose()
ownerB:Dispose()
hub:Dispose()
end
},
{
name = "preEmit and asyncEmit preserve trailing nil via table.pack.n",
fn = function()
local pending = {}
local preCalls = {}
local hub = __TS__New(
EventHub,
"AsyncTest",
{
preEmit = function(evName)
preCalls[#preCalls + 1] = evName
end,
asyncEmit = function(_evName, emit)
pending[#pending + 1] = emit
end
}
)
local owner = __TS__New(ScopedObject)
local argCount = -1
local capturedA
local capturedB
local capturedC
hub.on.Trailing(
function(...)
local args = {...}
argCount = select("#", ...)
capturedA = args[1]
capturedB = args[2]
capturedC = args[3]
end,
owner
)
hub.emit.Trailing("first", nil, nil)
AssertEqual(#preCalls, 0, "preEmit should not run before async flush")
AssertEqual(#pending, 1, "one queued async emit")
pending[1]()
AssertArrayEqual(preCalls, {"Trailing"})
AssertEqual(argCount, 3, "trailing nils must be preserved")
AssertEqual(capturedA, "first")
AssertEqual(capturedB, nil)
AssertEqual(capturedC, nil)
owner:Dispose()
hub:Dispose()
end
}
}
}
end
function __module.UpdateImports()
ScopedObject = M__share_base_scoped_object.ScopedObject
SetupTracebackHandler = M__share_base_traceback.SetupTracebackHandler
EventHub = M__share_event_event_hub.EventHub
Assert = M__tests_harness_test_runner.Assert
AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual
AssertEqual = M__tests_harness_test_runner.AssertEqual
end
+168
View File
@@ -0,0 +1,168 @@
local ____lualib = require("lualib_bundle")
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module)
local ScopedObject = M__share_base_scoped_object.ScopedObject
local M__framework_core_scheduler = __MODULE__.Import("framework.core.scheduler", __module)
local FrameScheduler = M__framework_core_scheduler.FrameScheduler
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual
local AssertEqual = M__tests_harness_test_runner.AssertEqual
function ____exports.CreateSchedulerSuite()
return {
name = "Step1.Scheduler",
cases = {
{
name = "Frame timers: 0 and 1 fire next frame, N fires on N-th frame",
fn = function()
local scheduler = __TS__New(FrameScheduler)
local fired = {}
scheduler:AddFrameTimer(
0,
function()
fired[#fired + 1] = "f0@" .. tostring(scheduler:GetFrameCount())
end
)
scheduler:AddFrameTimer(
1,
function()
fired[#fired + 1] = "f1@" .. tostring(scheduler:GetFrameCount())
end
)
scheduler:AddFrameTimer(
3,
function()
fired[#fired + 1] = "f3@" .. tostring(scheduler:GetFrameCount())
end
)
scheduler:Tick(0.016)
AssertArrayEqual(fired, {"f0@1", "f1@1"})
scheduler:Tick(0.016)
AssertArrayEqual(fired, {"f0@1", "f1@1"})
scheduler:Tick(0.016)
AssertArrayEqual(fired, {"f0@1", "f1@1", "f3@3"})
AssertEqual(
scheduler:GetStats().totalTasks,
0,
"all frame tasks completed"
)
scheduler:Dispose()
end
},
{
name = "World pause freezes world timers while monotonic timers continue",
fn = function()
local scheduler = __TS__New(FrameScheduler)
local log = {}
scheduler:AddWorldTimer(
0.1,
function()
log[#log + 1] = "world"
end
)
scheduler:AddMonotonicTimer(
0.1,
function()
log[#log + 1] = "mono"
end
)
scheduler:Tick(0.06, 0.06, true)
scheduler:Tick(0.06, 0.06, true)
AssertArrayEqual(log, {"mono"})
scheduler:Tick(0.05, 0.05, false)
AssertArrayEqual(log, {"mono"})
scheduler:Tick(0.06, 0.06, false)
AssertArrayEqual(log, {"mono", "world"})
AssertEqual(
scheduler:GetStats().totalTasks,
0
)
scheduler:Dispose()
end
},
{
name = "World invalidation cancels world & frame tasks but preserves monotonic tasks",
fn = function()
local scheduler = __TS__New(FrameScheduler)
local log = {}
scheduler:AddFrameTimer(
2,
function()
log[#log + 1] = "frame"
end
)
scheduler:AddWorldTimer(
0.05,
function()
log[#log + 1] = "world"
end
)
scheduler:AddMonotonicTimer(
0.05,
function()
log[#log + 1] = "mono"
end
)
local nextGen = scheduler:InvalidateWorld()
AssertEqual(nextGen, 2, "worldGen incremented")
AssertEqual(
scheduler:GetStats().worldTasks,
0,
"world tasks cleared"
)
AssertEqual(
scheduler:GetStats().frameTasks,
0,
"frame tasks cleared"
)
AssertEqual(
scheduler:GetStats().monotonicTasks,
1,
"monotonic task survives"
)
scheduler:Tick(0.06)
scheduler:Tick(0.06)
AssertArrayEqual(log, {"mono"})
AssertEqual(
scheduler:GetStats().totalTasks,
0
)
scheduler:Dispose()
end
},
{
name = "Disposing ScopedObject owner automatically cancels owned timers",
fn = function()
local scheduler = __TS__New(FrameScheduler)
local owner = __TS__New(ScopedObject)
local count = 0
scheduler:AddMonotonicRepeatTimer(
0.05,
function()
count = count + 1
end,
owner
)
scheduler:Tick(0.06)
AssertEqual(count, 1)
owner:Dispose()
scheduler:Tick(0.06)
scheduler:Tick(0.06)
AssertEqual(count, 1, "disposed owner timer must not fire")
AssertEqual(
scheduler:GetStats().totalTasks,
0,
"timer cleaned up"
)
scheduler:Dispose()
end
}
}
}
end
function __module.UpdateImports()
ScopedObject = M__share_base_scoped_object.ScopedObject
FrameScheduler = M__framework_core_scheduler.FrameScheduler
AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual
AssertEqual = M__tests_harness_test_runner.AssertEqual
end
+42
View File
@@ -0,0 +1,42 @@
local ____exports = __module.env
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local Assert = M__tests_harness_test_runner.Assert
local AssertEqual = M__tests_harness_test_runner.AssertEqual
function ____exports.CreateSmokeSuite()
return {
name = "Baseline.Smoke",
cases = {
{
name = "Lua 5.4 and __MODULE__ runtime are loaded",
fn = function()
Assert((string.match(_VERSION, "Lua 5%.4")) ~= nil, "Expected Lua 5.4 runtime")
Assert(__MODULE__ ~= nil, "Expected __MODULE__ global")
Assert(
type(__MODULE__.Import) == "function",
"Expected __MODULE__.Import function"
)
Assert(
type(__MODULE__.ReimportSafely) == "function",
"Expected __MODULE__.ReimportSafely"
)
end
},
{
name = "table.pack preserves trailing nil count n",
fn = function()
local packed = table.pack("a", nil, "c", nil)
AssertEqual(packed.n, 4, "packed.n")
local a, b, c, d = table.unpack(packed, 1, packed.n)
AssertEqual(a, "a")
AssertEqual(b, nil)
AssertEqual(c, "c")
AssertEqual(d, nil)
end
}
}
}
end
function __module.UpdateImports()
Assert = M__tests_harness_test_runner.Assert
AssertEqual = M__tests_harness_test_runner.AssertEqual
end
@@ -0,0 +1,250 @@
local ____lualib = require("lualib_bundle")
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__framework_core_scheduler = __MODULE__.Import("framework.core.scheduler", __module)
local FrameScheduler = M__framework_core_scheduler.FrameScheduler
local Json = __MODULE__.Import("framework.core.json", __module)
local M__framework_storage_local_save = __MODULE__.Import("framework.storage.local_save", __module)
local LocalSaveManager = M__framework_storage_local_save.LocalSaveManager
local LocalSaveStore = M__framework_storage_local_save.LocalSaveStore
local M__framework_storage_storage_backend = __MODULE__.Import("framework.storage.storage_backend", __module)
local MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend
local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module)
local SettingService = M__game_setting_setting_service.SettingService
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local Assert = M__tests_harness_test_runner.Assert
local AssertEqual = M__tests_harness_test_runner.AssertEqual
function ____exports.CreateStorageAndSettingSuite()
return {
name = "Step2A.StorageAndSetting",
cases = {
{
name = "JSON encodes/decodes nested objects, arrays, escapes, and 64-bit integers",
fn = function()
local bigId = tonumber("9007199254740993")
AssertEqual(
math.type(bigId),
"integer",
"bigId is Lua 5.4 integer"
)
local payload = {
version = 1,
roleId = bigId,
enabled = true,
label = "hello \"ue\"\nline2",
tags = {"a", "b", "c"},
emptyArr = Json.GetEmptyArray()
}
local encoded, encErr = Json.Encode(payload)
AssertEqual(encErr, nil, "encode error")
Assert(
type(encoded) == "string",
"encoded is string"
)
local decoded, decErr = Json.Decode(encoded)
AssertEqual(decErr, nil, "decode error")
local obj = decoded
AssertEqual(obj.version, 1)
AssertEqual(obj.roleId, bigId, "int64 round-trip")
AssertEqual(obj.enabled, true)
AssertEqual(obj.label, "hello \"ue\"\nline2")
local tags = obj.tags
AssertEqual(tags[1], "a")
AssertEqual(tags[3], "c")
end
},
{
name = "Missing slot returns defaults and coalesces rapid Set calls via 0.1s monotonic clock",
fn = function()
local scheduler = __TS__New(FrameScheduler)
local backend = __TS__New(MemoryStorageBackend)
local saveMgr = __TS__New(LocalSaveManager, backend, scheduler)
local settings = __TS__New(SettingService, saveMgr, "unit_coalesce")
AssertEqual(
settings:GetStore():GetLastLoadStatus(),
"not_found"
)
AssertEqual(
settings:GetSoundEnabled(),
true,
"default true"
)
settings:SetSoundEnabled(false)
settings:SetSoundEnabled(true)
settings:SetSoundEnabled(false)
AssertEqual(backend.writeCount, 0, "debounced before 0.1s")
scheduler:Tick(0.05, 0.05, true)
AssertEqual(backend.writeCount, 0)
scheduler:Tick(0.06, 0.06, true)
AssertEqual(backend.writeCount, 1, "coalesced into single write")
AssertEqual(
settings:GetStore():IsDirty(),
false
)
settings:Dispose()
saveMgr:Dispose()
local saveMgr2 = __TS__New(LocalSaveManager, backend, scheduler)
local settings2 = __TS__New(SettingService, saveMgr2, "unit_coalesce")
AssertEqual(
settings2:GetStore():GetLastLoadStatus(),
"ok"
)
AssertEqual(
settings2:GetStore():GetLoadedSchemaVersion(),
1
)
AssertEqual(
settings2:GetSoundEnabled(),
false,
"cold restart reads saved value"
)
settings2:Dispose()
saveMgr2:Dispose()
scheduler:Dispose()
end
},
{
name = "Write failure preserves previous valid data, retains dirty state, and succeeds on retry",
fn = function()
local scheduler = __TS__New(FrameScheduler)
local backend = __TS__New(MemoryStorageBackend)
local store = __TS__New(
LocalSaveStore,
"sdata_retry",
backend,
scheduler,
1
)
store:Set("k", "v1")
AssertEqual(
store:Flush(),
"ok"
)
backend.failNextWrite = true
store:Set("k", "v2")
AssertEqual(
store:Flush(),
"write_failed"
)
AssertEqual(
store:IsDirty(),
true,
"dirty remains true after failed write"
)
local reader = __TS__New(
LocalSaveStore,
"sdata_retry",
backend,
scheduler,
1
)
AssertEqual(
reader:Get("k"),
"v1",
"previous valid value preserved"
)
reader:Dispose()
AssertEqual(
store:Flush(),
"ok"
)
AssertEqual(
store:IsDirty(),
false
)
local reader2 = __TS__New(
LocalSaveStore,
"sdata_retry",
backend,
scheduler,
1
)
AssertEqual(
reader2:Get("k"),
"v2",
"retry wrote v2"
)
reader2:Dispose()
store:Dispose()
scheduler:Dispose()
end
},
{
name = "Corrupted primary slot preserves .corrupt evidence and recovers from .bak when available",
fn = function()
local scheduler = __TS__New(FrameScheduler)
local backend = __TS__New(MemoryStorageBackend)
backend:InjectCorruptPrimary("sdata_corrupt_only", "{not-valid-json")
local store1 = __TS__New(
LocalSaveStore,
"sdata_corrupt_only",
backend,
scheduler,
1
)
AssertEqual(
store1:GetLastLoadStatus(),
"corrupted"
)
AssertEqual(
backend:GetCorruptCopy("sdata_corrupt_only"),
"{not-valid-json"
)
AssertEqual(
store1:GetDefault("x", 42),
42
)
store1:Dispose()
local store2 = __TS__New(
LocalSaveStore,
"sdata_bak_recover",
backend,
scheduler,
1
)
store2:Set("val", "v1")
store2:Flush()
store2:Set("val", "v2")
store2:Flush()
store2:Dispose()
backend:InjectCorruptPrimary("sdata_bak_recover", "CORRUPTED_BYTES")
local store3 = __TS__New(
LocalSaveStore,
"sdata_bak_recover",
backend,
scheduler,
1
)
AssertEqual(
store3:GetLastLoadStatus(),
"ok"
)
AssertEqual(
store3:WasRecoveredFromBackup(),
true
)
AssertEqual(
store3:Get("val"),
"v1",
"recovered from backup"
)
AssertEqual(
backend:GetCorruptCopy("sdata_bak_recover"),
"CORRUPTED_BYTES"
)
store3:Dispose()
scheduler:Dispose()
end
}
}
}
end
function __module.UpdateImports()
FrameScheduler = M__framework_core_scheduler.FrameScheduler
LocalSaveManager = M__framework_storage_local_save.LocalSaveManager
LocalSaveStore = M__framework_storage_local_save.LocalSaveStore
MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend
SettingService = M__game_setting_setting_service.SettingService
Assert = M__tests_harness_test_runner.Assert
AssertEqual = M__tests_harness_test_runner.AssertEqual
end
@@ -0,0 +1,489 @@
local ____lualib = require("lualib_bundle")
local __TS__ClassExtends = ____lualib.__TS__ClassExtends
local __TS__New = ____lualib.__TS__New
local ____exports = __module.env
local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module)
local GameInstanceContext = M__framework_context_game_context.GameInstanceContext
local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module)
local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS
local BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS
local M__framework_resource_resource_service = __MODULE__.Import("framework.resource.resource_service", __module)
local ResourceService = M__framework_resource_resource_service.ResourceService
local M__framework_storage_local_save = __MODULE__.Import("framework.storage.local_save", __module)
local LocalSaveManager = M__framework_storage_local_save.LocalSaveManager
local M__framework_storage_storage_backend = __MODULE__.Import("framework.storage.storage_backend", __module)
local MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend
local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module)
local RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig
local M__framework_ui_ui_delegate_bridge = __MODULE__.Import("framework.ui.ui_delegate_bridge", __module)
local UIDelegateBridge = M__framework_ui_ui_delegate_bridge.UIDelegateBridge
local M__framework_ui_ui_manager = __MODULE__.Import("framework.ui.ui_manager", __module)
local UIManager = M__framework_ui_ui_manager.UIManager
local M__framework_ui_ui_window = __MODULE__.Import("framework.ui.ui_window", __module)
local UIWindow = M__framework_ui_ui_window.UIWindow
local M__game_setting_mini_settings_window = __MODULE__.Import("game.setting.mini_settings_window", __module)
local MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow
local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module)
local SettingService = M__game_setting_setting_service.SettingService
local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module)
local Assert = M__tests_harness_test_runner.Assert
local AssertEqual = M__tests_harness_test_runner.AssertEqual
local MockResourceBackend = __TS__DefineClass("MockResourceBackend", __module)
MockResourceBackend.name = "MockResourceBackend"
function MockResourceBackend.prototype.____constructor(self)
self.nextReqId = 0
self.pending = {}
self.refCounts = {}
self.loadRequestsCount = 0
end
function MockResourceBackend.prototype.ResolveAssetPath(self, keyOrPath)
return BASE_ASSET_PATHS[keyOrPath] or keyOrPath
end
function MockResourceBackend.prototype.DoesAssetExist(self, keyOrPath)
local resolved = self:ResolveAssetPath(keyOrPath)
return resolved ~= "/Game/Missing/BadAsset"
end
function MockResourceBackend.prototype.IsPackagedMode(self)
return false
end
function MockResourceBackend.prototype.RequestLoadObjectAsync(self, keyOrPath, worldGen)
self.nextReqId = self.nextReqId + 1
self.loadRequestsCount = self.loadRequestsCount + 1
self.pending[self.nextReqId] = {keyOrPath = keyOrPath, worldGen = worldGen, isClass = false}
return self.nextReqId
end
function MockResourceBackend.prototype.RequestLoadClassAsync(self, keyOrPath, worldGen)
self.nextReqId = self.nextReqId + 1
self.loadRequestsCount = self.loadRequestsCount + 1
self.pending[self.nextReqId] = {keyOrPath = keyOrPath, worldGen = worldGen, isClass = true}
return self.nextReqId
end
function MockResourceBackend.prototype.FlushAll(self)
local ids = {}
for id in pairs(self.pending) do
ids[#ids + 1] = id
end
table.sort(ids)
do
local i = 0
while i < #ids do
local id = ids[i + 1]
local req = self.pending[id]
if req ~= nil then
self.pending[id] = nil
local resolved = self:ResolveAssetPath(req.keyOrPath)
local exists = self:DoesAssetExist(req.keyOrPath)
if exists then
self.refCounts[resolved] = (self.refCounts[resolved] or 0) + 1
local ____opt_0 = self.service
if ____opt_0 ~= nil then
____opt_0:HandleNativeLoadComplete(
id,
true,
{mockAsset = resolved},
resolved,
""
)
end
else
local ____opt_2 = self.service
if ____opt_2 ~= nil then
____opt_2:HandleNativeLoadComplete(
id,
false,
nil,
resolved,
"Asset not found"
)
end
end
end
i = i + 1
end
end
end
function MockResourceBackend.prototype.CancelRequest(self, requestId)
if self.pending[requestId] == nil then
return false
end
self.pending[requestId] = nil
return true
end
function MockResourceBackend.prototype.CancelRequestsForWorld(self, worldGen)
local count = 0
for id, req in pairs(self.pending) do
if req ~= nil and req.worldGen == worldGen then
self.pending[id] = nil
count = count + 1
end
end
return count
end
function MockResourceBackend.prototype.ReleaseAsset(self, resolvedSoftPath)
local cur = self.refCounts[resolvedSoftPath] or 0
if cur <= 1 then
self.refCounts[resolvedSoftPath] = nil
else
self.refCounts[resolvedSoftPath] = cur - 1
end
end
function MockResourceBackend.prototype.GetResourceStats(self)
local inFlight = 0
for _, v in pairs(self.pending) do
if v ~= nil then
inFlight = inFlight + 1
end
end
local retained = 0
local totalRefs = 0
for _, refs in pairs(self.refCounts) do
if refs ~= nil and refs > 0 then
retained = retained + 1
totalRefs = totalRefs + refs
end
end
return inFlight, retained, totalRefs
end
local MockButtonBackend = __TS__DefineClass("MockButtonBackend", __module)
MockButtonBackend.name = "MockButtonBackend"
function MockButtonBackend.prototype.____constructor(self)
self.nextId = 0
self.buttonToIds = {}
self.idToButton = {}
end
function MockButtonBackend.prototype.BindButtonClicked(self, button)
self.nextId = self.nextId + 1
local id = self.nextId
self.idToButton[id] = button
local list = self.buttonToIds[button]
if list == nil then
list = {}
self.buttonToIds[button] = list
end
list[#list + 1] = id
return id
end
function MockButtonBackend.prototype.UnbindButtonClicked(self, bindingId)
local btn = self.idToButton[bindingId]
if btn == nil then
return false
end
self.idToButton[bindingId] = nil
local list = self.buttonToIds[btn]
if list ~= nil then
do
local i = #list - 1
while i >= 0 do
if list[i + 1] == bindingId then
table.remove(list, i + 1)
end
i = i - 1
end
end
end
return true
end
function MockButtonBackend.prototype.Click(self, button)
local list = self.buttonToIds[button]
if list == nil then
return
end
local snapshot = {}
do
local i = 0
while i < #list do
snapshot[i + 1] = list[i + 1]
i = i + 1
end
end
do
local i = 0
while i < #snapshot do
local ____opt_4 = self.bridge
if ____opt_4 ~= nil then
____opt_4:DispatchButtonClicked(snapshot[i + 1])
end
i = i + 1
end
end
end
function MockButtonBackend.prototype.GetActiveBindingCount(self)
local count = 0
for _, btn in pairs(self.idToButton) do
if btn ~= nil then
count = count + 1
end
end
return count
end
local MockWidgetFactory = __TS__DefineClass("MockWidgetFactory", __module)
MockWidgetFactory.name = "MockWidgetFactory"
function MockWidgetFactory.prototype.____constructor(self)
self.createdCount = 0
end
function MockWidgetFactory.prototype.CreateWidget(self)
self.createdCount = self.createdCount + 1
local txtStatus = {
text = "",
SetText = function(self, t)
self.text = t
end
}
local txtToggleLabel = {
text = "",
SetText = function(self, t)
self.text = t
end
}
local imgIcon = {
texture = nil,
SetBrushFromTexture = function(self, tex)
self.texture = tex
end
}
return {
valid = true,
inViewport = false,
visible = false,
zOrder = 0,
children = {
ImgIcon = imgIcon,
TxtStatus = txtStatus,
BtnToggle = {name = "BtnToggle"},
TxtToggleLabel = txtToggleLabel,
BtnClose = {name = "BtnClose"}
}
}
end
local MockWidgetAdapter = __TS__DefineClass("MockWidgetAdapter", __module)
MockWidgetAdapter.name = "MockWidgetAdapter"
function MockWidgetAdapter.prototype.____constructor(self)
end
function MockWidgetAdapter.prototype.FindChild(self, widget, name)
return widget.children[name]
end
function MockWidgetAdapter.prototype.AddToViewport(self, widget, zOrder)
widget.inViewport = true
widget.zOrder = zOrder
end
function MockWidgetAdapter.prototype.RemoveFromParent(self, widget)
widget.inViewport = false
end
function MockWidgetAdapter.prototype.SetVisible(self, widget, visible)
widget.visible = visible
end
function MockWidgetAdapter.prototype.IsWidgetValid(self, widget)
return widget ~= nil and widget.valid
end
local CachedTestWindow = __TS__DefineClass("CachedTestWindow", __module)
CachedTestWindow.name = "CachedTestWindow"
__TS__ClassExtends(CachedTestWindow, UIWindow)
function CachedTestWindow.prototype.____constructor(self, ...)
UIWindow.prototype.____constructor(self, ...)
self.reuseCount = 0
self.clickCount = 0
end
function CachedTestWindow.prototype.OnBindWidgets(self)
self.btn = self:RequireWidget("BtnToggle")
self:BindButtonClick(
self.btn,
function()
self.clickCount = self.clickCount + 1
end
)
end
function CachedTestWindow.prototype.OnReuseUI(self)
self.reuseCount = self.reuseCount + 1
end
RegisterUIConfig(CachedTestWindow, {
name = "CachedTestWindow",
assetKey = ASSET_KEYS.MINI_SETTINGS_WIDGET,
singleton = true,
layer = "normal",
cacheTag = "cache"
})
function ____exports.CreateUIAndResourceSuite()
return {
name = "Step2B_3.UIAndResource",
cases = {
{
name = "MiniSettingsWindow full lifecycle: open, load icon, click once, persist, close, reopen, zero leaks",
fn = function()
local ctx = __TS__New(GameInstanceContext)
local storageBackend = __TS__New(MemoryStorageBackend)
local saveMgr = __TS__New(LocalSaveManager, storageBackend, ctx.scheduler)
local settingSvc = __TS__New(SettingService, saveMgr, "ui_test")
local resBackend = __TS__New(MockResourceBackend)
local resSvc = __TS__New(ResourceService, ctx, resBackend)
resBackend.service = resSvc
local btnBackend = __TS__New(MockButtonBackend)
local btnBridge = __TS__New(UIDelegateBridge, ctx, btnBackend)
btnBackend.bridge = btnBridge
ctx:RegisterService("saveManager", saveMgr)
ctx:RegisterService("setting", settingSvc)
ctx:RegisterService("resource", resSvc)
ctx:RegisterService("uiDelegateBridge", btnBridge)
local widgetFactory = __TS__New(MockWidgetFactory)
local lp = ctx:GetOrCreateLocalPlayer(0)
local uiMgr = lp:RegisterService(
"uiManager",
__TS__New(
UIManager,
ctx,
lp,
resSvc,
widgetFactory,
__TS__New(MockWidgetAdapter)
)
)
local w1 = uiMgr:ShowUI(MiniSettingsWindow)
local w2 = uiMgr:ShowUI(MiniSettingsWindow)
AssertEqual(w1, w2, "concurrent singleton returns same controller")
resBackend:FlushAll()
resBackend:FlushAll()
AssertEqual(widgetFactory.createdCount, 1, "only 1 widget created")
Assert(w1 ~= nil and w1.iconLoaded, "icon loaded")
AssertEqual(w1.txtStatus.text, "Sound: ON")
AssertEqual(
uiMgr:GetDiagnostics().inputMode,
"ui"
)
btnBackend:Click(w1.btnToggle)
AssertEqual(w1.toggleClickCount, 1, "toggle click fired once")
AssertEqual(
settingSvc:GetSoundEnabled(),
false
)
AssertEqual(w1.txtStatus.text, "Sound: OFF")
ctx:Tick(0.12)
AssertEqual(storageBackend.writeCount, 1)
btnBackend:Click(w1.btnClose)
w1:Close()
Assert(
w1:IsDisposed(),
"window disposed"
)
AssertEqual(
btnBackend:GetActiveBindingCount(),
0,
"button bindings back to 0"
)
AssertEqual(
uiMgr:GetDiagnostics().openWindows,
0
)
AssertEqual(
uiMgr:GetDiagnostics().inputMode,
"game",
"focus restored to game"
)
AssertEqual(
resSvc:GetDiagnostics().nativeTotalRefCount,
0,
"resource refs back to 0"
)
local w3 = uiMgr:ShowUI(MiniSettingsWindow)
resBackend:FlushAll()
resBackend:FlushAll()
AssertEqual(w3.txtStatus.text, "Sound: OFF", "reopened window reflects persisted setting")
ctx:Dispose()
AssertEqual(
btnBackend:GetActiveBindingCount(),
0
)
AssertEqual(
resSvc:GetDiagnostics().nativeTotalRefCount,
0
)
end
},
{
name = "Close while loading cancels request and cached window reuse does not duplicate clicks",
fn = function()
local ctx = __TS__New(GameInstanceContext)
local resBackend = __TS__New(MockResourceBackend)
local resSvc = __TS__New(ResourceService, ctx, resBackend)
resBackend.service = resSvc
local btnBackend = __TS__New(MockButtonBackend)
local btnBridge = __TS__New(UIDelegateBridge, ctx, btnBackend)
btnBackend.bridge = btnBridge
ctx:RegisterService("resource", resSvc)
ctx:RegisterService("uiDelegateBridge", btnBridge)
local widgetFactory = __TS__New(MockWidgetFactory)
local lp = ctx:GetOrCreateLocalPlayer(0)
local uiMgr = lp:RegisterService(
"uiManager",
__TS__New(
UIManager,
ctx,
lp,
resSvc,
widgetFactory,
__TS__New(MockWidgetAdapter)
)
)
local loadingWin = uiMgr:ShowUI(CachedTestWindow)
loadingWin:Close()
resBackend:FlushAll()
AssertEqual(widgetFactory.createdCount, 0, "cancelled load never creates widget")
AssertEqual(
resSvc:GetDiagnostics().nativeTotalRefCount,
0
)
local win = uiMgr:ShowUI(CachedTestWindow)
resBackend:FlushAll()
AssertEqual(widgetFactory.createdCount, 1)
btnBackend:Click(win.btn)
AssertEqual(win.clickCount, 1)
win:Close()
AssertEqual(
uiMgr:GetDiagnostics().cachedWindows,
1,
"window moved to cache"
)
AssertEqual(
btnBackend:GetActiveBindingCount(),
0,
"cached window unbound buttons"
)
local reused = uiMgr:ShowUI(CachedTestWindow)
AssertEqual(reused, win, "reused cached controller")
AssertEqual(widgetFactory.createdCount, 1, "no second widget instantiated")
AssertEqual(reused.reuseCount, 1)
btnBackend:Click(reused.btn)
AssertEqual(reused.clickCount, 2, "single click after reuse increments by exactly 1")
uiMgr:CloseAll(true)
AssertEqual(
uiMgr:GetDiagnostics().cachedWindows,
0
)
AssertEqual(
btnBackend:GetActiveBindingCount(),
0
)
AssertEqual(
resSvc:GetDiagnostics().nativeTotalRefCount,
0
)
ctx:Dispose()
end
}
}
}
end
function __module.UpdateImports()
GameInstanceContext = M__framework_context_game_context.GameInstanceContext
ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS
BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS
ResourceService = M__framework_resource_resource_service.ResourceService
LocalSaveManager = M__framework_storage_local_save.LocalSaveManager
MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend
RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig
UIDelegateBridge = M__framework_ui_ui_delegate_bridge.UIDelegateBridge
UIManager = M__framework_ui_ui_manager.UIManager
UIWindow = M__framework_ui_ui_window.UIWindow
MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow
SettingService = M__game_setting_setting_service.SettingService
Assert = M__tests_harness_test_runner.Assert
AssertEqual = M__tests_harness_test_runner.AssertEqual
end