Assertions: Difference between revisions

(add BQN)
Line 898:
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
The assertion filters defined here are designed so that assertions
intended for development or testing could be left in-place, possibly
even in production code.
 
'''Highlights'''
 
* The input to every assertion filter is always passed through without alteration.
* If assertion checking is turned on, then an assertion violation
simply results in an error message being emitted on STDERR ("standard error").
* Assertions are only checked if the environment variable JQ_ASSERT
is set (see below for how to turn assertion checking on or off).
* Pinpointing the occurrence of an assertion violation by using $__loc__ is supported,
provided your implementation of jq includes this function.
 
The assertion checking filters defined here are as follows:
* assert(x)
* assert(x; msg)
* asserteq(x; y; msg)
<br>
where:
* msg determines the message that is printed as part of an assertion violation warning; it would typically be specified as a string or the $__loc__ object if your jq supports it.
 
'''JQ_ASSERT'''
 
Here is a table indicating how the JQ_ASSERT environment variable can be set or unset in various contexts:
<pre>
SHELL SET UNSET
sh bash (etc) export JQ_ASSERT=1 unset JQ_ASSERT
fish set -x JQ_ASSERT 1 set -u JQ_ASSERT
csh, tcsh setenv JQ_ASSERT 1 unsetenv JQ_ASSERT
 
Windows/DOS SET JQ_ASSERT=1 set JQ_ASSERT=
Windows: Start > Control Panel > System > Advanced > Environment Variables
</pre>
 
See also the example below for how to set it on a per-invocation basis.
 
<lang jq>def assert(exp; $msg):
def m: $msg | if type == "string" then . else [.[]] | join(":") end;
if env.JQ_ASSERT then
(exp as $e | if $e then . else . as $in | "assertion violation @ \(m) => \($e)" | debug | $in end)
else . end;
 
def assert(exp):
if env.JQ_ASSERT then
(exp as $e | if $e then . else . as $in | "assertion violation: \($e)" | debug | $in end)
else . end;
 
def asserteq(x;y;$msg):
def m: $msg | if type == "string" then . else [.[]] | join(":") end;
def s: (if $msg then m + ": " else "" end) + "\(x) != \(y)";
if env.JQ_ASSERT then
if x == y then .
else . as $in | "assertion violation @ \(s)" | debug | $in
end
else . end;
</lang>
'''Example'''
<lang jq>
# File: example.jq
# This example assumes the availability of the $__loc__ function
# and that assert.jq is in the same directory as example.jq.
 
include "assert" {search: "."};
 
def test:
"This is an input"
| 0 as $x
| assert($x == 42; $__loc__),
asserteq($x; 42; $__loc__);
 
test</lang>
'''Invocation'''
JQ_ASSERT=1 jq -n -f example.jq
 
In the output, the DEBUG line above appears on stderr.
{{out}}
<pre>
["DEBUG:","assertion violation @ <top-level>:16 => false"]
"This is an input"
["DEBUG:","assertion violation @ <top-level>:17: 0 != 42"]
"This is an input"
</pre>
=={{header|Julia}}==
<lang julia>const x = 5
2,478

edits