### LuaUnit Example Source Code
Source: https://github.com/bluebird75/luaunit/blob/main/doc/6_annexes.md
This Lua script contains the full source code for the example used in the Getting Started guide. It includes functions for addition and division, along with corresponding test cases using LuaUnit assertions.
```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())
```
--------------------------------
### TAP Report Example (Full Verbosity)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
This example shows the beginning of a TAP report with full verbosity, indicating extensive output details.
```text
$ lua my_test_suite_with_failures.lua -o tap --verbose
1..9
# Started on 02/24/17 22:09:31
```
--------------------------------
### Logger Test Setup and Execution
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Tests for a logging function, utilizing setUp and tearDown to manage a log file. The setUp ensures the file doesn't exist, and tearDown removes it after each test.
```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
```
--------------------------------
### Test Execution Summary
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Example output showing the execution summary of a test suite, including the start time, individual test results, and overall success metrics.
```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
```
--------------------------------
### Command-Line Test Execution (Text Format)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Example of running LuaUnit tests from the command line using the default non-verbose text output format.
```text
$ lua doc/my_test_suite.lua
.......
Ran 7 tests in 0.003 seconds, 7 successes, 0 failures
OK
```
--------------------------------
### Command-Line Test Execution (TAP Format)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Example of running LuaUnit tests from the command line with the TAP (Test Anything Protocol) output format specified.
```text
$ 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
```
--------------------------------
### Clone LuaUnit Repository
Source: https://github.com/bluebird75/luaunit/blob/main/README.rst
Clone the LuaUnit repository from GitHub to get the latest version. This is the simplest way to install LuaUnit.
```bash
git clone git@github.com:bluebird75/luaunit.git
```
--------------------------------
### TAP Report Example (Minimal Verbosity)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
This TAP output shows a concise summary of test results with minimal output, suitable for basic CI integration.
```text
$ 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
# Ran 9 tests in 0.003 seconds, 7 successes, 1 failure, 1 error
```
--------------------------------
### Generate LuaUnit Documentation
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Run 'doit.py makedoc' to generate HTML documentation using Sphinx. Ensure Sphinx is installed and available in your system's PATH.
```shell
doit.py makedoc
```
--------------------------------
### Run All LuaUnit Unit Tests
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Use 'doit.py rununittests' to execute all unit tests across all installed Lua versions on the system.
```shell
doit.py rununittests
```
--------------------------------
### TAP Report Example (Default Verbosity)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
The default TAP output includes detailed diagnostic information for test failures and errors directly within the report.
```text
$ 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
```
--------------------------------
### JUnit XML Test Report Example
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
This XML output conforms to the Jenkins/Hudson schema and provides detailed test case information, including failures and errors.
```xml
```
--------------------------------
### TestListener: Starting a Test
Source: https://github.com/bluebird75/luaunit/blob/main/junitxml/XMLJUnitResultFormatter.java.txt
Records the start time of a test when the startTest method is called. This is part of the TestListener interface.
```Java
/**
* Interface TestListener.
*
*
A new Test is started.
* @param t the test.
*/
public void startTest(Test t) {
testStarts.put(t, new Long(System.currentTimeMillis()));
}
```
--------------------------------
### LuaUnit List Comparison Output
Source: https://github.com/bluebird75/luaunit/blob/main/doc/0_readme.md
This is an example of the output generated by LuaUnit when a list comparison fails. It provides a detailed analysis of the differences between the actual and expected lists, including common and differing parts.
```sh
$ 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
```
--------------------------------
### Example of Absolute vs. Relative Error Calculation
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Demonstrates the difference between absolute and relative error calculations for floating-point comparisons. It shows how relative error is more consistent and suitable for assertions with default margins.
```lua
-- convert pi/6 radian to 30 degree
pi_div_6_deg_calculated = math.deg(math.pi/6)
pi_div_6_deg_expected = 30
-- convert pi/3 radian to 60 degree
pi_div_3_deg_calculated = math.deg(math.pi/3)
pi_div_3_deg_expected = 60
-- check absolute error: it is not constant
print( (pi_div_6_deg_expected - pi_div_6_deg_calculated) / lu.EPS ) -- prints: 16
print( (pi_div_3_deg_expected - pi_div_3_deg_calculated) / lu.EPS ) -- prints: 3
-- The difference between expected value and calculated value is bigger than the machine epsilon, so
-- it will fail an assertAlmostEquals with default margin. You could supply a bigger margin, but it is not a
-- good solution because the error is not constant and it will be bigger for some calculations than for others.
-- A better approach is to use relative error:
print( ( (pi_div_6_deg_expected - pi_div_6_deg_calculated) / pi_div_6_deg_expected) / lu.EPS ) -- prints: 0.53333
print( ( (pi_div_3_deg_expected - pi_div_3_deg_calculated) / pi_div_3_deg_expected) / lu.EPS ) -- prints: 0.53333
-- By dividing the error by the expected value, we get a constant error for both calculations, which is less than
-- the machine epsilon. This is more reliable and assertAlmostEquals() will succeed with the default margin.
-- relative error is constant. Assertion can take the form of:
assertAlmostEquals( (pi_div_6_deg_expected - pi_div_6_deg_calculated) / pi_div_6_deg_expected, lu.EPS )
assertAlmostEquals( (pi_div_3_deg_expected - pi_div_3_deg_calculated) / pi_div_3_deg_expected, lu.EPS )
-- or simply (relying on the default margin):
assertAlmostEquals( (pi_div_6_deg_expected - pi_div_6_deg_calculated) / pi_div_6_deg_expected)
assertAlmostEquals( (pi_div_3_deg_expected - pi_div_3_deg_calculated) / pi_div_3_deg_expected)
```
--------------------------------
### assertStrMatches(str, pattern)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Asserts that the string 'str' matches the full pattern 'pattern'. If 'start' and 'final' are not provided, the pattern must match the entire string. An optional extra message can be provided for failures.
```APIDOC
## assertStrMatches(str, pattern)
### Description
Asserts that the string 'str' matches the full pattern 'pattern'. If 'start' and 'final' are not provided, the pattern must match the entire string. An optional extra message can be provided for failures.
### Method
assertStrMatches
### Parameters
- **str**: The string to match against.
- **pattern**: The pattern to match.
- **start** (number, optional): The starting position for the pattern match.
- **final** (number, optional): The ending position for the pattern match.
- **extra_msg** (string, optional): An additional message to display on failure.
```
--------------------------------
### Run All LuaUnit Tests (CI Equivalent)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Execute 'doit.py runtests' to perform a full test suite run, including syntax check, unit tests, and functional tests, mimicking the continuous integration process.
```shell
doit.py runtests
```
--------------------------------
### Prepare LuaUnit Release Rock File
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Use 'doit.py buildrock' to create a rock file suitable for luarocks. This includes a git clone with generated documentation and stripped test/CI files.
```shell
doit.py buildrock
```
--------------------------------
### Import LuaUnit Library
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Import the LuaUnit library at the beginning of your test script.
```lua
lu = require('luaunit')
```
--------------------------------
### LuaUnit JUNIT Output Configuration
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Demonstrates how to configure LuaUnit to output test results in the JUNIT XML format. This involves using the `-o junit` option and specifying the output filename with `-n `.
```text
$ 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)
```
--------------------------------
### Package LuaUnit for GitHub Release
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Execute 'doit.py packageit' to create zip and tar.gz archives for GitHub. These archives contain the core LuaUnit code with full documentation, excluding development/CI files.
```shell
doit.py packageit
```
--------------------------------
### Assert String Matches Pattern
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Use assertStrMatches to check if a string fully matches a given Lua pattern. Optionally specify start and final positions for partial matches.
```lua
lu.assertStrMatches('hello world', 'hello%s+world')
lu.assertStrMatches('hello world', 'world', 7, 11)
```
--------------------------------
### Run Unit Tests
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Execute all unit tests for LuaUnit. Ensure all proposed changes pass these tests.
```shell
lua run_unit_tests.lua
................................................................................
...............................
Ran 111 tests in 0.120 seconds
OK
```
--------------------------------
### Run Test Suite with Pattern Matching
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Executes tests that match a specified pattern from the command-line arguments. Useful for selecting a subset of tests.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
-- execute tests matching the 'withXY' pattern
os.exit(runner.runSuite('--pattern', 'withXY'))
```
--------------------------------
### Run Test Suite with Default Arguments
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Executes 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())
```
--------------------------------
### Instantiate LuaUnit runner object
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Shows how to create a LuaUnit runner object programmatically using `LuaUnit.new()`. This runner object can then be used to control test execution.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
-- use the runner object...
runner.runSuite()
```
--------------------------------
### Running Lua Unit Tests from Command Line
Source: https://github.com/bluebird75/luaunit/blob/main/README.rst
This shell command demonstrates how to execute Lua unit tests using the Lua interpreter. It is typically used after writing test files to run the test suite and view the results.
```sh
$ lua test_some_lists_comparison.lua
```
--------------------------------
### Run LuaUnit Syntax Check
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Execute the 'luacheck' command using the doit.py utility to perform a syntax check on the LuaUnit code.
```shell
doit.py luacheck
```
--------------------------------
### Running Specific Tests
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Execute specific test tables or functions by listing them on the command line. Use the -v flag for verbose output.
```bash
-- Run all TestAdd table tests and one test of TestDiv table.
$ lua doc/my_test_suite.lua TestAdd TestDiv.testDivError -v
Started on 02/19/17 22:15:53
TestAdd.testAddError ... Ok
TestAdd.testAddPositive ... Ok
TestAdd.testAddZero ... Ok
TestAdd.testAdder ... Ok
TestDiv.testDivError ... Ok
=========================================================
Ran 5 tests in 0.003 seconds, 5 successes, 0 failures
OK
```
--------------------------------
### Combine inclusion and exclusion patterns
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Demonstrates combining --pattern and --exclude options to precisely select tests. Inclusion patterns add tests, while exclusion patterns remove them from the selected list.
```bash
-- Add all tests which include the word Add
-- except the test Adder
-- and also include the Zero tests
$ lua my_test_suite.lua -v --pattern Add --exclude Adder --pattern Zero
```
--------------------------------
### LuaUnit Test with Module-Level Assertions
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Illustrates the recommended practice of using LuaUnit assertions as module-level functions by requiring the 'luaunit' module and prefixing assertion calls with 'lu.'.
```lua
require('luaunit')
TestToto = {} --class
function TestToto:test1_withFailure()
local a = 1
assertEquals( a , 1 )
-- will fail
assertEquals( a , 2 )
end
[...]
```
--------------------------------
### LuaUnit Text Output - Minimal Verbosity
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Demonstrates the default minimal text output format of LuaUnit, showing successful tests, failures (F), and errors (E). Includes a summary of failed tests and a final test execution count.
```text
$ 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
```
--------------------------------
### Lua Unit Test with List Comparison
Source: https://github.com/bluebird75/luaunit/blob/main/doc/0_readme.md
This Lua code demonstrates a unit test case using LuaUnit to compare two lists. It highlights the detailed difference analysis provided by LuaUnit when lists do not match.
```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
```
--------------------------------
### Run Tests via Static Method with Pattern
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
A static method to run tests, creating an internal runner and passing arguments. It supports pattern matching for test selection.
```lua
-- execute tests matching the 'withXY' pattern
os.exit(lu.LuaUnit.run('--pattern', 'withXY'))
```
--------------------------------
### Including Tests by Pattern
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Use the --pattern or -p option with Lua patterns to run only tests that match the specified patterns. Multiple patterns can be provided.
```bash
-- Run all tests of zero testing and error testing
-- by using the magic character .
$ lua my_test_suite.lua -v -p Err.r -p Z.ro
Started on 02/19/17 22:15:53
TestAdd.testAddError ... Ok
TestAdd.testAddZero ... Ok
TestDiv.testDivError ... Ok
TestDiv.testDivZero ... Ok
=========================================================
Ran 4 tests in 0.003 seconds, 4 successes, 0 failures, 3 non-selected
OK
```
--------------------------------
### Run Functional Tests
Source: https://github.com/bluebird75/luaunit/blob/main/doc/5_developing.md
Execute functional tests to validate LuaUnit's output consistency across different environments and formats. Requires 'diff' and optionally 'xmllint'.
```shell
lua run_functional_tests.lua
...............
Ran 15 tests in 9.676 seconds
OK
```
--------------------------------
### Run Test Suite by Explicit Instances
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Runs tests provided as explicit instances (functions or tables of functions) along with their names, bypassing global collection. Command-line arguments can still be parsed if not supplied.
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
os.exit(runner.runSuiteByInstances( {'mySpecialTest1', mySpecialTest1}, {'mySpecialTest2', mySpecialTest2} } )
```
--------------------------------
### LuaUnit Test with Module-Level Assertions (Recommended)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Shows the modern approach to using LuaUnit where assertions are accessed via the 'lu' module alias after requiring 'luaunit'.
```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
[...]
```
--------------------------------
### List Comparison with Swapped Elements and Size Discrepancy
Source: https://github.com/bluebird75/luaunit/blob/main/test/ref/some_lists_comparisons.txt
This test case is similar to the previous one but with the roles of 'expected' and 'actual' lists potentially reversed in the description. It demonstrates the comparison logic for swapped elements and differing list sizes.
```lua
-- list sizes differ: list A (actual) has 17 items, list B (expected) has 20 items
-- lists A and B start differing at index 5
-- lists A and B are equal again from index 7 for A, 10 for B
-- Common parts:
-- = A[1], B[1]: 1
-- = A[2], B[2]: 2
-- = A[3], B[3]: 3
-- = A[4], B[4]: 4
-- Differing parts:
-- - A[5]: 6
-- + B[5]: 5
-- - A[6]: 5
-- + B[6]: 6
-- Present only in one list:
-- + B[7]: 7
-- + B[8]: 8
-- + B[9]: 9
-- Common parts at the end of the lists
-- = A[7], B[10]: 10
-- = A[8], B[11]: 11
-- = A[9], B[12]: 12
-- = A[10], B[13]: 13
-- = A[11], B[14]: 14
-- = A[12], B[15]: 15
-- = A[13], B[16]: 16
-- = A[14], B[17]: 17
-- = A[15], B[18]: 18
-- = A[16], B[19]: 19
-- = A[17], B[20]: 20
```
--------------------------------
### LuaUnit Test with Global Assertions Enabled
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Demonstrates how to enable the older practice of exporting assertion functions to the global namespace by setting `EXPORT_ASSERT_TO_GLOBALS` 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 )
-- will fail
assertEquals( a , 2 )
end
[...]
```
--------------------------------
### Run LuaUnit Tests
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Execute your test script with LuaUnit. This line should be at the end of your test file to run all collected tests and exit with the appropriate status code.
```lua
os.exit( lu.LuaUnit.run() )
```
--------------------------------
### Compare Nested Tables with assertEquals
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Demonstrates how assertEquals handles differences in nested tables by analyzing list content and pinpointing the exact location of the discrepancy. This is useful for debugging complex data structures.
```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
```
--------------------------------
### List Comparison with Size Difference and Swapped Elements
Source: https://github.com/bluebird75/luaunit/blob/main/test/ref/some_lists_comparisons.txt
This test case highlights a scenario where lists have different sizes and elements are swapped in the differing section. It shows how the comparison identifies differing parts and common sections at the end.
```lua
-- list sizes differ: list A (expected) has 17 items, list B (actual) has 20 items
-- lists A and B start differing at index 5
-- lists A and B are equal again from index 7 for A, 10 for B
-- Common parts:
-- = A[1], B[1]: 1
-- = A[2], B[2]: 2
-- = A[3], B[3]: 3
-- = A[4], B[4]: 4
-- Differing parts:
-- - A[5]: 6
-- + B[5]: 5
-- - A[6]: 5
-- + B[6]: 6
-- Present only in one list:
-- + B[7]: 7
-- + B[8]: 8
-- + B[9]: 9
-- Common parts at the end of the lists
-- = A[7], B[10]: 10
-- = A[8], B[11]: 11
-- = A[9], B[12]: 12
-- = A[10], B[13]: 13
-- = A[11], B[14]: 14
-- = A[12], B[15]: 15
-- = A[13], B[16]: 16
-- = A[14], B[17]: 17
-- = A[15], B[18]: 18
-- = A[16], B[19]: 19
-- = A[17], B[20]: 20
```
--------------------------------
### Tests for Add Function
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
A collection of tests for an 'add' function, demonstrating assertions for positive numbers, zero, and error conditions. Includes a test for a higher-order function 'adder'.
```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
```
--------------------------------
### Pretty Printing Tables with LuaUnit
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Demonstrates the usage of the `prettystr` function to convert various Lua values, including nested tables and functions, into a human-readable string format.
```default
> 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}
```
--------------------------------
### Lua Unit Test for List Comparison
Source: https://github.com/bluebird75/luaunit/blob/main/README.rst
This Lua code demonstrates a unit test case using LuaUnit to compare two lists. It highlights the assertEquals assertion for lists and is intended to showcase the detailed difference analysis provided by LuaUnit when lists do not match.
```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
```
--------------------------------
### Compare Tables with Different Table Keys
Source: https://github.com/bluebird75/luaunit/blob/main/doc/6_annexes.md
LuaUnit treats tables used as keys as distinct entities even if their content is identical. Asserting equality between tables with different table references as keys will fail.
```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
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
A static method that creates an internal runner and executes the test suite, passing all arguments to the underlying runSuite method.
```APIDOC
## *static* run()
### Description
This function may be called directly from the LuaUnit table. It creates an internal LuaUnit runner and passes all arguments to it. Arguments and return value are the same as [`LuaUnit.runSuite()`](#LuaUnit.runSuite).
### Example:
```lua
-- execute tests matching the 'withXY' pattern
os.exit(lu.LuaUnit.run('--pattern', 'withXY'))
```
```
--------------------------------
### Test Positive Addition
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Verifies the add function correctly sums two positive numbers.
```lua
function testAddPositive()
lu.assertEquals(add(1,1),2)
end
```
--------------------------------
### LuaUnit Text Output - Verbose Mode
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Illustrates the verbose text output format of LuaUnit, which provides detailed information for each test, including its status (Ok, FAIL, ERROR), and a full summary of failures and errors.
```text
$ 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
```
--------------------------------
### runSuiteByInstances
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Runs specific test instances without performing a global collection process. Tests are provided as explicit arguments along with their names.
```APIDOC
## runSuiteByInstances(listOfNameAndInstances)
### Description
This function runs tests without performing the global test collection process on the global namespace. The tests are explicitly provided as arguments, along with their names. Arguments are handled the same way as in `runner:runSuite()`; if no arguments are supplied, the function will parse the script command-line.
### Input
Input is provided as a list of `{ name, test_instance }` where `test_instance` can either be a function or a table containing test functions starting with the prefix `test`.
### Example of using runSuiteByInstances
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
os.exit(runner.runSuiteByInstances( {'mySpecialTest1', mySpecialTest1}, {'mySpecialTest2', mySpecialTest2} } )
```
```
--------------------------------
### Test Adder Function and Closure Behavior
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Tests that the adder function returns a function and that this returned function behaves as expected.
```lua
function testAdder()
f = adder(3)
lu.assertIsFunction( f )
lu.assertEquals( f(2), 5 )
end
```
--------------------------------
### Assert Value is Nil
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Use assertNil to verify that a given value is nil.
```lua
lu.assertNil(nil)
lu.assertNil(0)
lu.assertNil('')
```
--------------------------------
### Add Function for Testing
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
This is the function to be tested, which adds two numbers with specific conditions for positive, zero, and negative inputs.
```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
```
--------------------------------
### runSuite
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Executes the test suite. It can parse command-line arguments or accept explicit test names or patterns to control which tests are run.
```APIDOC
## runSuite()
### Description
This function runs the test suite. If no arguments are supplied, it parses the script's command-line arguments. If arguments are supplied, they are parsed as command-line arguments, allowing for specific test selection by name or pattern.
### Return value
Returns the number of failures and errors. 0 is returned on success, suitable for an exit code.
### Example of using pattern to select tests:
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
-- execute tests matching the 'withXY' pattern
os.exit(runner.runSuite('--pattern', 'withXY'))
```
### Example of explicitly selecting tests:
```lua
lu = require('luaunit')
runner = lu.LuaUnit.new()
os.exit(runner.runSuite('testABC', 'testDEF'))
```
```
--------------------------------
### assertMinusZero(value)
Source: https://github.com/bluebird75/luaunit/blob/main/doc/4_reference_doc.md
Asserts that a given number is negative zero (-0) according to IEEE-754. An optional extra message can be provided for failure cases.
```APIDOC
## assertMinusZero(value)
### Description
Asserts that a given number is -0, according to the definition of [IEEE-754](https://en.wikipedia.org/wiki/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]().
### Method
assertMinusZero
### Parameters
#### Path Parameters
- **value** (number) - Required - The number to check for negative zero.
#### Query Parameters
- **extra_msg** (string) - Optional - An additional message to display on failure.
```
--------------------------------
### Handle Table Reference Loops in Printing
Source: https://github.com/bluebird75/luaunit/blob/main/doc/6_annexes.md
LuaUnit automatically handles tables with reference loops by displaying the full content once and only the table ID for subsequent references within the loop. This prevents infinite recursion.
```lua
local t1 = {}
local t2 = {}
t1.t2 = t2
t1.a = {1,2,3}
t2.t1 = t1
-- when displaying table t1:
-- table t1 inside t2 is only displayed by its id because t1 is already being displayed
-- table t2 is displayed along with its id because it is part of a loop.
-- t1: " { a={1,2,3}, t2= {t1=} }"
```
--------------------------------
### Test Addition with Zero
Source: https://github.com/bluebird75/luaunit/blob/main/doc/3_getting-started.md
Ensures the add function returns 0 when one or both arguments are zero.
```lua
function testAddZero()
lu.assertEquals(add(1,0),0)
lu.assertEquals(add(0,5),0)
lu.assertEquals(add(0,0),0)
end
```
--------------------------------
### List Comparison with Different Data Types
Source: https://github.com/bluebird75/luaunit/blob/main/test/ref/some_lists_comparisons.txt
This test case compares two lists that differ in a boolean value at a specific index. It demonstrates the comparison's ability to detect differences in various data types, including booleans, functions, threads, and strings.
```lua
-- lists A (actual) and B (expected) have the same size
-- lists A and B start differing at index 7
-- lists A and B are equal again from index 8
-- Common parts:
-- = A[1], B[1]: "aaa"
-- = A[2], B[2]: "bbb"
-- = A[3], B[3]: "ccc"
-- = A[4], B[4]: function: 00E70160
-- = A[5], B[5]: 1.1
-- = A[6], B[6]: 2.1
-- Differing parts:
-- - A[7]: false
-- + B[7]: true
-- Common parts at the end of the lists
-- = A[8], B[8]: false
-- = A[9], B[9]: thread: 00E35480
-- = A[10], B[10]: thread: 00E35480
-- = A[11], B[11]: thread: 00E35480
```