JanetRossini.github.io

Lua, LSL, Blender, Python in Second Life


Project maintained by JanetRossini

Test Framework Upgrade

May 14, 2025 • [luatesting]


I wanted a small update to the testing framework, which I’ll explain below. Here is the new version:

Tests = {}

local test_correct
local test_wrong
function Tests:assert_equals(result, expected, message)
   local message = message or ""
   local correct = result == expected
   if correct then
      test_correct += 1
   else
      test_wrong += 1
      self:diagnose(result, 'was expected to  be', expected, message)
      -- print(`{message}:{result} == {expected} {correct}`)
   end
end

function Tests:assert_nearly_equal(result, expected, delta, message)
   local message = message or ""
   correct = ll.Fabs(result-expected) <= delta
   if correct then
      test_correct += 1
   else
      test_wrong += 1
      self:diagnose(result, `should be within {delta} of`, expected, message)
   end
end

function Tests:run_tests(verbose)
   test_correct = 0
   test_wrong = 0
   for k, v in pairs(Tests) do
      if k:sub(1, 5) == 'test_' then
         Tests.current_name = k
         if verbose then print(k) end
         v(Tests)
      end
   end
   print(`Tests: correct {test_correct}, wrong {test_wrong}`)
end

function Tests:diagnose(result, check_name, expected, message)
   print(`{self.current_name}: {result} {check_name} {expected} ({message})`)
end

I moved the assert functions to be methods of the object Tests, and changed the error messages to use the new diagnose method. The diagnose now prepends error messages with the name of the test, e.g. test_this_thing, and includes a description of the error that is created by the individual assert. So:

self:assert_nearly_equal(30, 15, 1, "unlikely comparison")
-- should print
test_foo: 30 should be within 1 of 15 (unlikely comparison)

It is my practice to upgrade my tools when I get what seems a better idea. Here, my main point was to make the free-standing assert functions into methods on the Tests object, and then the duplication in the error printing induced me to write diagnose.

I find that keeping my tools sharp helps me make steady progress in my work.

Until next time, safe paths!