Mô đun:ScribuntoUnit

-------------------------------------------------------------------------------
-- Unit tests for Scribunto.
-------------------------------------------------------------------------------
require('strict')

local DebugHelper = {}
local ScribuntoUnit = {}

-- The cfg table contains all localisable strings and configuration, to make it
-- easier to port this module to another wiki.
local cfg = mw.loadData('Module:ScribuntoUnit/config')

-------------------------------------------------------------------------------
-- Concatenates keys and values, ideal for displaying a template or parser function argument table.
-- @param keySeparator glue between key and value (defaults to " = ")
-- @param separator glue between different key-value pairs (defaults to ", ")
-- @example concatWithKeys({a = 1, b = 2, c = 3}, ' => ', ', ') => "a => 1, b => 2, c => 3"
--
function DebugHelper.concatWithKeys(table, keySeparator, separator)
keySeparator = keySeparator or ' = '
separator = separator or ', '
local concatted =
local i = 1
local first = true
local unnamedArguments = true
for k, v in pairs(table) do
if first then
first = false
else
concatted = concatted .. separator
end
if k == i and unnamedArguments then
i = i + 1
concatted = concatted .. tostring(v)
else
unnamedArguments = false
concatted = concatted .. tostring(k) .. keySeparator .. tostring(v)
end
end
return concatted
end

-------------------------------------------------------------------------------
-- Compares two tables recursively (non-table values are handled correctly as well).
-- @param ignoreMetatable if false, t1.__eq is used for the comparison
--
function DebugHelper.deepCompare(t1, t2, ignoreMetatable)
local type1 = type(t1)
local type2 = type(t2)

if type1 ~= type2 then
return false
end
if type1 ~= 'table' then
return t1 == t2
end

local metatable = getmetatable(t1)
if not ignoreMetatable and metatable and metatable.__eq then
return t1 == t2
end

for k1, v1 in pairs(t1) do
local v2 = t2[k1]
if v2 nil or not DebugHelper.deepCompare(v1, v2) then
return false
end
end
for k2, v2 in pairs(t2) do
if t1[k2] nil then
return false
end
end

return true
end

-------------------------------------------------------------------------------
-- Raises an error with stack information
-- @param details a table with error details
-- - should have a 'text' key which is the error message to display
-- - a 'trace' key will be added with the stack data
-- - and a 'source' key with file/line number
-- - a metatable will be added for error handling
--
function DebugHelper.raise(details, level)
level = (level or 1) + 1
details.trace = debug.traceback(, level)
details.source = string.match(details.trace, '^%sstack traceback:%s(%S: )')

-- setmetatable(details, {
-- __tostring: function() return details.text end
-- })

error(details, level)
end

-------------------------------------------------------------------------------
-- when used in a test, that test gets ignored, and the skipped count increases by one.
--
function ScribuntoUnit:markTestSkipped()
DebugHelper.raise({ScribuntoUnit = true, skipped = true}, 3)
end

-------------------------------------------------------------------------------
-- Unconditionally fail a test
-- @param message optional description of the test
--
function ScribuntoUnit:fail(message)
DebugHelper.raise({ScribuntoUnit = true, text = "Test failed", message = message}, 2)
end

-------------------------------------------------------------------------------
-- Checks that the input is true
-- @param message optional description of the test
--
function ScribuntoUnit:assertTrue(actual, message)
if not actual then
DebugHelper.raise({ScribuntoUnit = true, text = string.format("Failed to assert that %s is true", tostring(actual)), message = message}, 2)
end
end

-------------------------------------------------------------------------------
-- Checks that the input is false
-- @param message optional description of the test
--
function ScribuntoUnit:assertFalse(actual, message)
if actual then
DebugHelper.raise({ScribuntoUnit = true, text = string.format("Failed to assert that %s is false", tostring(actual)), message = message}, 2)
end
end

-------------------------------------------------------------------------------
-- Checks an input string contains the expected string
-- @param message optional description of the test
-- @param plain search is made with a plain string instead of a ustring pattern
--
function ScribuntoUnit:assertStringContains(pattern, s, plain, message)
if type(pattern) ~= 'string' then
DebugHelper.raise({
ScribuntoUnit = true,
text = mw.ustring.format("Pattern type error (expected string, got %s)", type(pattern)),
message = message
}, 2)
end
if type(s) ~= 'string' then
DebugHelper.raise({
ScribuntoUnit = true,
text = mw.ustring.format("String type error (expected string, got %s)", type(s)),
message = message
}, 2)
end
if not mw.ustring.find(s, pattern, nil, plain) then
DebugHelper.raise({
ScribuntoUnit = true,
text = mw.ustring.format('Failed to find %s "%s" in string "%s"', plain and "plain string" or "pattern", pattern, s),
message = message
}, 2)
end
end

-------------------------------------------------------------------------------
-- Checks an input string doesn't contain the expected string
-- @param message optional description of the test
-- @param plain search is made with a plain string instead of a ustring pattern
--
function ScribuntoUnit:assertNotStringContains(pattern, s, plain, message)
if type(pattern) ~= 'string' then
DebugHelper.raise({
ScribuntoUnit = true,
text = mw.ustring.format("Pattern type error (expected string, got %s)", type(pattern)),
message = message
}, 2)
end
if type(s) ~= 'string' then
DebugHelper.raise({
ScribuntoUnit = true,
text = mw.ustring.format("String type error (expected string, got %s)", type(s)),
message = message
}, 2)
end
local i, j = mw.ustring.find(s, pattern, nil, plain)
if i then
local match = mw.ustring.sub(s, i, j)
DebugHelper.raise({
ScribuntoUnit = true,
text = mw.ustring.format('Found match "%s" for %s "%s"', match, plain and "plain string" or "pattern", pattern),
message = message
}, 2)
end
end

-------------------------------------------------------------------------------
-- Checks that an input has the expected value.
-- @param message optional description of the test
-- @example assertEquals(4, add(2,2), "2+2 should be 4")
--
function ScribuntoUnit:assertEquals(expected, actual, message)
if type(expected) 'number' and type(actual) 'number' then
self:assertWithinDelta(expected, actual, 1e-8, message)
elseif expected ~= actual then
DebugHelper.raise({
ScribuntoUnit = true,
text = string.format("Failed to assert that %s equals expected %s", tostring(actual), tostring(expected)),
actual = actual,
expected = expected,
message = message,
}, 2)
end
end

-------------------------------------------------------------------------------
-- Checks that an input does not have the expected value.
-- @param message optional description of the test
-- @example assertNotEquals(5, add(2,2), "2+2 should not be 5")
--
function ScribuntoUnit:assertNotEquals(expected, actual, message)
if type(expected) 'number' and type(actual) 'number' then
self:assertNotWithinDelta(expected, actual, 1e-8, message)
elseif expected == actual then
DebugHelper.raise({
ScribuntoUnit = true,
text = string.format("Failed to assert that %s does not equal expected %s", tostring(actual), tostring(expected)),
actual = actual,
expected = expected,
message = message,
}, 2)
end
end

-------------------------------------------------------------------------------
-- Validates that both the expected and actual values are numbers
-- @param message optional description of the test
--
local function validateNumbers(expected, actual, message)
if type(expected) ~= "number" then
DebugHelper.raise({
ScribuntoUnit = true,
text = string.format("Expected value %s is not a number", tostring(expected)),
actual = actual,
expected = expected,
message = message,
}, 3)
end
if type(actual) ~= "number" then
DebugHelper.raise({
ScribuntoUnit = true,
text = string.format("Actual value %s is not a number", tostring(actual)),
actual = actual,
expected = expected,
message = message,
}, 3)
end
end

-------------------------------------------------------------------------------
-- Checks that 'actual' is within 'delta' of 'expected'.
-- @param message optional description of the test
-- @example assertWithinDelta(1/3, 3/9, 0.000001, "3/9 should be 1/3")
function ScribuntoUnit:assertWithinDelta(expected, actual, delta, message)
validateNumbers(expected, actual, message)
local diff = expected - actual
if diff delta then
DebugHelper.raise({
ScribuntoUnit = true,
text = string.format("Failed to assert that %f is within %f of expected %f", actual, delta, expected),
actual = actual,
expected = expected,
message = message,
}, 2)
end
end

-------------------------------------------------------------------------------
-- Checks that 'actual' is not within 'delta' of 'expected'.
-- @param message optional description of the test
-- @example assertNotWithinDelta(1/3, 2/3, 0.000001, "1/3 should not be 2/3")
function ScribuntoUnit:assertNotWithinDelta(expected, actual, delta, message)
validateNumbers(expected, actual, message)
local diff = expected - actual
if diff 0 then
mw.log('FAILURES!!!')
elseif testData.skipCount > 0 then
mw.log('Some tests could not be executed without a frame and have been skipped. Invoke this test suite as a template to run all tests.')
end
mw.log(string.format('Assertions: success: %d, error: %d, skipped: %d', testData.successCount, testData.failureCount, testData.skipCount))
mw.log('-------------------------------------------------------------------------------')
for _, result in ipairs(testData.results) do
if result.error then
mw.log(string.format('%s: %s', result.name, result.message))
end
end
end

function ScribuntoUnit:displayResultsAsShort(testData)
local text = string.format(cfg.shortResultsFormat, testData.successCount, testData.failureCount, testData.skipCount)
if testData.failureCount > 0 then
text = .. text ..
end
return text
end

function ScribuntoUnit:displayResultsAsTable(testData)
local successIcon, failIcon = self.frame:preprocess(cfg.successIndicator), self.frame:preprocess(cfg.failureIndicator)
local text =
if testData.failureCount > 0 then
local msg = mw.message.newRawMessage(cfg.failureSummary, testData.failureCount):plain()
msg = self.frame:preprocess(msg)
if cfg.failureCategory then
msg = cfg.failureCategory .. msg
end
text = text .. failIcon .. ' ' .. msg .. '\n'
else
text = text .. successIcon .. ' ' .. cfg.successSummary .. '\n'
end
text = text .. '\n'
return text
end

return ScribuntoUnit