-- Minimal dependency-free test framework. -- Provides: describe, it, before_each, expect, TestHarness_report -- -- expect(value) returns an object with bound matcher methods, so matchers are -- called with dot syntax: expect(x).toEqual(y).toBeTruthy() local Harness = { passed = 0, failed = 0, failures = {}, current_describe = "", before_each_fn = nil, } local function deep_equal(a, b) if a == b then return true end if type(a) ~= "table" or type(b) ~= "table" then return false end for k, v in pairs(a) do if not deep_equal(v, b[k]) then return false end end for k in pairs(b) do if a[k] == nil then return false end end return true end local function fmt(v) if type(v) == "table" then local parts = {} for k, val in pairs(v) do table.insert(parts, tostring(k) .. "=" .. tostring(val)) end return "{" .. table.concat(parts, ", ") .. "}" end return tostring(v) end local function fail(message) error(message, 2) end function expect(value) local exp = {} function exp.toEqual(expected) if not deep_equal(value, expected) then fail(string.format("expected %s to equal %s", fmt(value), fmt(expected))) end return exp end function exp.toBeTruthy() if not value then fail("expected truthy, got " .. fmt(value)) end return exp end function exp.toBeFalsy() if value then fail("expected falsy, got " .. fmt(value)) end return exp end function exp.toBeNil() if value ~= nil then fail("expected nil, got " .. fmt(value)) end return exp end function exp.toBeAtLeast(min) if not (value >= min) then fail(string.format("expected %s >= %s", fmt(value), fmt(min))) end return exp end function exp.toBeAtMost(max) if not (value <= max) then fail(string.format("expected %s <= %s", fmt(value), fmt(max))) end return exp end function exp.toBeCloseTo(expected, tolerance) tolerance = tolerance or 0.0001 if math.abs(value - expected) > tolerance then fail(string.format("expected %s close to %s (tolerance %s)", fmt(value), fmt(expected), fmt(tolerance))) end return exp end function exp.lengthIs(expected) if #value ~= expected then fail(string.format("expected length %d, got %d", expected, #value)) end return exp end return exp end function describe(name, fn) Harness.current_describe = name Harness.before_each_fn = nil fn() Harness.before_each_fn = nil end function before_each(fn) Harness.before_each_fn = fn end function it(name, fn) if Harness.before_each_fn then Harness.before_each_fn() end local ok, err = pcall(fn) if ok then Harness.passed = Harness.passed + 1 else Harness.failed = Harness.failed + 1 table.insert(Harness.failures, Harness.current_describe .. " > " .. name .. ":\n " .. tostring(err)) end end function TestHarness_report() print(string.format("\n%d passed, %d failed", Harness.passed, Harness.failed)) for _, failure in ipairs(Harness.failures) do print(" FAIL: " .. failure) end return Harness.failed == 0 end