cc-libs/apis/libtest.lua
2026-06-08 04:52:19 +02:00

93 lines
1.8 KiB
Lua

local _VERSION = "1.3.0"
local function createLibTest(args)
local api = {}
local tests = {}
local verbose = false
local reportPath = "/trapos-test-report"
for _, arg in ipairs(args or {}) do
if arg == "--verbose" then
verbose = true
end
end
local function fail(message)
error(message, 2)
end
local function writeReport(line)
if not verbose then
return
end
local file = fs.open(reportPath, "a")
if file then
file.writeLine(line)
file.close()
end
end
function api.test(name, fn)
assert(type(name) == "string", "bad argument #1 (string expected)")
assert(type(fn) == "function", "bad argument #2 (function expected)")
tests[#tests + 1] = { name = name, fn = fn }
end
function api.assertEquals(actual, expected, message)
if actual ~= expected then
fail(
(message or "assertEquals failed")
.. ": expected "
.. tostring(expected)
.. ", got "
.. tostring(actual)
)
end
end
function api.assertTrue(value, message)
if not value then
fail(message or "assertTrue failed")
end
end
function api.assertErrors(fn, expected)
assert(type(fn) == "function", "bad argument #1 (function expected)")
local ok, err = pcall(fn)
if ok then
fail("expected error")
end
if expected and not string.find(tostring(err), expected, 1, true) then
fail("expected error containing " .. expected .. ", got " .. tostring(err))
end
end
function api.run()
for _, t in ipairs(tests) do
local ok, err = pcall(t.fn)
if not ok then
writeReport("KO " .. t.name .. ": " .. tostring(err))
if not verbose then
print("FAIL " .. t.name .. ": " .. tostring(err))
end
os.shutdown()
end
writeReport("OK " .. t.name)
end
print("__TRAPOS_TEST_OK__")
os.shutdown()
end
function api.version()
return _VERSION
end
return api
end
return createLibTest