2.2.5 One body with multiple tests using assertions
PlUnit is designed to cooperate with the assertion/1 test provided by library(debug).3This integration was suggested by Günter Kniesel. If an assertion fails in the context of a test, the test framework reports this and considers the test failed, but does not trap the debugger. Using assertion/1 in the test-body is attractive for two scenarios:
- Confirm that multiple claims hold. Where multiple claims about variable bindings can be tested using the == option in the test header, arbitrary boolean tests, notably about the state of the database, are harder to combine. Simply adding them in the body of the test has two disadvantages: it is less obvious to distinguish the tested code from the test and if one of the tests fails there is no easy way to find out which one.
- Testing‘scenarios’or sequences of actions. If one step in such a sequence fails there is again no easy way to find out which one. By inserting assertions into the sequence this becomes obvious.
Below is a simple example, showing two failing assertions. The first line of the failure message gives the test. The second reports the location of the assertion.4If known. The location is determined by analysing the stack. The second failure shows a case where this does not work because last-call optimization has already removed the context of the test-body. If the assertion call originates from a different file this is reported appropriately. The last line gives the actually failed goal.
:- begin_tests(test). test(a) :- A is 2^3, assertion(float(A)), assertion(A == 9). :- end_tests(test).
?- run_tests. % PL-Unit: test ERROR: /home/jan/src/pl-devel/linux/t.pl:5: test a: assertion at line 7 failed Assertion: float(8) ERROR: /home/jan/src/pl-devel/linux/t.pl:5: test a: assertion failed Assertion: 8==9 . done % 2 assertions failed