Testy is a quick-and-dirty unit testing script for Lua modules
that tries to be as unobtrusive as possible. It loads the specified
modules and collects test functions from local variables by means
of debug hooks. Finally, those test functions are run to collect
and print statistics about passed/failed test assertions.
Nice features about this approach are:
- By storing the test code side-by-side with your regular module
code it should be easier to keep those two in sync.
- You can test internal/local functions without messing up your
public interface (because the test functions themselves are
local functions embedded in the module code as well).
- If you don’t load the module via the
testy.lua
script, the
local test functions and all test data just goes out of scope
and gets garbage-collected very quickly.
The current implementation consists of a single pure Lua file
compatible with Lua 5.1 and up, with no external dependencies.
The testy.lua
source code is available on GitHub, and is
released under the MIT license. You can view a nice HTML
version of this file rendered by Docco on the GitHub
pages.
Test functions are identified by a "test_"
prefix and use the
standard assert
function or the new testy_assert
function for
individual test assertions. Both functions just log failure/success
and print a visual indicator to the console, but they do not
terminate the program (of course assert
still does when used
outside of a test function for compatibility).
Here is an example:
local M = {}
function M.func1()
return 1
end
local function test_func1()
assert( M.func1() == 1, "func1() should always return 1" )
assert( M.func1() ~= 2, "func1() should never return 2" )
assert( type( M.func1() ) == "number" )
end
function M.func2()
return 2
end
local function test_func2()
assert( M.func2() == 2 )
assert( M.func2() ~= M.func1() )
end
return M
Using the testy.lua
script on this file will get you the
following output:
$ testy.lua module1.lua
func1 ('module1.lua') ...
func2 ('module1.lua') ..
5 tests (5 ok, 0 failed, 0 errors)
Testy is a very minimal unit testing framework that lacks lots
of features that other unit testing frameworks have, but in return
you can start unit testing without a learning curve.
Implementation