Skip to content

Commit

Permalink
statements: Add assert
Browse files Browse the repository at this point in the history
Closes #199
  • Loading branch information
awelzel committed Oct 13, 2023
1 parent 0f47bf1 commit 3b8ca1d
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
18 changes: 18 additions & 0 deletions script-reference/assert_1.zeek
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
event test_1() {
assert 3 == 3;
local x = 37;
assert x > 40;
print "not reached";
}

event test_2() {
assert 2 == 2;
local x = 37;
assert x > 40, fmt("%s is not greater than 40", x);
print "not reached";
}

event zeek_init() {
schedule 0.01sec { test_1() };
schedule 0.02sec { test_2() };
}
52 changes: 52 additions & 0 deletions script-reference/statements.rst
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,9 @@ Here are the statements that the Zeek scripting language supports.
* - :zeek:keyword:`add`, :zeek:keyword:`delete`
- Add or delete elements

* - :zeek:keyword:`assert`
- Runtime assertion

* - :zeek:keyword:`print`
- Print to stdout or a file

Expand Down Expand Up @@ -533,6 +536,55 @@ Example:
add myset["test"];
.. zeek:keyword:: assert
assert
~~~~~~

.. versionadded:: 6.1

The ``assert`` statement can be used for runtime assertion checks or as a building
block for a testing framework. It takes an expression ``expr`` of type
:zeek:see:`bool` and an optional message of type :zeek:see:`string`.
If ``expr`` at runtime evaluates to ``F``, the string representation
of the expression and the given message, if any, are logged
via :zeek:see:`Reporter::error` by default.

Script execution for a given event handler stops with a failing ``assert`` statement
comparable to a scripting runtime error after generating the log.

Example:

.. literalinclude:: assert_1.zeek
:language: zeek
:linenos:
:tab-width: 4

This script prints the following messages to stderr, as well as logging them to
``reporter.log``.

.. code-block:: console
$ zeek assert_1.zeek
error in ./assert_1.zeek, line 6: assertion failure: 40 < x
error in ./assert_1.zeek, line 12: assertion failure: 40 < x (37 is not greater than 40)
.. note::

Zeek's exit code in this example will be ``0``, indicating success.
Script errors other than those in a ``zeek_init()`` handler are not
reflected in Zeek's exit code.


The logging behavior of failing assert statements can be customized using the
:zeek:see:`assertion_failure` or zeek:see:`assertion_result` hook.
Using the :zeek:see:`break` statement in either hook allows for suppression
of the the default log generation.
The :zeek:see:`assertion_result` hook is targeted for testing frameworks as it
is likely prohibitively expensive for use in a live production environment due
to being invoked for every ``assert`` statement execution.


.. zeek:keyword:: break
break
Expand Down

0 comments on commit 3b8ca1d

Please sign in to comment.