{assert}

A condition a test run holds the page to; silent everywhere else.

Debugging and errors Single tags

Syntax

{assert condition}
{assert condition, 'message'}

Parameters

condition
An expression, as in {if}: $total eq 42. Read raw and evaluated only when asserts are on.
message
Optional. An expression - usually a quoted text - added to the report: assert failed: $total eq 42 - the cart total.

Description

{assert $total eq 42, 'the cart total'} states something that must be true at that point of the page. It always renders nothing. What it does depends on $padAssert: off - the default, and so in production - the tag is skipped entirely, the condition is not even evaluated, so an assert on a field that is not there costs nothing and raises nothing. On, a condition that holds passes quietly and a false one is a PAD error: assert failed: $total eq 42 - the cart total.

pad test <app> switches $padAssert on for its run. An application's tests live in _tests/: cart.pad (with cart.php for its data) is the test page and cart.txt its expected answer; a failing assert fails the test, with the condition, the message and the template position as its report. So the checks can stand in the real pages and templates, and the tests exercise them.

The parameters are read as written, not evaluated in advance - the condition is an expression with its own operators, evaluated only after the switch has been asked. With asserts on, an {assert} without a condition is an error of its own. To raise an error unconditionally, use {error}.

Examples

Silent in a page

With $padAssert off, as here, the asserts render nothing - not even the one on a field that does not exist.

Templateexamples/assert/1-silent.pad
{set $total = 42}
<p>Before the asserts.</p>
{assert $total eq 42, 'the cart total'}
{assert $missing gt 0, 'never evaluated'}
<p>After the asserts - nothing between the two paragraphs.</p>
Resultopen alone

Before the asserts.

After the asserts - nothing between the two paragraphs.

In an application test

apps/shop/_tests/cart.pad - pad test shop turns asserts on, and a false one fails the test.

Templateexamples/assert/2-a-test.src
{set $total = 0}
{cart}
  {assert $price gt 0, 'every line has a price'}
  {set $total = $total + $price * $qty}
{/cart}
{assert $total eq 42, 'the cart total'}
<p>{$total}</p>

See also

  • {if} Renders its content only when a condition holds, with elseif and else branches.
  • {error} Raises a PAD error from the template, handled as the configured error action says.