Skip to content

Instantly share code, notes, and snippets.

@RichardB01
Created July 4, 2020 20:30
Show Gist options
  • Save RichardB01/20349672018d4ba1ca6b98203aab282e to your computer and use it in GitHub Desktop.
Save RichardB01/20349672018d4ba1ca6b98203aab282e to your computer and use it in GitHub Desktop.
Lua testing functions similar to Unity
Ring = {}
Ring._registeredFunctions = {}
Ring._currentTestFunctionPtr = nil
Ring._tests = {}
function Ring.RegisterTest(func)
table.insert(Ring._registeredFunctions, func)
end
function Ring.Assert(op, msg)
local assertFailed = not op
table.insert(Ring._tests[Ring._currentTestFunctionPtr],
{
status = not assertFailed,
message = msg,
hasMessage = (msg ~= nil)
})
end
function Ring.RunTests()
print("-----------------------------")
print("-- Ring Unit Testing Began --")
print("-----------------------------")
print("Running tests...")
for k,funcPtr in pairs(Ring._registeredFunctions) do
Ring._currentTestFunctionPtr = funcPtr
Ring._tests[Ring._currentTestFunctionPtr] = {}
funcPtr() -- executes other ring functions Ring.Assert(op,msg).etc
Ring._currentTestFunctionPtr = nil
end
print("Completed!")
print("")
for funcPtr, a in pairs(Ring._tests) do
for _,testResult in pairs(a) do
-- Get RTTI for this function.
local functionInformation = debug.getinfo(funcPtr)
local source = functionInformation.source
local short_src = functionInformation.short_src
local linedefined = functionInformation.linedefined
local what = functionInformation.what -- Lua/C/main
local name = functionInformation.name
local namewhat = functionInformation.namewhat -- meaning of name. global/local/method/field/-empty-
local nups = functionInformation.nups
-- Get test results information.
local status = testResult.status
local message = testResult.message
local hasMessage = testResult.hasMessage
if hasMessage then
print(source, linedefined, "Name: `" .. tostring(name) .. "`", "Status: " .. tostring(status), "Message: " .. tostring(message))
else
print(source, linedefined, "Name: `" .. tostring(name) .. "`", "Status: " .. tostring(status))
end
end
end
print("")
print("---------------------------------")
print("-- Ring Unit Testing Completed --")
print("---------------------------------")
end
--[[
function abc()
a = 1
Ring.Assert(a == 2, "test")
b = 10
return a + b
end
Ring.RegisterTest(abc)
Ring.RunTests()
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment