### Getting Started with LuaUnit
Source: https://luaunit.readthedocs.io/en/latest/index.html
Guides on setting up test scripts, writing tests, grouping tests, and using the command-line interface.
```APIDOC
## Getting started with LuaUnit
### Setting up your test script
### Writing tests
### Grouping tests, setup/teardown functionality
### Using the command-line
### Conclusion
```
--------------------------------
### LuaUnit Installation and History
Source: https://luaunit.readthedocs.io/en/latest/index.html
Details on how to install LuaUnit and a history of its versions.
```APIDOC
## Installation
### History
* Version 3.5 - 26 March 2026
* Version 3.4 - 02 March 2021
* Version 3.3 - 6. March 2018
* Version 3.2 - 12. Jul 2016
* Version 3.1 - 10 Mar. 2015
* Version 3.0 - 9. Oct 2014
* Version 2.0
* Version 1.5 - 8. Nov 2012
* Version 1.4 - 26. Jul 2012
* Version 1.3 - 30. Oct 2007
* Version 1.2 - 13. Jun 2005
* Version 1.1
```
--------------------------------
### Implement setUp and tearDown for resource management
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
Use setUp and tearDown methods to prepare and clean up test environments. Errors in these methods are treated as test failures.
```lua
TestLogger = {}
function TestLogger:setUp()
-- define the fname to use for logging
self.fname = 'mytmplog.log'
-- make sure the file does not already exists
os.remove(self.fname)
end
function TestLogger:testLoggerCreatesFile()
initLog(self.fname)
log('toto')
-- make sure that our log file was created
f = io.open(self.fname, 'r')
lu.assertNotNil( f )
f:close()
end
function TestLogger:tearDown()
-- cleanup our log file after all tests
os.remove(self.fname)
end
```
--------------------------------
### LuaUnit Example Suite
Source: https://luaunit.readthedocs.io/en/latest/6_annexes.html
A comprehensive example script demonstrating function testing, assertion usage, and test suite organization in LuaUnit.
```lua
--
-- The examples described in the documentation are below.
--
lu = require('luaunit')
function add(v1,v2)
-- add positive numbers
-- return 0 if any of the numbers are 0
-- error if any of the two numbers are negative
if v1 < 0 or v2 < 0 then
error('Can only add positive or null numbers, received '..v1..' and '..v2)
end
if v1 == 0 or v2 == 0 then
return 0
end
return v1+v2
end
function adder(v)
-- return a function that adds v to its argument using add
function closure( x ) return x+v end
return closure
end
function div(v1,v2)
-- divide positive numbers
-- return 0 if any of the numbers are 0
-- error if any of the two numbers are negative
if v1 < 0 or v2 < 0 then
error('Can only divide positive or null numbers, received '..v1..' and '..v2)
end
if v1 == 0 or v2 == 0 then
return 0
end
return v1/v2
end
TestAdd = {}
function TestAdd:testAddPositive()
lu.assertEquals(add(1,1),2)
end
function TestAdd:testAddZero()
lu.assertEquals(add(1,0),0)
lu.assertEquals(add(0,5),0)
lu.assertEquals(add(0,0),0)
end
function TestAdd:testAddError()
lu.assertErrorMsgContains('Can only add positive or null numbers, received 2 and -3', add, 2, -3)
end
function TestAdd:testAdder()
f = adder(3)
lu.assertIsFunction( f )
lu.assertEquals( f(2), 5 )
end
-- end of table TestAdd
TestDiv = {}
function TestDiv:testDivPositive()
lu.assertEquals(div(4,2),2)
end
function TestDiv:testDivZero()
lu.assertEquals(div(4,0),0)
lu.assertEquals(div(0,5),0)
lu.assertEquals(div(0,0),0)
end
function TestDiv:testDivError()
lu.assertErrorMsgContains('Can only divide positive or null numbers, received 2 and -3', div, 2, -3)
end
-- end of table TestDiv
--[[
--
-- Uncomment this section to see how failures are displayed
--
TestWithFailures = {}
-- two failing tests
function TestWithFailures:testFail1()
lu.assertEquals( "toto", "titi")
end
function TestWithFailures:testFail2()
local a=1
local b='toto'
local c = a + b -- oops, can not add string and numbers
return c
end
-- end of table TestWithFailures
]]
--[[
TestLogger = {}
function TestLogger:setUp()
-- define the fname to use for logging
self.fname = 'mytmplog.log'
-- make sure the file does not already exists
os.remove(self.fname)
end
function TestLogger:testLoggerCreatesFile()
initLog(self.fname)
log('toto')
f = io.open(self.fname, 'r')
lu.assertNotNil( f )
f:close()
end
function TestLogger:tearDown()
self.fname = 'mytmplog.log'
-- cleanup our log file after all tests
os.remove(self.fname)
end
-- end of table TestLogger
]]
os.exit(lu.LuaUnit.run())
```
--------------------------------
### Import LuaUnit Library
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
Import the LuaUnit library at the beginning of your test script. This is the initial setup step for using LuaUnit.
```lua
lu = require('luaunit')
```
--------------------------------
### Configure Assertion Namespace
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Examples showing the transition from global assertion functions to module-prefixed functions, and how to re-enable global exports.
```lua
require('luaunit')
TestToto = {} --class
function TestToto:test1_withFailure()
local a = 1
assertEquals( a , 1 )
-- will fail
assertEquals( a , 2 )
end
[...]
```
```lua
-- the imported module must be stored
lu = require('luaunit')
TestToto = {} --class
function TestToto:test1_withFailure()
local a = 1
lu.assertEquals( a , 1 )
-- will fail
lu.assertEquals( a , 2 )
end
[...]
```
```lua
-- this works
EXPORT_ASSERT_TO_GLOBALS = true
require('luaunit')
TestToto = {} --class
function TestToto:test1_withFailure()
local a = 1
assertEquals( a , 1 )
-- will fail
assertEquals( a , 2 )
end
[...]
```
--------------------------------
### Define Test Suite Structure
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Example structure of test classes and methods used for demonstration.
```lua
-- class: TestAdd
TestAdd.testAddError
TestAdd.testAddPositive
TestAdd.testAddZero
TestAdd.testAdder
-- class: TestDiv
TestDiv.testDivError
TestDiv.testDivPositive
TestDiv.testDivZero
```
--------------------------------
### Execute LuaUnit test suite via command line
Source: https://luaunit.readthedocs.io/en/latest/0_readme.html
Example of running a Lua test file from the terminal and viewing the resulting failure analysis.
```bash
$ lua test_some_lists_comparison.lua
TestListCompare.test1 ... FAIL
test/some_lists_comparisons.lua:22: expected:
List difference analysis:
* lists A (actual) and B (expected) have the same size
* lists A and B start differing at index 9
* lists A and B are equal again from index 10
* Common parts:
= A[1], B[1]: 121221
= A[2], B[2]: 122211
= A[3], B[3]: 121221
= A[4], B[4]: 122211
= A[5], B[5]: 121221
= A[6], B[6]: 122212
= A[7], B[7]: 121212
= A[8], B[8]: 122112
* Differing parts:
- A[9]: 122121
+ B[9]: 121221
* Common parts at the end of the lists
= A[10], B[10]: 121212
= A[11], B[11]: 122121
```
--------------------------------
### Configure LuaUnit TAP Output Verbosity
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Examples of running LuaUnit test suites with different verbosity levels using the TAP output format.
```bash
$ lua my_test_suite_with_failures.lua -o tap
1..9
# Started on 02/24/17 22:09:31
# Starting class: TestAdd
ok 1 TestAdd.testAddError
ok 2 TestAdd.testAddPositive
ok 3 TestAdd.testAddZero
ok 4 TestAdd.testAdder
# Starting class: TestDiv
ok 5 TestDiv.testDivError
ok 6 TestDiv.testDivPositive
ok 7 TestDiv.testDivZero
# Starting class: TestWithFailures
not ok 8 TestWithFailures.testFail1
doc/my_test_suite_with_failures.lua:79: expected: "titi"
actual: "toto"
not ok 9 TestWithFailures.testFail2
doc/my_test_suite_with_failures.lua:85: attempt to perform arithmetic on local 'b' (a string value)
# Ran 9 tests in 0.005 seconds, 7 successes, 1 failure, 1 error
```
```bash
$ lua my_test_suite_with_failures.lua -o tap --verbose
1..9
# Started on 02/24/17 22:09:31
# Starting class: TestAdd
ok 1 TestAdd.testAddError
ok 2 TestAdd.testAddPositive
ok 3 TestAdd.testAddZero
ok 4 TestAdd.testAdder
# Starting class: TestDiv
ok 5 TestDiv.testDivError
ok 6 TestDiv.testDivPositive
ok 7 TestDiv.testDivZero
# Starting class: TestWithFailures
not ok 8 TestWithFailures.testFail1
doc/my_test_suite_with_failures.lua:79: expected: "titi"
actual: "toto"
stack traceback:
doc/my_test_suite_with_failures.lua:79: in function 'TestWithFailures.testFail1'
not ok 9 TestWithFailures.testFail2
doc/my_test_suite_with_failures.lua:85: attempt to perform arithmetic on local 'b' (a string value)
stack traceback:
[C]: in function 'xpcall'
# Ran 9 tests in 0.007 seconds, 7 successes, 1 failure, 1 error
```
--------------------------------
### Generate documentation with doit.py
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Run the 'makedoc' command via doit.py to generate HTML documentation using Sphinx. Ensure Sphinx is installed and available in your system's PATH.
```bash
doit.py makedoc
```
--------------------------------
### View test execution output
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
Example of the standard console output generated by running a LuaUnit test suite.
```text
Started on 02/19/17 22:15:53
TestAdd.testAddError ... Ok
TestAdd.testAddPositive ... Ok
TestAdd.testAddZero ... Ok
TestAdd.testAdder ... Ok
TestDiv.testDivError ... Ok
TestDiv.testDivPositive ... Ok
TestDiv.testDivZero ... Ok
=========================================================
Ran 7 tests in 0.006 seconds, 7 successes, 0 failures
OK
```
--------------------------------
### Run all unit tests with doit.py
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Use doit.py with the 'rununittests' command to execute all unit tests across all installed Lua versions on the system.
```bash
doit.py rununittests
```
--------------------------------
### Define Test Suite with Failures
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Example test suite structure containing intentional failures for demonstration purposes.
```lua
TestWithFailures = {}
-- two failing tests
function TestWithFailures:testFail1()
local a="toto"
local b="titi"
lu.assertEquals( a, b ) --oops, two values are not equal
end
function TestWithFailures:testFail2()
local a=1
local b='toto'
local c = a + b --oops, can not add string and numbers
return c
end
```
--------------------------------
### Organize tests into a table
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
Tests are grouped by placing them inside a table. The table name must start with 'Test' or 'test'.
```lua
TestAdd = {}
function TestAdd:testAddPositive()
lu.assertEquals(add(1,1),2)
end
function TestAdd:testAddZero()
lu.assertEquals(add(1,0),0)
lu.assertEquals(add(0,5),0)
lu.assertEquals(add(0,0),0)
end
function TestAdd:testAddError()
lu.assertErrorMsgContains('Can only add positive or null numbers, received 2 and -3', add, 2, -3)
end
function TestAdd:testAdder()
f = adder(3)
lu.assertIsFunction( f )
lu.assertEquals( f(2), 5 )
end
-- end of table TestAdd
```
```lua
TestDiv = {}
function TestDiv:testDivPositive()
lu.assertEquals(div(4,2),2)
end
function TestDiv:testDivZero()
lu.assertEquals(div(4,0),0)
lu.assertEquals(div(0,5),0)
lu.assertEquals(div(0,0),0)
end
function TestDiv:testDivError()
lu.assertErrorMsgContains('Can only divide positive or null numbers, received 2 and -3', div, 2, -3)
end
-- end of table TestDiv
```
--------------------------------
### View Assertion Error Output
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Example of the error message format generated by LuaUnit when an assertion fails.
```text
1) TestWithFailures.testFail1
doc\my_test_suite_with_failures.lua:79: expected: "titi"
actual: "toto"
```
--------------------------------
### LuaUnit Annexes
Source: https://luaunit.readthedocs.io/en/latest/index.html
Supplementary information including details on table printing, comparing tables, source code examples, and the project license.
```APIDOC
## Annexes
### Annex A: More on table printing
### Annex B: Comparing tables with keys of type table
### Annex C: Source code of example
### Annex D: BSD License
```
--------------------------------
### Junit XML Test Report Structure
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
This is an example of the Junit XML file generated by LuaUnit. It includes test suite details, individual test cases, and specific failure or error information.
```xml
```
--------------------------------
### Run unit tests
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Execute the unit test suite to verify changes.
```bash
$ lua run_unit_tests.lua
................................................................................
...............................
Ran 111 tests in 0.120 seconds
OK
```
--------------------------------
### Prepare release rock file with doit.py
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Create a rock file suitable for luarocks upload using 'doit.py buildrock'. This process clones the current git repository, generates documentation, and strips unnecessary files.
```bash
doit.py buildrock
```
--------------------------------
### Run tests from the command line
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
Execute test suites using the Lua interpreter and specify output formats like TAP.
```bash
$ lua doc/my_test_suite.lua
.......
Ran 7 tests in 0.003 seconds, 7 successes, 0 failures
OK
```
```bash
$ lua doc/my_test_suite.lua -o TAP
1..7
# Started on 02/19/17 22:15:53
# Starting class: TestAdd
ok 1 TestAdd.testAddError
ok 2 TestAdd.testAddPositive
ok 3 TestAdd.testAddZero
ok 4 TestAdd.testAdder
# Starting class: TestDiv
ok 5 TestDiv.testDivError
ok 6 TestDiv.testDivPositive
ok 7 TestDiv.testDivZero
```
--------------------------------
### Run all tests (luacheck, unit, functional) with doit.py
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Execute a comprehensive test suite by running 'doit.py runtests', which includes luacheck, unit tests, and functional tests, mimicking the continuous integration process.
```bash
doit.py runtests
```
--------------------------------
### Execute Test Suite with Default Output
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Default text output format showing test progress and failure details.
```bash
$ lua my_test_suite.lua
.......
Ran 7 tests in 0.002 seconds, 7 successes, 0 failures
OK
```
```bash
$ lua my_test_suite.lua
.......FE
Failed tests:
-------------
1) TestWithFailures.testFail1
doc\my_test_suite_with_failures.lua:79: expected: "titi"
actual: "toto"
stack traceback:
doc\my_test_suite_with_failures.lua:79: in function 'TestWithFailures.testFail1'
2) TestWithFailures.testFail2
doc\my_test_suite_with_failures.lua:85: attempt to perform arithmetic on local 'b' (a string value)
stack traceback:
[C]: in function 'xpcall'
Ran 9 tests in 0.001 seconds, 7 successes, 1 failure, 1 error
```
--------------------------------
### Run Test Suite with Default Arguments
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Execute the test suite by parsing command-line arguments. Returns the number of failures and errors, suitable for exit codes.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
os.exit(runner.runSuite())
```
--------------------------------
### Compare lists with assertEquals
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Demonstrates how LuaUnit provides detailed difference analysis when comparing two tables used as lists.
```lua
-- lua test code. Can you spot the difference ?
function TestListCompare:test1()
local A = { 121221, 122211, 121221, 122211, 121221, 122212, 121212, 122112, 122121, 121212, 122121 }
local B = { 121221, 122211, 121221, 122211, 121221, 122212, 121212, 122112, 121221, 121212, 122121 }
lu.assertEquals( A, B )
end
$ lua test_some_lists_comparison.lua
TestListCompare.test1 ... FAIL
test/some_lists_comparisons.lua:22: expected:
List difference analysis:
* lists A (actual) and B (expected) have the same size
* lists A and B start differing at index 9
* lists A and B are equal again from index 10
* Common parts:
= A[1], B[1]: 121221
= A[2], B[2]: 122211
= A[3], B[3]: 121221
= A[4], B[4]: 122211
= A[5], B[5]: 121221
= A[6], B[6]: 122212
= A[7], B[7]: 121212
= A[8], B[8]: 122112
* Differing parts:
- A[9]: 122121
+ B[9]: 121221
* Common parts at the end of the lists
= A[10], B[10]: 121212
= A[11], B[11]: 122121
```
--------------------------------
### Run All Tests
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Execute all tests to ensure functionality. This command is used to verify the state of the project after version updates.
```bash
doit.py runtests
```
--------------------------------
### Assert Value Identity
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Use assertIs to check if two variables are identical. For primitive types like strings and numbers, this is similar to assertEquals. For other types, it checks if they refer to the same object. Example demonstrates usage with strings, tables, and nil/boolean.
```lua
assertIs(_actual_ , _expected_[, _extra_msg_])
```
```lua
s1='toto'
s2='to'..'to'
t1={1,2}
t2={1,2}
v1=nil
v2=false
lu.assertIs(s1,s1) -- ok
lu.assertIs(s1,s2) -- ok
lu.assertIs(t1,t1) -- ok
lu.assertIs(t1,t2) -- fail
lu.assertIs(v1,v2) -- fail
```
--------------------------------
### Run LuaUnit Test Suite
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
Execute your test script using LuaUnit. This command runs all discovered tests and exits with an appropriate status code. The '-v' flag enables verbose output.
```bash
lua my_test_suite.lua
```
```bash
lua my_test_suite.lua -v
```
--------------------------------
### Global vs. Module-Level Functions
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Explains the evolution of LuaUnit's function export behavior, from global exports to module-level access, and how to configure it.
```APIDOC
## Enabling global or module-level functions
### Description
This section describes the change in LuaUnit's practice regarding the export of assertion functions. Previously, functions were exported to the global namespace. The recommended practice now is to access them via the `lu` module.
### Obsolete Practice (Global Exports)
```lua
require('luaunit')
TestToto = {} --class
function TestToto:test1_withFailure()
local a = 1
assertEquals( a , 1 ) -- Global function
-- will fail
assertEquals( a , 2 ) -- Global function
end
[...]---
```
### Recommended Practice (Module-Level Access)
```lua
-- the imported module must be stored
lu = require('luaunit')
TestToto = {} --class
function TestToto:test1_withFailure()
local a = 1
lu.assertEquals( a , 1 ) -- Module-level function
-- will fail
lu.assertEquals( a , 2 ) -- Module-level function
end
[...]---
```
### Enabling Global Exports (for older versions or preference)
To maintain the old behavior of exporting assertion functions to the global namespace, set the `EXPORT_ASSERT_TO_GLOBALS` variable to `true` before requiring `luaunit`.
```lua
-- this works
EXPORT_ASSERT_TO_GLOBALS = true
require('luaunit')
TestToto = {} --class
function TestToto:test1_withFailure()
local a = 1
assertEquals( a , 1 ) -- Global function
-- will fail
assertEquals( a , 2 ) -- Global function
end
[...]---
```
```
--------------------------------
### LuaUnit Reference Documentation
Source: https://luaunit.readthedocs.io/en/latest/index.html
Detailed reference for LuaUnit features, including command-line options, runner object, skipping/failing tests, output formats, test execution, and assertion functions.
```APIDOC
## Reference documentation
### Index and Search page
### Command-line options
#### Output formats
#### Other options
#### Flexible test selection
#### Test naming
### LuaUnit runner object
### Skipping and ending test
#### Test skipping
#### Force test failing
#### Force test success
### Output formats details
#### Text format
#### JUNIT format
#### TAP format
#### NIL format
### Test collection and execution process
#### Test collection
#### Test execution
### Assertions functions
#### Equality assertions
#### Value assertions
#### String assertions
#### Error assertions
#### Type assertions
#### Table assertions
#### Scientific computing and LuaUnit
#### EPS _constant_
#### Pretty printing
### Enabling global or module-level functions
### Variables controlling LuaUnit behavior
#### luaunit.ORDER_ACTUAL_EXPECTED
#### luaunit.PRINT_TABLE_REF_IN_ERROR_MSG
#### luaunit.STRIP_EXTRA_ENTRIES_IN_STACK_TRACE
#### luaunit.VERSION
```
--------------------------------
### Compare lists with LuaUnit assertions
Source: https://luaunit.readthedocs.io/en/latest/0_readme.html
Demonstrates using lu.assertEquals to compare two tables, which triggers a detailed difference analysis in the output.
```lua
-- lua test code. Can you spot the difference ?
function TestListCompare:test1()
local A = { 121221, 122211, 121221, 122211, 121221, 122212, 121212, 122112, 122121, 121212, 122121 }
local B = { 121221, 122211, 121221, 122211, 121221, 122212, 121212, 122112, 121221, 121212, 122121 }
lu.assertEquals( A, B )
end
```
--------------------------------
### Package project for release with doit.py
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Generate zip and tar.gz archives for GitHub release using 'doit.py packageit'. The archives contain the current git content, excluding CI files but including full documentation.
```bash
doit.py packageit
```
--------------------------------
### Write Basic Addition Tests
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
These LuaUnit tests verify the 'add' function's behavior for positive numbers and cases involving zero. `lu.assertEquals` is used to compare the actual result with the expected outcome.
```lua
function testAddPositive()
lu.assertEquals(add(1,1),2)
end
function testAddZero()
lu.assertEquals(add(1,0),0)
lu.assertEquals(add(0,5),0)
lu.assertEquals(add(0,0),0)
end
```
--------------------------------
### Run Test Suite with Pattern Matching
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Execute specific tests that match a given pattern. This allows for targeted test execution based on naming conventions.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
-- execute tests matching the 'withXY' pattern
os.exit(runner.runSuite('--pattern', 'withXY'))
```
--------------------------------
### Execute Test Suite with Verbose Output
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Verbose text output format providing per-test status and detailed stack traces.
```bash
$ lua doc\my_test_suite_with_failures.lua --verbose
Started on 02/20/17 21:47:21
TestAdd.testAddError ... Ok
TestAdd.testAddPositive ... Ok
TestAdd.testAddZero ... Ok
TestAdd.testAdder ... Ok
TestDiv.testDivError ... Ok
TestDiv.testDivPositive ... Ok
TestDiv.testDivZero ... Ok
TestWithFailures.testFail1 ... FAIL
doc\my_test_suite_with_failures.lua:79: expected: "titi"
actual: "toto"
TestWithFailures.testFail2 ... ERROR
doc\my_test_suite_with_failures.lua:85: attempt to perform arithmetic on local 'b' (a string value)
=========================================================
Failed tests:
-------------
1) TestWithFailures.testFail1
doc\my_test_suite_with_failures.lua:79: expected: "titi"
actual: "toto"
stack traceback:
doc\my_test_suite_with_failures.lua:79: in function 'TestWithFailures.testFail1'
2) TestWithFailures.testFail2
doc\my_test_suite_with_failures.lua:85: attempt to perform arithmetic on local 'b' (a string value)
stack traceback:
[C]: in function 'xpcall'
Ran 9 tests in 0.008 seconds, 7 successes, 1 failure, 1 error
```
--------------------------------
### CLI Execution Command
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
The standard command-line interface for running LuaUnit test suites.
```APIDOC
## CLI Execution
### Description
Executes a Lua test suite file with optional filters and configuration flags.
### Usage
`lua [options] [testname1 [testname2] …]`
### Options
- **--output, -o** (string) - Optional - Set output format (text, tap, junit, nil).
- **--name, -n** (string) - Optional - Filename for junit XML output.
- **--pattern, -p** (string) - Optional - Lua pattern to include specific tests.
- **--exclude, -x** (string) - Optional - Lua pattern to exclude specific tests.
- **--test-prefix, -t** (string) - Optional - Prefix for detecting test tables or functions.
- **--test-suffix, -T** (string) - Optional - Suffix for detecting test tables or functions.
- **--method-prefix, -m** (string) - Optional - Prefix for test methods.
- **--repeat, -r** (number) - Optional - Repeat tests NUM times.
- **--shuffle, -s** (boolean) - Optional - Shuffle tests before running.
- **--error, -e** (boolean) - Optional - Stop on first error.
- **--failure, -f** (boolean) - Optional - Stop on first failure or error.
- **--verbose, -v** (boolean) - Optional - Increase verbosity.
- **--quiet, -q** (boolean) - Optional - Set verbosity to minimum.
- **--help, -h** (boolean) - Optional - Print help.
- **--version** (boolean) - Optional - Print version information.
```
--------------------------------
### Run specific tests via command line
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
Execute specific test tables or methods by passing them as arguments to the test suite script.
```bash
$ lua doc/my_test_suite.lua TestAdd TestDiv.testDivError -v
```
--------------------------------
### Clone LuaUnit repository
Source: https://luaunit.readthedocs.io/en/latest/0_readme.html
Use this command to fetch the latest stable version of LuaUnit from GitHub.
```bash
git clone git@github.com:bluebird75/luaunit.git
```
--------------------------------
### luaunit.VERSION
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Provides the current version of the LuaUnit library as a string.
```APIDOC
## luaunit.VERSION
### Description
Current version of LuaUnit as a string.
### Example Usage
```lua
print(luaunit.VERSION)
```
```
--------------------------------
### Run luacheck syntax check with doit.py
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Execute the 'luacheck' command using the doit.py utility to perform a syntax check on the LuaUnit code.
```bash
doit.py luacheck
```
--------------------------------
### Generate GitHub Package
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Create a package suitable for distribution via GitHub. This command is part of the release process to bundle the project.
```bash
doit.py packageit
```
--------------------------------
### LuaUnit Runner Methods
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Methods to configure and execute LuaUnit test suites programmatically.
```APIDOC
## LuaUnit.new()
### Description
Creates a new LuaUnit runner object to control test suite execution.
### Method
Static
### Response
- **runner** (object) - A new LuaUnit runner instance.
---
## runner:setVerbosity(verbosity)
### Description
Sets the verbosity level of the runner.
### Parameters
#### Request Body
- **verbosity** (integer) - Required - Value ranging from lu.VERBOSITY_QUIET to lu.VERBOSITY_VERBOSE.
---
## runner:setOutputType(type[, junit_fname])
### Description
Sets the output format for the test suite results.
### Parameters
#### Request Body
- **type** (string) - Required - The output format type.
- **junit_fname** (string) - Optional - Filename for XML output when format is 'junit'.
---
## runner:runSuite([arguments])
### Description
Executes the test suite. If no arguments are provided, it parses command-line arguments.
### Parameters
#### Request Body
- **arguments** (string/list) - Optional - Command-line style arguments or specific test names to execute.
### Response
- **exit_code** (integer) - Returns the number of failures and errors (0 on success).
---
## LuaUnit.run([arguments])
### Description
Static helper to create a runner and execute tests immediately.
### Parameters
#### Request Body
- **arguments** (string/list) - Optional - Arguments passed to the internal runner.
---
## runner:runSuiteByInstances(listOfNameAndInstances[, arguments])
### Description
Runs specific test instances provided as a list, bypassing global test collection.
### Parameters
#### Request Body
- **listOfNameAndInstances** (table) - Required - A list of {name, test_instance} pairs.
- **arguments** (string/list) - Optional - Command-line style arguments.
```
--------------------------------
### Comparing tables with table keys
Source: https://luaunit.readthedocs.io/en/latest/6_annexes.html
LuaUnit treats tables as keys based on their reference, not their content.
```lua
local lu = require('luaunit')
-- let's define two tables
t1 = { 1, 2 }
t2 = { 1, 2 }
lu.assertEquals( t1, t2 ) -- succeeds
-- let's define three tables, with the two above tables as keys
t3 = { t1='a' }
t4 = { t2='a' }
t5 = { t2='a' }
```
```lua
lu.assertEquals( t3, t4 ) -- fails
```
```lua
lu.assertEquals( t4, t5 ) -- fails
```
--------------------------------
### Run Tests with NIL Output Format
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Executes tests without displaying output, relying solely on the command exit code.
```bash
$ lua my_test_suite_with_failures.lua -o nil --verbose
$
```
--------------------------------
### Generate TAP Output
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Use the 'tap' format with the --output flag and the --quiet flag for minimal verbosity. This command generates a TAP-compatible report on standard output.
```bash
$ lua my_test_suite_with_failures.lua -o tap --quiet
1..9
# Started on 02/24/17 22:09:31
# Starting class: TestAdd
ok 1 TestAdd.testAddError
ok 2 TestAdd.testAddPositive
ok 3 TestAdd.testAddZero
ok 4 TestAdd.testAdder
# Starting class: TestDiv
ok 5 TestDiv.testDivError
ok 6 TestDiv.testDivPositive
ok 7 TestDiv.testDivZero
# Starting class: TestWithFailures
not ok 8 TestWithFailures.testFail1
not ok 9 TestWithFailures.testFail2
```
--------------------------------
### Run Tests Directly via LuaUnit Table
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Execute tests by calling the `run` function directly on the `LuaUnit` table. This internally creates a runner and passes arguments.
```lua
-- execute tests matching the 'withXY' pattern
os.exit(lu.LuaUnit.run('--pattern', 'withXY'))
```
--------------------------------
### Run Tests by Explicit Instances
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Execute tests provided as explicit instances (functions or tables) without global collection. Useful for modular test organization.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
os.exit(runner.runSuiteByInstances( {'mySpecialTest1', mySpecialTest1}, {'mySpecialTest2', mySpecialTest2} } )
```
--------------------------------
### Create and Use LuaUnit Runner
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Instantiate a LuaUnit runner object to control test suite execution. This is the primary way to manage test runs programmatically.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
-- use the runner object...
runner.runSuite()
```
--------------------------------
### Format Tables with prettystr
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Converts complex tables into a readable string format for debugging purposes.
```lua
> lu = require('luaunit')
> t1 = {1,2,3}
> t1['toto'] = 'titi'
> t1.f = function () end
> t1.fa = (1 == 0)
> t1.tr = (1 == 1)
> print( lu.prettystr(t1) )
{1, 2, 3, f=function: 00635d68, fa=false, toto="titi", tr=true}
```
--------------------------------
### Generate Junit XML Output
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Use the 'junit' format with the --output flag and specify the filename with --name. This command generates an XML file containing detailed test results, including failures and errors.
```bash
$ lua my_test_suite_with_failures.lua -o junit -n toto.xml
# XML output to toto.xml
# Started on 02/24/17 09:54:59
# Starting class: TestAdd
# Starting test: TestAdd.testAddError
# Starting test: TestAdd.testAddPositive
# Starting test: TestAdd.testAddZero
# Starting test: TestAdd.testAdder
# Starting class: TestDiv
# Starting test: TestDiv.testDivError
# Starting test: TestDiv.testDivPositive
# Starting test: TestDiv.testDivZero
# Starting class: TestWithFailures
# Starting test: TestWithFailures.testFail1
# Failure: doc/my_test_suite_with_failures.lua:79: expected: "titi"
# actual: "toto"
# Starting test: TestWithFailures.testFail2
# Error: doc/my_test_suite_with_failures.lua:85: attempt to perform arithmetic on local 'b' (a string value)
# Ran 9 tests in 0.007 seconds, 7 successes, 1 failure, 1 error
```
--------------------------------
### assertMinusZero
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Asserts that a number is negative zero (-0).
```APIDOC
## assertMinusZero
### Description
Assert that a given number is _-0_, according to the definition of IEEE-754. The verification is done by dividing by the provided number and verifying that it yields _minus infinity_. If provided, _extra_msg_ is a string which will be printed along with the failure message.
Be careful when dealing with _+0_ and _-0_ , see MinusZero
**Alias**: _assert_minus_zero()_
```
--------------------------------
### Run Tests with Inclusion Patterns
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Use the --pattern or -p flag to execute only tests matching specific Lua patterns.
```bash
$ lua mytest_suite.lua -v -p Err.r -p Z.ro
Started on 02/19/17 22:29:45
TestAdd.testAddError ... Ok
TestAdd.testAddZero ... Ok
TestDiv.testDivError ... Ok
TestDiv.testDivZero ... Ok
=========================================================
Ran 4 tests in 0.004 seconds, 4 successes, 0 failures, 3 non-selected
OK
```
--------------------------------
### Configure LuaUnit assertion order
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Sets the global order for equality assertions to expected-actual instead of the default actual-expected.
```lua
lu.ORDER_ACTUAL_EXPECTED=false
```
--------------------------------
### Build LuaRocks Package
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Generate the package for LuaRocks, the Lua package manager. This step is crucial for distributing LuaUnit to the Lua community.
```bash
doit.py buildrock
```
--------------------------------
### Variables Controlling LuaUnit Behavior
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Documentation for configuration variables that control LuaUnit's behavior, such as argument order and table reference printing.
```APIDOC
## Variables controlling LuaUnit behavior
### luaunit.ORDER_ACTUAL_EXPECTED
This boolean value defines the order of arguments in assertion functions. By default, the first argument is treated as the actual (calculated) value and the second as the expected (reference) value. Setting this to `false` reverses this convention.
**Default:** `true` (Actual, Expected)
**Example Error Message (Default):**
```
1) TestWithFailures.testFail1
doc\my_test_suite_with_failures.lua:79: expected: "titi"
actual: "toto"
```
### luaunit.PRINT_TABLE_REF_IN_ERROR_MSG
This controls whether table references are always printed along with tables in error messages. The default is `false`.
**Default:** `false`
```
--------------------------------
### Run Specific Tests by Name
Source: https://luaunit.readthedocs.io/en/latest/4_reference_doc.html
Execute a predefined list of tests by their explicit names. This provides precise control over which tests are run.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
os.exit(runner.runSuite('testABC', 'testDEF'))
```
--------------------------------
### Define Function to Test
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
This Lua function 'add' is designed to add positive numbers, return 0 if either number is 0, and raise an error for negative inputs. It serves as the target for subsequent test cases.
```lua
function add(v1,v2)
-- add positive numbers
-- return 0 if any of the numbers are 0
-- error if any of the two numbers are negative
if v1 < 0 or v2 < 0 then
error('Can only add positive or null numbers, received '..v1..' and '..v2)
end
if v1 == 0 or v2 == 0 then
return 0
end
return v1+v2
end
```
--------------------------------
### Developing LuaUnit
Source: https://luaunit.readthedocs.io/en/latest/index.html
Information for developers on the LuaUnit development ecosystem, contributing guidelines, and the process for releasing new versions.
```APIDOC
## Developing LuaUnit
### Development ecosystem
### Contributing
#### Running unit-tests
#### Running functional tests
#### Modifying reference files for functional tests
#### Typical failures for functional tests
#### Using doit.py
### Process of releasing a new version of LuaUnit
```
--------------------------------
### Define a division function for testing
Source: https://luaunit.readthedocs.io/en/latest/3_getting-started.html
A sample function to be tested, which raises errors for negative inputs.
```lua
function div(v1,v2)
-- divide positive numbers
-- return 0 if any of the numbers are 0
-- error if any of the two numbers are negative
if v1 < 0 or v2 < 0 then
error('Can only divide positive or null numbers, received '..v1..' and '..v2)
end
if v1 == 0 or v2 == 0 then
return 0
end
return v1/v2
end
```
--------------------------------
### Update specific reference files for functional tests
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Use the --update option with specific arguments to overwrite only the relevant reference files for functional tests. This is useful for recording changes in specific output formats like XML, TAP, or text.
```bash
$ lua run_functional_tests.lua --update ErrFailPassXml ErrFailPassTap ErrFailPassText
>>>>>>> Generating test/ref/errFailPassXmlDefault.txt
>>>>>>> Generating test/ref/errFailPassXmlDefault-success.txt
>>>>>>> Generating test/ref/errFailPassXmlDefault-failures.txt
>>>>>>> Generating test/ref/errFailPassXmlQuiet.txt
>>>>>>> Generating test/ref/errFailPassXmlQuiet-success.txt
>>>>>>> Generating test/ref/errFailPassXmlQuiet-failures.txt
>>>>>>> Generating test/ref/errFailPassXmlVerbose.txt
>>>>>>> Generating test/ref/errFailPassXmlVerbose-success.txt
>>>>>>> Generating test/ref/errFailPassXmlVerbose-failures.txt
>>>>>>> Generating test/ref/errFailPassTapDefault.txt
>>>>>>> Generating test/ref/errFailPassTapDefault-success.txt
>>>>>>> Generating test/ref/errFailPassTapDefault-failures.txt
>>>>>>> Generating test/ref/errFailPassTapQuiet.txt
>>>>>>> Generating test/ref/errFailPassTapQuiet-success.txt
>>>>>>> Generating test/ref/errFailPassTapQuiet-failures.txt
>>>>>>> Generating test/ref/errFailPassTapVerbose.txt
>>>>>>> Generating test/ref/errFailPassTapVerbose-success.txt
>>>>>>> Generating test/ref/errFailPassTapVerbose-failures.txt
>>>>>>> Generating test/ref/errFailPassTextDefault.txt
>>>>>>> Generating test/ref/errFailPassTextDefault-success.txt
>>>>>>> Generating test/ref/errFailPassTextDefault-failures.txt
>>>>>>> Generating test/ref/errFailPassTextQuiet.txt
>>>>>>> Generating test/ref/errFailPassTextQuiet-success.txt
>>>>>>> Generating test/ref/errFailPassTextQuiet-failures.txt
>>>>>>> Generating test/ref/errFailPassTextVerbose.txt
>>>>>>> Generating test/ref/errFailPassTextVerbose-success.txt
>>>>>>> Generating test/ref/errFailPassTextVerbose-failures.txt
$
```
--------------------------------
### Run functional tests
Source: https://luaunit.readthedocs.io/en/latest/5_developing.html
Execute the functional test suite to validate output consistency across different formats and environments.
```bash
$ lua run_functional_tests.lua
...............
Ran 15 tests in 9.676 seconds
OK
```