Testing And Benchmarking in Lua
Here’s the translation of the Go testing and benchmarking example to Lua, formatted for Hugo:
-- Unit testing is an important part of writing principled Lua programs.
-- Lua doesn't have a built-in testing framework, but we can use a popular
-- third-party library like busted for unit testing.
-- For the sake of demonstration, this code is in a single file,
-- but it could be split into separate files. Testing code typically
-- lives in a separate file from the code it tests.
-- We'll be testing this simple implementation of an integer minimum.
local function int_min(a, b)
if a < b then
return a
end
return b
end
-- To use busted, we need to wrap our tests in a describe block
describe("int_min", function()
-- A test is created by using the it function
it("returns the minimum of two numbers", function()
local ans = int_min(2, -2)
-- assert is used to check conditions
assert.are.equal(-2, ans)
end)
-- Writing tests can be repetitive, so it's idiomatic to
-- use a data-driven style, where test inputs and
-- expected outputs are listed in a table and a single loop
-- walks over them and performs the test logic.
it("handles various input combinations", function()
local tests = {
{a = 0, b = 1, want = 0},
{a = 1, b = 0, want = 0},
{a = 2, b = -2, want = -2},
{a = 0, b = -1, want = -1},
{a = -1, b = 0, want = -1},
}
for _, tt in ipairs(tests) do
local ans = int_min(tt.a, tt.b)
assert.are.equal(tt.want, ans)
end
end)
end)
-- Lua doesn't have built-in benchmarking tools like Go,
-- but we can create a simple benchmarking function
local function benchmark_int_min()
local start = os.clock()
for i = 1, 1000000 do
int_min(1, 2)
end
local elapsed = os.clock() - start
print(string.format("BenchmarkIntMin: %.6f seconds", elapsed))
end
-- Run the benchmark
benchmark_int_min()
To run the tests and benchmark:
$ busted test_file.lua
●●
2 successes / 0 failures / 0 errors / 0 pending : 0.001196 seconds
$ lua test_file.lua
BenchmarkIntMin: 0.062500 seconds
In this Lua version:
We use the
busted
testing framework, which is a popular choice for Lua. It provides a structure similar to many modern testing frameworks.The
describe
andit
functions are used to organize and define tests, similar to theTestIntMinBasic
andTestIntMinTableDriven
functions in the Go version.We use
assert.are.equal
for assertions, which is similar to thet.Errorf
in Go.Lua doesn’t have built-in benchmarking tools like Go, so we created a simple benchmarking function that measures the time taken to run the
int_min
function a million times.The output format is different from Go’s, but it provides similar information about test success and benchmark performance.
Remember to install the busted
framework (luarocks install busted
) before running the tests. The benchmark can be run with the standard Lua interpreter.