-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
578 lines (497 loc) · 17.1 KB
/
main.lua
File metadata and controls
578 lines (497 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
REPENTOGON_TEST = RegisterMod("REPENTOGON Tests", 1)
REPENTOGON_TEST.Root = "rgon_test_scripts/"
REPENTOGON_TEST.TestsRoot = REPENTOGON_TEST.Root .. "tests/"
local BIG_FLOAT = 9999999 -- Precision issues start if you add another 9 here
local LONG_STRING = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -- Mostly just wanted something with >16 characters
-- Tables of test values for different types, for testing bounds or limits of a field or checking to see if large numbers lead to weird results.
-- Not required for use in tests, but can be useful for our purposes since we don't always know for sure what internal code will do with a number
-- passed from lua, especially if a signed integer gets converted to signed or vice versa.
REPENTOGON_TEST.TestInts = { 0, 1, -1, 2147483647, -2147483647 }
REPENTOGON_TEST.TestNonNegativeInts = { 0, 1, 2147483647 }
REPENTOGON_TEST.TestUnsignedInts = { 0, 1, 2147483647, 4294967295 }
REPENTOGON_TEST.TestInt8s = { 0, 1, -1, 127, -127 }
REPENTOGON_TEST.TestUInt8s = { 0, 1, 255 }
REPENTOGON_TEST.TestInt16s = { 0, 1, -1, 32767, -32767 }
REPENTOGON_TEST.TestUInt16s = { 0, 1, 65535 }
REPENTOGON_TEST.TestFloats = { 0.5, -0.5, 0, 1, -BIG_FLOAT, BIG_FLOAT }
REPENTOGON_TEST.TestNonNegativeFloats = { 0, 0.5, 1, BIG_FLOAT }
REPENTOGON_TEST.TestPositiveFloats = { 0.5, 1, BIG_FLOAT }
REPENTOGON_TEST.TestStrings = { "hello", "", LONG_STRING }
REPENTOGON_TEST.TestNonEmptyStrings = { "hello", LONG_STRING }
REPENTOGON_TEST.TestVectors = { Vector(0,0), Vector(1,1), Vector(BIG_FLOAT, BIG_FLOAT), Vector(-BIG_FLOAT, -BIG_FLOAT), Vector(0.5, -0.5) }
REPENTOGON_TEST.TestColors = {
Color(1,1,1,1,1,1,1,1,1,1),
Color(BIG_FLOAT, BIG_FLOAT, BIG_FLOAT, BIG_FLOAT, BIG_FLOAT, BIG_FLOAT, BIG_FLOAT, BIG_FLOAT, BIG_FLOAT, BIG_FLOAT),
Color(-BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT, -BIG_FLOAT),
Color(0.5,0.5,0.5,0.5,0.5,0.5,0.5),
Color(0,0,0,0),
Color(1,1,1,1),
}
REPENTOGON_TEST.TEST_PLAYER = Isaac.GetPlayerTypeByName("Testsaac")
REPENTOGON_TEST.TEST_FAMILIAR = Isaac.GetEntityVariantByName("Brother Bobentogon")
include(REPENTOGON_TEST.Root .. "misc")
local function Round(n, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
local x = (n*mult) % 1 >= 0.5 and math.ceil(n*mult) or math.floor(n*mult)
return x / mult
end
-- Triggers a lua error if a ~= b. The error will log the line where AssertEquals was called from.
-- For userdata, supports Color and Vector.
function REPENTOGON_TEST.AssertEquals(a, b)
if type(a) ~= type(b) then
error("Expected " .. type(b) .. ", got " .. type(a), 2)
end
if type(b) == "number" then
if math.floor(a) ~= a then
a = Round(a, 4)
end
if math.floor(b) ~= b then
b = Round(b, 4)
end
end
if type(b) == "userdata" then
local atype = getmetatable(a).__name
local btype = getmetatable(b).__name
if atype ~= btype then
error("Expected " .. btype .. ", got " .. atype, 2)
end
-- TODO: Maybe make this less lazy, lol.
if tostring(a) ~= tostring(b) then
error("Expected " .. tostring(b) .. ", got " .. tostring(a), 2)
end
elseif a ~= b then
error("Expected " .. tostring(b) .. ", got " .. tostring(a), 2)
end
end
-- Triggers a lua error if the provided value is anything other than a TRUE boolean.
function REPENTOGON_TEST.AssertTrue(val)
if type(val) ~= "boolean" or not val then
error("Expected true, got " .. tostring(val), 2)
end
end
-- Triggers a lua error if the provided value is anything other than a FALSE boolean.
function REPENTOGON_TEST.AssertFalse(val)
if type(val) ~= "boolean" or val then
error("Expected false, got " .. tostring(val), 2)
end
end
-- Triggers a lua error if the provided value is non-nil.
function REPENTOGON_TEST.AssertNil(val)
if val ~= nil then
error("Expected nil, got " .. tostring(val), 2)
end
end
REPENTOGON_TEST.AssertNull = REPENTOGON_TEST.AssertNil -- lol
-- Callbacks added during tests.
local testCallbacks = {}
function REPENTOGON_TEST:ClearTestCallbacks()
for callbackid, tab in pairs(testCallbacks) do
for _, func in ipairs(tab) do
REPENTOGON_TEST:RemoveCallback(callbackid, func)
end
end
testCallbacks = {}
end
REPENTOGON_TEST.OriginalAddPriorityCallback = REPENTOGON_TEST.AddPriorityCallback
function REPENTOGON_TEST:AddPriorityCallback(callbackid, priority, func, param)
if REPENTOGON_TEST.RunningTest then
if not testCallbacks[callbackid] then
testCallbacks[callbackid] = {}
end
table.insert(testCallbacks[callbackid], func)
end
return REPENTOGON_TEST:OriginalAddPriorityCallback(callbackid, priority, func, param)
end
function REPENTOGON_TEST:AddCallback(callbackid, func, param)
return REPENTOGON_TEST:AddPriorityCallback(callbackid, CallbackPriority.DEFAULT, func, param)
end
-- Track one-time callbacks that were added so we can find ones that did not run.
local oneTimeCallbacks = {}
-- Stores tracked callbacks that should never fire to be removed.
local unexpectedCallbacks = {}
local unexpectedCallbacksFired = 0
function REPENTOGON_TEST:ClearOneTimeCallbacks()
local found = 0
for callbackid, tab in pairs(oneTimeCallbacks) do
for _, func in ipairs(tab) do
found = found + 1
REPENTOGON_TEST:RemoveCallback(callbackid, func)
end
end
oneTimeCallbacks = {}
return found
end
-- Add a callback that removes itself when it runs.
function REPENTOGON_TEST:AddOneTimePriorityCallback(callbackid, priority, func, param)
local wrapper
wrapper = function(...)
REPENTOGON_TEST:RemoveCallback(callbackid, wrapper)
local tab = oneTimeCallbacks[callbackid] or {}
for i, v in ipairs(tab) do
if v == wrapper then
table.remove(tab, i)
end
end
return func(...)
end
if not oneTimeCallbacks[callbackid] then
oneTimeCallbacks[callbackid] = {}
end
table.insert(oneTimeCallbacks[callbackid], wrapper)
REPENTOGON_TEST:AddPriorityCallback(callbackid, priority, wrapper, param)
end
function REPENTOGON_TEST:AddUnexpectedPriorityCallback(callbackid, priority)
local wrapper
wrapper = function(...)
REPENTOGON_TEST:RemoveCallback(callbackid, wrapper)
unexpectedCallbacksFired = unexpectedCallbacksFired + 1
end
table.insert(unexpectedCallbacks, {callbackid, wrapper})
REPENTOGON_TEST:AddPriorityCallback(callbackid, priority, wrapper)
end
function REPENTOGON_TEST:AddOneTimeCallback(callbackid, func, param)
REPENTOGON_TEST:AddOneTimePriorityCallback(callbackid, CallbackPriority.DEFAULT, func, param)
end
function REPENTOGON_TEST:AddUnexpectedCallback(callbackid)
REPENTOGON_TEST:AddUnexpectedPriorityCallback(callbackid, CallbackPriority.DEFAULT)
end
function REPENTOGON_TEST.GetTestSprite()
local sprite = Sprite("gfx/001.000_player.anm2", true)
sprite:Play("WalkDown", true)
sprite:PlayOverlay("HeadDown", true)
return sprite
end
function REPENTOGON_TEST.GetDoor()
local room = Game():GetRoom()
for i=0,3 do
if room:GetDoor(i) then
return room:GetDoor(i)
end
end
end
function REPENTOGON_TEST.SpawnGridEntity(gridType, gridVar)
local grid = nil
local idx = 0
while idx <= Game():GetRoom():GetGridSize() do
if not Game():GetRoom():GetGridEntity(idx) then
Game():GetRoom():SpawnGridEntity(idx, gridType or GridEntityType.GRID_ROCK, gridVar or 0, 1234, 0)
if Game():GetRoom():GetGridEntity(idx) then
return Game():GetRoom():GetGridEntity(idx)
end
end
idx = idx + 1
end
end
function REPENTOGON_TEST.RemoveGridEntity(gridentity)
local idx = gridentity:GetGridIndex()
Game():GetRoom():RemoveGridEntity(idx, 0, false)
Game():GetRoom():Update()
end
function REPENTOGON_TEST.ResetPlayer(player)
if player:IsDead() then
player:Revive()
end
if player:GetPlayerType() ~= PlayerType.PLAYER_ISAAC then
player:ChangePlayerType(PlayerType.PLAYER_ISAAC)
end
player:AddSoulHearts(-999)
player:AddBlackHearts(-999)
player:AddBoneHearts(-999)
player:AddGoldenHearts(-999)
player:AddEternalHearts(-999)
player:AddBrokenHearts(-999)
player:AddRottenHearts(-999)
player:AddRottenHearts(-999)
if player:GetMaxHearts() ~= 6 then
player:AddMaxHearts(6 - player:GetMaxHearts())
end
player:AddHearts(player:GetMaxHearts())
player:SetBagOfCraftingContent({})
player.ControlsEnabled = true
player.ControlsCooldown = 0
player:ResetDamageCooldown()
player:StopExtraAnimation()
for item, count in pairs(player:GetCollectiblesList()) do
for i=1,count do
player:RemoveCollectible(item)
end
end
for i=0,1 do
local t = player:GetTrinket(i)
if t > 0 then
player:TryRemoveTrinket(t)
end
end
for i=0,3 do
player:SetCard(i, 0)
end
player:GetEffects():ClearEffects()
Game():GetRoom():GetEffects():ClearEffects()
if Game():GetDebugFlags() & DebugFlag.INFINITE_HP ~= 0 then
Isaac.ExecuteCommand("debug 3")
end
player:AddCacheFlags(CacheFlag.CACHE_ALL, true)
for pillColor = PillColor.PILL_NULL, PillColor.PILL_GOLD do
Game():GetItemPool():UnidentifyPill(pillColor)
end
end
function REPENTOGON_TEST.CleanEntities()
for _, ent in pairs(Isaac.GetRoomEntities()) do
if ent.Type ~= EntityType.ENTITY_PLAYER then
ent:Remove()
end
end
end
-- A new run is started between each test FILE to ensure a clean state.
-- We need to wait for MC_POST_GAME_STARTED to run again for things to be initialized properly,
-- so doing this between each TEST would be too slow, but between each FILE is a good comprimise.
-- Greed Mode is used to minimize the time wasted on level generation.
local function ResetRun()
Isaac.StartNewGame(PlayerType.PLAYER_ISAAC, Challenge.CHALLENGE_NULL, Difficulty.DIFFICULTY_GREED, 4)
end
local function Log(str, toConsole)
if toConsole then
print(str)
end
Isaac.DebugString(str)
end
local function LogFailure(className, funcName, errStr)
errStr = "Test " .. className.."."..funcName .. " FAILED:\n\t" .. errStr
Console.PrintError(errStr)
Isaac.DebugString("ERROR: " .. errStr)
end
local TESTS_RAN = 0
local TEST_FAILURES = 0
local TEST_QUEUE = {}
local function LogTestsFinished()
Log("All tests complete! Ran " .. TESTS_RAN .. " tests with " .. TEST_FAILURES .. " failures.", true)
TESTS_RAN = 0
TEST_FAILURES = 0
end
-- Returns a table of unit test files.
-- Only returns InGame tests while in-game, and only InMenu tests while in the main menu.
function REPENTOGON_TEST:GetUnitTests(menu)
local alltests = REPENTOGON_TEST.Tests
if menu == false or Isaac.IsInGame() then
return alltests.InGame
end
return alltests.InMenu
end
-- Run tests only on MC_POST_GAME_STARTED to ensure things are initialized. We trigger a new run when we need to move to the next test file.
function REPENTOGON_TEST:UpdateTests()
local currentClass = TEST_QUEUE[#TEST_QUEUE]
if not currentClass then return end
if not currentClass.Started then
Log("Running tests for " .. currentClass.Name .. "...")
currentClass.Started = true
end
while #currentClass.UpdateTests > 0 do
local test = table.remove(currentClass.UpdateTests)
test()
end
end
REPENTOGON_TEST:AddCallback(ModCallbacks.MC_POST_GAME_STARTED, REPENTOGON_TEST.UpdateTests)
-- Tests for functions that start with "Render" are only run on render callbacks to avoid weird issues.
function REPENTOGON_TEST:RenderTests()
local currentClass = TEST_QUEUE[#TEST_QUEUE]
if not currentClass then return end
if #currentClass.UpdateTests > 0 or not currentClass.Started then
return
end
Log("Running render tests for " .. currentClass.Name .. "...")
while #currentClass.RenderTests > 0 do
local test = table.remove(currentClass.RenderTests)
test()
end
Log("Finished all tests for " .. currentClass.Name .. "! Starting a new run...")
-- Reset the game between test classes
table.remove(TEST_QUEUE)
if #TEST_QUEUE == 0 then
LogTestsFinished()
end
ResetRun()
end
REPENTOGON_TEST:AddCallback(ModCallbacks.MC_POST_RENDER, REPENTOGON_TEST.RenderTests)
local function RunTestsForClass(className, classTests, functionToTest)
local testsToRun = {
Name = className,
--Class = classTests,
UpdateTests = {},
RenderTests = {},
}
-- Sort tests by name for the sake of determinism.
local sortedTests = {}
for funcName, func in pairs(classTests) do
if funcName:match("^Test") and (not functionToTest or (funcName:match("^" .. functionToTest) or funcName:match("^Test" .. functionToTest)))
and not (className == "FontRenderSettings" and not REPENTANCE_PLUS) then
table.insert(sortedTests, {Name = funcName, Func = func})
end
end
table.sort(sortedTests, function(a, b)
return a.Name < b.Name
end)
local beforeFunc = classTests.BeforeEach or function() end
local afterFunc = classTests.AfterEach or function() end
for _, test in ipairs(sortedTests) do
local funcName = test.Name
local func = test.Func
local runtest = function()
Log("Running test: " .. className ..".".. funcName .. "...")
TESTS_RAN = TESTS_RAN + 1
if Isaac.IsInGame() then
REPENTOGON_TEST.ResetPlayer(Isaac.GetPlayer())
REPENTOGON_TEST.CleanEntities()
end
REPENTOGON_TEST.RunningTest = true
local success, ret = pcall(function()
local input = beforeFunc(classTests)
func(classTests, input)
afterFunc(classTests, input)
end)
REPENTOGON_TEST.RunningTest = false
REPENTOGON_TEST:ClearTestCallbacks()
local unrunCallbacks = REPENTOGON_TEST:ClearOneTimeCallbacks()
if unrunCallbacks > 0 then
local err = "- Found " .. unrunCallbacks .. " one-time callbacks that did not run!"
if success then
success = false
ret = err
else
ret = ret .. "\n\t" .. err
end
end
if unexpectedCallbacksFired > 0 then
local err = "- Found " .. unexpectedCallbacksFired .. " unexpected callbacks that ran!"
if success then
success = false
ret = err
else
ret = ret .. "\n\t" .. err
end
end
for _, v in pairs(unexpectedCallbacks) do
REPENTOGON_TEST:RemoveCallback(v[1], v[2])
end
unexpectedCallbacks = {}
unexpectedCallbacksFired = 0
if not success then
LogFailure(className, funcName, ret)
TEST_FAILURES = TEST_FAILURES + 1
else
Log("...finished!")
end
return
end
-- Menu tests can be run immediately. Others are queued up to execute during callbacks.
if not Isaac.IsInGame() then
runtest()
elseif funcName:match("^TestRender") then
table.insert(testsToRun.RenderTests, runtest)
else
table.insert(testsToRun.UpdateTests, runtest)
end
end
if Isaac.IsInGame() then
table.insert(TEST_QUEUE, testsToRun)
end
end
function REPENTOGON_TEST:RunTests(classToTest, functionToTest)
local tests = REPENTOGON_TEST:GetUnitTests()
TESTS_RAN = 0
TEST_FAILURES = 0
Log("Running tests...", true)
if classToTest then
RunTestsForClass(classToTest, tests[classToTest], functionToTest)
else
local testclasses = {}
for className, _ in pairs(tests) do
table.insert(testclasses, className)
end
table.sort(testclasses)
for _, className in pairs(testclasses) do
RunTestsForClass(className, tests[className])
end
end
if Isaac.IsInGame() then
table.sort(TEST_QUEUE, function(a, b)
return a.Name < b.Name
end)
ResetRun()
else
LogTestsFinished()
end
end
REPENTOGON_TEST.Tests = include(REPENTOGON_TEST.Root .. "get_all_tests")
-- QOL for console auto complete and such.
function REPENTOGON_TEST:TestCommand(cmdName, argsStr)
local tests = REPENTOGON_TEST:GetUnitTests()
if cmdName == "testall" then
REPENTOGON_TEST:RunTests()
elseif cmdName == "test" then
-- Split args into table.
local args = {}
for w in argsStr:gmatch("%S+") do args[#args+1] = w end
local classToTest = args[1]
local functionToTest = args[2]
if not classToTest then
print("No class to test provided!")
return
else
if not functionToTest then
if not tests[classToTest] then
print("[" .. classToTest .. "] is not a valid class!")
return
end
REPENTOGON_TEST:RunTests(classToTest)
else
-- Validate that this test exists before trying to run it.
local classTests = tests[classToTest]
if not classTests then
print("[" .. classToTest .. "] is not a valid class!")
return
end
for funcName in pairs(classTests) do
if funcName:match("^Test") and (funcName:match("^" .. functionToTest) or funcName:match("^Test" .. functionToTest))
and not (classTests == "FontRenderSettings" and not REPENTANCE_PLUS) then
REPENTOGON_TEST:RunTests(classToTest, functionToTest)
return
end
end
-- No test found.
print("[" .. functionToTest .. "] is not a valid test of [" .. classToTest .. "]!")
end
end
end
end
REPENTOGON_TEST:AddCallback(ModCallbacks.MC_EXECUTE_CMD, REPENTOGON_TEST.TestCommand)
function REPENTOGON_TEST:CommandAutocomplete(_, argsStr)
-- Split args into table.
local args = {}
for w in argsStr:gmatch("%S+") do args[#args+1] = w end
-- I tried making it only return auto complete for one argument
local returnTable = {}
local tests = REPENTOGON_TEST:GetUnitTests()
for className, classTests in pairs(tests) do
for funcName in pairs(classTests) do
if funcName:match("^Test") and not (classTests == "FontRenderSettings" and not REPENTANCE_PLUS) then
table.insert(returnTable, className .. " " .. funcName:sub(5))
end
end
end
return returnTable
end
REPENTOGON_TEST:AddCallback(ModCallbacks.MC_CONSOLE_AUTOCOMPLETE, REPENTOGON_TEST.CommandAutocomplete, "test")
Console.RegisterCommand(
"testall",
"REPENTOGON: Tests every class",
"testall",
true,
AutocompleteType.NONE
)
Console.RegisterCommand(
"test",
"REPENTOGON: Tests a specific class or class function",
"test <class> <funcName?>",
true,
AutocompleteType.CUSTOM
)