Assertions: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 13: | Line 13: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=11l>V a = 5 |
||
assert(a == 42) |
assert(a == 42) |
||
assert(a == 42, ‘Error message’)</ |
assert(a == 42, ‘Error message’)</syntaxhighlight> |
||
=={{header|68000 Assembly}}== |
=={{header|68000 Assembly}}== |
||
< |
<syntaxhighlight lang=68000devpac>CMP.L #42,D0 |
||
BEQ continue |
BEQ continue |
||
ILLEGAL ;causes an immediate jump to the illegal instruction vector. |
ILLEGAL ;causes an immediate jump to the illegal instruction vector. |
||
continue: |
continue: |
||
; rest of program</ |
; rest of program</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Using pragma Assert: |
Using pragma Assert: |
||
< |
<syntaxhighlight lang=ada>pragma Assert (A = 42, "Oops!");</syntaxhighlight> |
||
The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions: |
The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions: |
||
< |
<syntaxhighlight lang=ada>with Ada.Assertions; use Ada.Assertions; |
||
... |
... |
||
Assert (A = 42, "Oops!");</ |
Assert (A = 42, "Oops!");</syntaxhighlight> |
||
The procedure Assert propagates Assertion_Error when condition is false. |
The procedure Assert propagates Assertion_Error when condition is false. |
||
Since Ada 2012 one may also specify preconditions and post-conditions for a subprogram. |
Since Ada 2012 one may also specify preconditions and post-conditions for a subprogram. |
||
< |
<syntaxhighlight lang=ada>procedure Find_First |
||
(List : in Array_Type; |
(List : in Array_Type; |
||
Value : in Integer; |
Value : in Integer; |
||
Line 42: | Line 42: | ||
Post => |
Post => |
||
(if Found then Position in List'Range and then List (Position) = Value |
(if Found then Position in List'Range and then List (Position) = Value |
||
else Position = List'Last);</ |
else Position = List'Last);</syntaxhighlight> |
||
The precondition identified with "Pre =>" is an assertion that the length of the parameter List must be greater than zero. The post-condition identified with "Post =>" asserts that, upon completion of the procedure, if Found is true then Position is a valid index value in List and the value at the array element List(Position) equals the value of the Value parameter. If Found is False then Position is set to the highest valid index value for List. |
The precondition identified with "Pre =>" is an assertion that the length of the parameter List must be greater than zero. The post-condition identified with "Post =>" asserts that, upon completion of the procedure, if Found is true then Position is a valid index value in List and the value at the array element List(Position) equals the value of the Value parameter. If Found is False then Position is set to the highest valid index value for List. |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang=aime>integer x; |
||
x = 41; |
x = 41; |
||
if (x != 42) { |
if (x != 42) { |
||
error("x is not 42"); |
error("x is not 42"); |
||
}</ |
}</syntaxhighlight> |
||
Executing the program will produce on standard error: |
Executing the program will produce on standard error: |
||
<pre>aime: assert: 5: x is not 42</pre> |
<pre>aime: assert: 5: x is not 42</pre> |
||
Line 70: | Line 70: | ||
In [[ELLA ALGOL 68]] the ASSERT is implemented as an operator in the ''environment'' prelude: |
In [[ELLA ALGOL 68]] the ASSERT is implemented as an operator in the ''environment'' prelude: |
||
< |
<syntaxhighlight lang=algol68>OP ASSERT = (VECTOR [] CHAR assertion,BOOL valid) VOID: |
||
IF NOT valid |
IF NOT valid |
||
THEN type line on terminal(assertion); |
THEN type line on terminal(assertion); |
||
terminal error( 661 {invalid assertion } ) |
terminal error( 661 {invalid assertion } ) |
||
FI;</ |
FI;</syntaxhighlight> |
||
And can be "USEd" as follows: |
And can be "USEd" as follows: |
||
< |
<syntaxhighlight lang=algol68>PROGRAM assertions CONTEXT VOID |
||
USE standard,environment |
USE standard,environment |
||
BEGIN |
BEGIN |
||
Line 82: | Line 82: | ||
"Oops!" ASSERT ( a = 42 ) |
"Oops!" ASSERT ( a = 42 ) |
||
END |
END |
||
FINISH</ |
FINISH</syntaxhighlight> |
||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
Assertions were added to the 1972 version of Algol W. If the tested condition is false, the program terminates. In the following, the write does not get executed. |
Assertions were added to the 1972 version of Algol W. If the tested condition is false, the program terminates. In the following, the write does not get executed. |
||
< |
<syntaxhighlight lang=algolw>begin |
||
integer a; |
integer a; |
||
a := 43; |
a := 43; |
||
assert a = 42; |
assert a = 42; |
||
write( "this won't appear" ) |
write( "this won't appear" ) |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Apex}}== |
=={{header|Apex}}== |
||
Asserts that the specified condition is true. If it is not, a fatal error is returned that causes code execution to halt. |
Asserts that the specified condition is true. If it is not, a fatal error is returned that causes code execution to halt. |
||
< |
<syntaxhighlight lang=apex> |
||
String myStr = 'test; |
String myStr = 'test; |
||
System.assert(myStr == 'something else', 'Assertion Failed Message'); |
System.assert(myStr == 'something else', 'Assertion Failed Message'); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Asserts that the first two arguments are the same. If they are not, a fatal error is returned that causes code execution to halt. |
Asserts that the first two arguments are the same. If they are not, a fatal error is returned that causes code execution to halt. |
||
< |
<syntaxhighlight lang=apex> |
||
Integer i = 5; |
Integer i = 5; |
||
System.assertEquals(6, i, 'Expected 6, received ' + i); |
System.assertEquals(6, i, 'Expected 6, received ' + i); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Asserts that the first two arguments are different. If they are the same, a fatal error is returned that causes code execution to halt. |
Asserts that the first two arguments are different. If they are the same, a fatal error is returned that causes code execution to halt. |
||
< |
<syntaxhighlight lang=apex> |
||
Integer i = 5; |
Integer i = 5; |
||
System.assertNotEquals(5, i, 'Expected different value than ' + i); |
System.assertNotEquals(5, i, 'Expected different value than ' + i); |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.''' |
'''You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.''' |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang=rebol>a: 42 |
||
ensure [a = 42]</ |
ensure [a = 42]</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
=== Exceptions === |
=== Exceptions === |
||
{{works with|AutoHotkey_L}} |
{{works with|AutoHotkey_L}} |
||
< |
<syntaxhighlight lang=AHK>a := 42 |
||
Assert(a > 10) |
Assert(a > 10) |
||
Assert(a < 42) ; throws exception |
Assert(a < 42) ; throws exception |
||
Line 129: | Line 129: | ||
If !bool |
If !bool |
||
throw Exception("Expression false", -1) |
throw Exception("Expression false", -1) |
||
}</ |
}</syntaxhighlight> |
||
=== Legacy versions === |
=== Legacy versions === |
||
< |
<syntaxhighlight lang=AutoHotkey>if (a != 42) |
||
{ |
{ |
||
OutputDebug, "a != 42" ; sends output to a debugger if connected |
OutputDebug, "a != 42" ; sends output to a debugger if connected |
||
ListVars ; lists values of local and global variables |
ListVars ; lists values of local and global variables |
||
Pause ; pauses the script, use ExitApp to exit instead |
Pause ; pauses the script, use ExitApp to exit instead |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 142: | Line 142: | ||
AWK doesn't have a built-in assert statement. It could be simulated using a user-defined assert() function defined as below. The BEGIN section shows some examples of successful and failed "assertions". |
AWK doesn't have a built-in assert statement. It could be simulated using a user-defined assert() function defined as below. The BEGIN section shows some examples of successful and failed "assertions". |
||
< |
<syntaxhighlight lang=awk> |
||
BEGIN { |
BEGIN { |
||
meaning = 6 * 7 |
meaning = 6 * 7 |
||
Line 164: | Line 164: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
The above example produces the output below, and sets the program's exit code to 1 (the default is 0) |
The above example produces the output below, and sets the program's exit code to 1 (the default is 0) |
||
Line 172: | Line 172: | ||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
< |
<syntaxhighlight lang=axe>A=42??Returnʳ</syntaxhighlight> |
||
=={{header|BaCon}}== |
=={{header|BaCon}}== |
||
< |
<syntaxhighlight lang=qbasic>' Assertions |
||
answer = assertion(42) |
answer = assertion(42) |
||
PRINT "The ultimate answer is indeed ", answer |
PRINT "The ultimate answer is indeed ", answer |
||
Line 198: | Line 198: | ||
RETURN i |
RETURN i |
||
END FUNCTION</ |
END FUNCTION</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 222: | Line 222: | ||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
{{works with|BASIC256|2.0.0.11}} |
{{works with|BASIC256|2.0.0.11}} |
||
< |
<syntaxhighlight lang=BASIC256> |
||
subroutine assert (condition, message) |
subroutine assert (condition, message) |
||
if not condition then print "ASSERTION FAIED: ";message: throwerror 1 |
if not condition then print "ASSERTION FAIED: ";message: throwerror 1 |
||
Line 229: | Line 229: | ||
call assert(1+1=2, "but I don't expect this assertion to fail"): rem Does not throw an error |
call assert(1+1=2, "but I don't expect this assertion to fail"): rem Does not throw an error |
||
rem call assert(1+1=3, "and rightly so"): rem Throws an error |
rem call assert(1+1=3, "and rightly so"): rem Throws an error |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang=bbcbasic> PROCassert(a% = 42) |
||
END |
END |
||
DEF PROCassert(bool%) |
DEF PROCassert(bool%) |
||
IF NOT bool% THEN ERROR 100, "Assertion failed" |
IF NOT bool% THEN ERROR 100, "Assertion failed" |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
Line 255: | Line 255: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang=brat>squish import :assert :assertions |
||
assert_equal 42 42 |
assert_equal 42 42 |
||
assert_equal 13 42 #Raises an exception</ |
assert_equal 13 42 #Raises an exception</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang=c>#include <assert.h> |
||
int main(){ |
int main(){ |
||
Line 269: | Line 269: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
To turn off assertions, simply define the <tt>NDEBUG</tt> macro before where <tt><assert.h></tt> is included. |
To turn off assertions, simply define the <tt>NDEBUG</tt> macro before where <tt><assert.h></tt> is included. |
||
There is no mechanism to add a custom "message" with your assertion, like in other languages. However, there is a "trick" to do this, by simply logical-AND-ing your condition with a string constant message, like in the following. Since a string constant is guaranteed to be non-NULL (and hence evaluated as True), and since AND-ing with True is an identity operation for a boolean, it will not alter the behavior of the assertion, but it will get captured in the debug message that is printed: |
There is no mechanism to add a custom "message" with your assertion, like in other languages. However, there is a "trick" to do this, by simply logical-AND-ing your condition with a string constant message, like in the following. Since a string constant is guaranteed to be non-NULL (and hence evaluated as True), and since AND-ing with True is an identity operation for a boolean, it will not alter the behavior of the assertion, but it will get captured in the debug message that is printed: |
||
< |
<syntaxhighlight lang=c>assert(a == 42 && "Error message");</syntaxhighlight> |
||
This trick only works with messages written directly in the source code (i.e. cannot be a variable or be computed), however, since the assertion message is captured by the macro at compile-time. |
This trick only works with messages written directly in the source code (i.e. cannot be a variable or be computed), however, since the assertion message is captured by the macro at compile-time. |
||
Line 289: | Line 289: | ||
Calls to methods of the Debug class are only compiled when the DEBUG compiler constant is defined, and so are intended for asserting invariants in internal code that could only be broken because of logic errors. Calls to methods of the Trace class similarly require the TRACE constant, which, however, is defined by default for both debug and release builds in Visual Studio projects—trace assertions can thus be used for various logging purposes in production code. |
Calls to methods of the Debug class are only compiled when the DEBUG compiler constant is defined, and so are intended for asserting invariants in internal code that could only be broken because of logic errors. Calls to methods of the Trace class similarly require the TRACE constant, which, however, is defined by default for both debug and release builds in Visual Studio projects—trace assertions can thus be used for various logging purposes in production code. |
||
< |
<syntaxhighlight lang=csharp>using System.Diagnostics; // Debug and Trace are in this namespace. |
||
static class Program |
static class Program |
||
Line 309: | Line 309: | ||
Console.WriteLine("After Debug.Assert"); |
Console.WriteLine("After Debug.Assert"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang=vbnet>Imports System.Diagnostics |
||
' Note: VB Visual Studio projects have System.Diagnostics imported by default, |
' Note: VB Visual Studio projects have System.Diagnostics imported by default, |
||
' along with several other namespaces. |
' along with several other namespaces. |
||
Line 331: | Line 331: | ||
Console.WriteLine("After Debug.Assert") |
Console.WriteLine("After Debug.Assert") |
||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{out|note=for .NET Core debug builds when outside of a debugger}} |
{{out|note=for .NET Core debug builds when outside of a debugger}} |
||
Line 357: | Line 357: | ||
Subscribing an instance involves adding the following line to the beginning of Main() (with a semicolon in C#, of course ;) |
Subscribing an instance involves adding the following line to the beginning of Main() (with a semicolon in C#, of course ;) |
||
< |
<syntaxhighlight lang=vbnet>Trace.Listeners.Add(new ConsoleTraceListener())</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang=cpp>#include <cassert> // assert.h also works |
||
int main() |
int main() |
||
Line 370: | Line 370: | ||
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined |
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined |
||
// when including <cassert>, in which case it has no effect |
// when including <cassert>, in which case it has no effect |
||
}</ |
}</syntaxhighlight> |
||
Note that assert does ''not'' get a <code>std::</code> prefix because it's a macro. |
Note that assert does ''not'' get a <code>std::</code> prefix because it's a macro. |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang=Clojure> |
||
(let [i 42] |
(let [i 42] |
||
(assert (= i 42))) |
(assert (= i 42))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang=lisp>(let ((x 42)) |
||
(assert (and (integerp x) (= 42 x)) (x)))</ |
(assert (and (integerp x) (= 42 x)) (x)))</syntaxhighlight> |
||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
Works with BlackBox Component Builder |
Works with BlackBox Component Builder |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE Assertions; |
MODULE Assertions; |
||
VAR |
VAR |
||
Line 397: | Line 397: | ||
Assertions.DoIt |
Assertions.DoIt |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 422: | Line 422: | ||
Crystal doesn't have an assert statement. the <code>spec</code> module provides a testing DSL, but a simple assert can be created with a function or macro. |
Crystal doesn't have an assert statement. the <code>spec</code> module provides a testing DSL, but a simple assert can be created with a function or macro. |
||
< |
<syntaxhighlight lang=ruby>class AssertionError < Exception |
||
end |
end |
||
Line 429: | Line 429: | ||
end |
end |
||
assert(12 == 42, "It appears that 12 doesn't equal 42")</ |
assert(12 == 42, "It appears that 12 doesn't equal 42")</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang=d>import std.exception: enforce; |
||
int foo(in bool condition) pure nothrow |
int foo(in bool condition) pure nothrow |
||
Line 467: | Line 467: | ||
// There are some different versions of this lazy function. |
// There are some different versions of this lazy function. |
||
enforce(x == 42, "x is not 42"); |
enforce(x == 42, "x is not 42"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
=== Assert === |
=== Assert === |
||
< |
<syntaxhighlight lang=javascript> |
||
main() { |
main() { |
||
var i = 42; |
var i = 42; |
||
assert( i == 42 ); |
assert( i == 42 ); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== Expect === |
=== Expect === |
||
Testing assertions can be done using the test and expect functions in the test package |
Testing assertions can be done using the test and expect functions in the test package |
||
< |
<syntaxhighlight lang=d>import 'package:test/test.dart'; |
||
main() { |
main() { |
||
Line 493: | Line 493: | ||
expect( j, equals(42) ); |
expect( j, equals(42) ); |
||
}); |
}); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang=Delphi>Assert(a = 42);</syntaxhighlight> |
||
If an assertion fails, EAssertionFailed exception is raised. |
If an assertion fails, EAssertionFailed exception is raised. |
||
Line 503: | Line 503: | ||
The generation of assertion code can be disabled by compiler directive |
The generation of assertion code can be disabled by compiler directive |
||
<lang |
<syntaxhighlight lang=Delphi>{$ASSERTIONS OFF}</syntaxhighlight> |
||
Here is a simple console demo app which raises and handles assertion exception: |
Here is a simple console demo app which raises and handles assertion exception: |
||
< |
<syntaxhighlight lang=Delphi>program TestAssert; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 527: | Line 527: | ||
end; |
end; |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
Simple assertion, with a custom (optional) message |
Simple assertion, with a custom (optional) message |
||
< |
<syntaxhighlight lang=Delphi>Assert(a = 42, 'Not 42!');</syntaxhighlight> |
||
Other specialized assertions can be used in contracts, for instance this function check that the parameter (passed by reference ofr the purpose of illustration) is 42 when entering the function and when leaving the function |
Other specialized assertions can be used in contracts, for instance this function check that the parameter (passed by reference ofr the purpose of illustration) is 42 when entering the function and when leaving the function |
||
< |
<syntaxhighlight lang=Delphi>procedure UniversalAnswer(var a : Integer); |
||
require |
require |
||
a = 42; |
a = 42; |
||
Line 540: | Line 540: | ||
ensure |
ensure |
||
a = 42; |
a = 42; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
Dyalect has a built-in "assert" function: |
Dyalect has a built-in "assert" function: |
||
< |
<syntaxhighlight lang=dyalect>var x = 42 |
||
assert(42, x)</ |
assert(42, x)</syntaxhighlight> |
||
This function throws an exception if assertion fails. |
This function throws an exception if assertion fails. |
||
Line 554: | Line 554: | ||
E does not have the specific feature of assertions which may be disabled by a global option. But it does have a utility to throw an exception if a condition is false: |
E does not have the specific feature of assertions which may be disabled by a global option. But it does have a utility to throw an exception if a condition is false: |
||
< |
<syntaxhighlight lang=e>require(a == 42) # default message, "Required condition failed" |
||
require(a == 42, "The Answer is Wrong.") # supplied message |
require(a == 42, "The Answer is Wrong.") # supplied message |
||
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure</ |
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang=lisp> |
||
(assert (integer? 42)) → #t ;; success returns true |
(assert (integer? 42)) → #t ;; success returns true |
||
Line 571: | Line 571: | ||
(assert (integer? 'quarante-deux) "☝️ expression must evaluate to the integer 42") |
(assert (integer? 'quarante-deux) "☝️ expression must evaluate to the integer 42") |
||
💥 error: ☝️ expression must evaluate to the integer 42 : assertion failed : (#integer? 'quarante-deux) |
💥 error: ☝️ expression must evaluate to the integer 42 : assertion failed : (#integer? 'quarante-deux) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
<lang> |
<lang> |
||
ASSERT(a = 42,'A is not 42!',FAIL);</ |
ASSERT(a = 42,'A is not 42!',FAIL);</syntaxhighlight> |
||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
Line 584: | Line 584: | ||
File called main.e: |
File called main.e: |
||
< |
<syntaxhighlight lang=eiffel>class MAIN |
||
creation main |
creation main |
||
feature main is |
feature main is |
||
Line 595: | Line 595: | ||
test.assert(io.last_integer); |
test.assert(io.last_integer); |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Another file called test.e: |
Another file called test.e: |
||
< |
<syntaxhighlight lang=eiffel>class TEST |
||
feature assert(val: INTEGER) is |
feature assert(val: INTEGER) is |
||
require |
require |
||
Line 604: | Line 604: | ||
print("Thanks for the 42!%N"); |
print("Thanks for the 42!%N"); |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang=elixir>ExUnit.start |
||
defmodule AssertionTest do |
defmodule AssertionTest do |
||
Line 617: | Line 617: | ||
assert 42 == return_5 |
assert 42 == return_5 |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 639: | Line 639: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang=lisp>(require 'cl-lib) |
||
(let ((x 41)) |
(let ((x 41)) |
||
(cl-assert (= x 42) t "This shouldn't happen"))</ |
(cl-assert (= x 42) t "This shouldn't happen"))</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Erlang doesn't have an assert statement. However, it is single assignment, and its assignment operator won't complain if you reassign the exact same value to an existing variable but will throw an exception otherwise. |
Erlang doesn't have an assert statement. However, it is single assignment, and its assignment operator won't complain if you reassign the exact same value to an existing variable but will throw an exception otherwise. |
||
< |
<syntaxhighlight lang=erlang>1> N = 42. |
||
42 |
42 |
||
2> N = 43. |
2> N = 43. |
||
Line 654: | Line 654: | ||
** exception error: no match of right hand side value 42 |
** exception error: no match of right hand side value 42 |
||
5> 42 = N. |
5> 42 = N. |
||
42</ |
42</syntaxhighlight> |
||
As such, the behavior of Erlang's assignment operator is extremely similar to a regular <tt>assert</tt> in other languages. |
As such, the behavior of Erlang's assignment operator is extremely similar to a regular <tt>assert</tt> in other languages. |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang=euphoria>type fourty_two(integer i) |
||
return i = 42 |
return i = 42 |
||
end type |
end type |
||
Line 665: | Line 665: | ||
fourty_two i |
fourty_two i |
||
i = 41 -- type-check failure</ |
i = 41 -- type-check failure</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
F# provides an ''assert'' function that is only enabled when the program is compiled with ''DEBUG'' defined. When an assertion fails, a dialog box is shown with the option to enter the debugger. |
F# provides an ''assert'' function that is only enabled when the program is compiled with ''DEBUG'' defined. When an assertion fails, a dialog box is shown with the option to enter the debugger. |
||
< |
<syntaxhighlight lang=fsharp>let test x = |
||
assert (x = 42) |
assert (x = 42) |
||
test 43</ |
test 43</syntaxhighlight> |
||
For additional information about assertions in .NET, see [[#C# and Visual Basic .NET]] |
For additional information about assertions in .NET, see [[#C# and Visual Basic .NET]] |
||
Line 679: | Line 679: | ||
Throw an exception if the value on the top of the stack is not equal to 42: |
Throw an exception if the value on the top of the stack is not equal to 42: |
||
< |
<syntaxhighlight lang=factor>USING: kernel ; |
||
42 assert=</ |
42 assert=</syntaxhighlight> |
||
=={{header|FBSL}}== |
=={{header|FBSL}}== |
||
Line 686: | Line 686: | ||
This implementation evaluates the expression given to the function and displays a message if it evaluates to false. |
This implementation evaluates the expression given to the function and displays a message if it evaluates to false. |
||
< |
<syntaxhighlight lang=qbasic>#APPTYPE CONSOLE |
||
DECLARE asserter |
DECLARE asserter |
||
Line 699: | Line 699: | ||
Assert("1>2") |
Assert("1>2") |
||
PAUSE</ |
PAUSE</syntaxhighlight> |
||
Output |
Output |
||
<pre>Assertion: 1>2 failed |
<pre>Assertion: 1>2 failed |
||
Line 706: | Line 706: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang=fsharp>variable a |
||
: assert a @ 42 <> throw ; |
: assert a @ 42 <> throw ; |
||
41 a ! assert</ |
41 a ! assert</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64 |
||
' requires compilation with -g switch |
' requires compilation with -g switch |
||
Line 719: | Line 719: | ||
'The rest of the code will not be executed |
'The rest of the code will not be executed |
||
Print a |
Print a |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 727: | Line 727: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang=gap># See section 7.5 of reference manual |
||
# GAP has assertions levels. An assertion is tested if its level |
# GAP has assertions levels. An assertion is tested if its level |
||
Line 745: | Line 745: | ||
# Show current global level |
# Show current global level |
||
AssertionLevel(); |
AssertionLevel(); |
||
# 10</ |
# 10</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
Assertions are a feature [http://golang.org/doc/go_faq.html#assertions consciously omitted] from Go. For cases where you want feedback during development, the following code should provide a similar purpose. While it is simply an if statement and a panic, the technique does have some properties typical of assertions. For one, the predicate of an if statement in Go is required to be of boolean type. Specifically, ints are not tacitly tested for zero, pointers are not tested for nil: the expression must be boolean, as the WP article mentions is typical of assertions. Also, it provides a good amount of information should the predicate evaluate to true. First, a value of any type can be passed to the panic, and by default is displayed, followed by a stack trace which includes the location of the panic in the source code—function name, file name, and line number. |
Assertions are a feature [http://golang.org/doc/go_faq.html#assertions consciously omitted] from Go. For cases where you want feedback during development, the following code should provide a similar purpose. While it is simply an if statement and a panic, the technique does have some properties typical of assertions. For one, the predicate of an if statement in Go is required to be of boolean type. Specifically, ints are not tacitly tested for zero, pointers are not tested for nil: the expression must be boolean, as the WP article mentions is typical of assertions. Also, it provides a good amount of information should the predicate evaluate to true. First, a value of any type can be passed to the panic, and by default is displayed, followed by a stack trace which includes the location of the panic in the source code—function name, file name, and line number. |
||
< |
<syntaxhighlight lang=go>package main |
||
func main() { |
func main() { |
||
Line 756: | Line 756: | ||
panic(42) |
panic(42) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 773: | Line 773: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang=groovy>def checkTheAnswer = { |
||
assert it == 42 : "This: " + it + " is not the answer!" |
assert it == 42 : "This: " + it + " is not the answer!" |
||
}</ |
}</syntaxhighlight> |
||
Test program: |
Test program: |
||
< |
<syntaxhighlight lang=groovy>println "before 42..." |
||
checkTheAnswer(42) |
checkTheAnswer(42) |
||
println "before 'Hello Universe'..." |
println "before 'Hello Universe'..." |
||
checkTheAnswer("Hello Universe")</ |
checkTheAnswer("Hello Universe")</syntaxhighlight> |
||
Output: |
Output: |
||
Line 791: | Line 791: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang=haskell>import Control.Exception |
||
main = let a = someValue in |
main = let a = someValue in |
||
assert (a == 42) -- throws AssertionFailed when a is not 42 |
assert (a == 42) -- throws AssertionFailed when a is not 42 |
||
somethingElse -- what to return when a is 42</ |
somethingElse -- what to return when a is 42</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang=Icon>... |
||
runerr(n,( expression ,"Assertion/error - message.")) # Throw (and possibly trap) an error number n if expression succeeds. |
runerr(n,( expression ,"Assertion/error - message.")) # Throw (and possibly trap) an error number n if expression succeeds. |
||
... |
... |
||
stop(( expression ,"Assertion/stop - message.")) # Terminate program if expression succeeds. |
stop(( expression ,"Assertion/stop - message.")) # Terminate program if expression succeeds. |
||
...</ |
...</syntaxhighlight> |
||
There are no 'assertions', which can be turned on/off by the compiler. We can emulate them by prefixing a stop statement with a check on a global variable: |
There are no 'assertions', which can be turned on/off by the compiler. We can emulate them by prefixing a stop statement with a check on a global variable: |
||
< |
<syntaxhighlight lang=Icon> |
||
$define DEBUG 1 # this allows the assertions to go through |
$define DEBUG 1 # this allows the assertions to go through |
||
Line 820: | Line 820: | ||
check (12) |
check (12) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
This produces the output: |
This produces the output: |
||
Line 831: | Line 831: | ||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang=j> assert n = 42</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang=java5>public class Assertions { |
||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
Line 849: | Line 849: | ||
// The error message can be any non-void expression. |
// The error message can be any non-void expression. |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Note: assertion checking is disabled by default when you run your program with the <tt>java</tt> command. You must provide the <tt>-ea</tt> (short for <tt>-enableassertions</tt>) flag in order to enable them. |
Note: assertion checking is disabled by default when you run your program with the <tt>java</tt> command. You must provide the <tt>-ea</tt> (short for <tt>-enableassertions</tt>) flag in order to enable them. |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang=javaScript> |
||
function check() { |
function check() { |
||
try { |
try { |
||
Line 878: | Line 878: | ||
answer = 23; |
answer = 23; |
||
check(); |
check(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}}<pre> |
{{out}}<pre> |
||
Line 936: | Line 936: | ||
'''assert.jq''' |
'''assert.jq''' |
||
< |
<syntaxhighlight lang=jq>def assert(exp; $msg): |
||
def m: $msg | if type == "string" then . else [.[]] | join(":") end; |
def m: $msg | if type == "string" then . else [.[]] | join(":") end; |
||
if env.JQ_ASSERT then |
if env.JQ_ASSERT then |
||
Line 955: | Line 955: | ||
end |
end |
||
else . end; |
else . end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Example''' |
'''Example''' |
||
<syntaxhighlight lang=jq> |
|||
<lang jq> |
|||
# File: example.jq |
# File: example.jq |
||
# This example assumes the availability of the $__loc__ function |
# This example assumes the availability of the $__loc__ function |
||
Line 970: | Line 970: | ||
asserteq($x; 42; $__loc__); |
asserteq($x; 42; $__loc__); |
||
test</ |
test</syntaxhighlight> |
||
'''Invocation''' |
'''Invocation''' |
||
JQ_ASSERT=1 jq -n -f example.jq |
JQ_ASSERT=1 jq -n -f example.jq |
||
Line 984: | Line 984: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang=julia>const x = 5 |
||
# @assert macro checks the supplied conditional expression, with the expression |
# @assert macro checks the supplied conditional expression, with the expression |
||
Line 995: | Line 995: | ||
x::String |
x::String |
||
# ERROR: LoadError: TypeError: in typeassert, expected String, got Int64 |
# ERROR: LoadError: TypeError: in typeassert, expected String, got Int64 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Kotlin supports Jva-style assertions. These need to be enabled using java's -ea option for an <code>AssertionError</code> to be thrown when the condition is false. An assertion should generally never fire, and throws an <code>Error</code>. <code>Error</code>s are seldom used in Kotlin (and much less assertions), as they represent catastrophic issues with the program, such as classes failing to load. These are usually only ever raised by the JVM itself, rather than actual user code. |
Kotlin supports Jva-style assertions. These need to be enabled using java's -ea option for an <code>AssertionError</code> to be thrown when the condition is false. An assertion should generally never fire, and throws an <code>Error</code>. <code>Error</code>s are seldom used in Kotlin (and much less assertions), as they represent catastrophic issues with the program, such as classes failing to load. These are usually only ever raised by the JVM itself, rather than actual user code. |
||
< |
<syntaxhighlight lang=kotlin>fun main() { |
||
val a = 42 |
val a = 42 |
||
assert(a == 43) |
assert(a == 43) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,013: | Line 1,013: | ||
A more Kotlin idiomatic approach to checks are the <code>require</code> (and <code>requireNotNull</code>) to check arguments, and the <code>check</code> (and <code>checkNotNull</code>), and <code>error</code> to check state. The former is mostly meant for checking input, and will throw <code>IllegalArgumentException</code>s, whereas the later is meant for state-checking, and will throw <code>IllegalStateException</code>s |
A more Kotlin idiomatic approach to checks are the <code>require</code> (and <code>requireNotNull</code>) to check arguments, and the <code>check</code> (and <code>checkNotNull</code>), and <code>error</code> to check state. The former is mostly meant for checking input, and will throw <code>IllegalArgumentException</code>s, whereas the later is meant for state-checking, and will throw <code>IllegalStateException</code>s |
||
< |
<syntaxhighlight lang=kotlin>fun findName(names: Map<String, String>, firstName: String) { |
||
require(names.isNotEmpty()) { "Please pass a non-empty names map" } // IllegalArgumentException |
require(names.isNotEmpty()) { "Please pass a non-empty names map" } // IllegalArgumentException |
||
val lastName = requireNotNull(names[name]) { "names is expected to contain name" } // IllegalArgumentException |
val lastName = requireNotNull(names[name]) { "names is expected to contain name" } // IllegalArgumentException |
||
Line 1,020: | Line 1,020: | ||
check(fullName.contains(" ")) { "fullname was expected to have a space...?" } // IllegalStateException |
check(fullName.contains(" ")) { "fullname was expected to have a space...?" } // IllegalStateException |
||
return fullName |
return fullName |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang=lasso>local(a) = 8 |
||
fail_if( |
fail_if( |
||
#a != 42, |
#a != 42, |
||
error_code_runtimeAssertion, |
error_code_runtimeAssertion, |
||
error_msg_runtimeAssertion + ": #a is not 42" |
error_msg_runtimeAssertion + ": #a is not 42" |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>-9945 Runtime assertion: #a is not 42</pre> |
<pre>-9945 Runtime assertion: #a is not 42</pre> |
||
Line 1,036: | Line 1,036: | ||
but we could break program if condition is not met. |
but we could break program if condition is not met. |
||
We can even make it spell "AssertionFailed". In a way. |
We can even make it spell "AssertionFailed". In a way. |
||
<syntaxhighlight lang=lb> |
|||
<lang lb> |
|||
a=42 |
a=42 |
||
call assert a=42 |
call assert a=42 |
||
Line 1,051: | Line 1,051: | ||
end if |
end if |
||
end sub |
end sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,066: | Line 1,066: | ||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
Lingo has no assert statement, but the abort command (that exits the full call stack) allows to implement something like it as global function: |
Lingo has no assert statement, but the abort command (that exits the full call stack) allows to implement something like it as global function: |
||
< |
<syntaxhighlight lang=lingo>-- in a movie script |
||
on assert (ok, message) |
on assert (ok, message) |
||
if not ok then |
if not ok then |
||
Line 1,082: | Line 1,082: | ||
assert(x=42, "Assertion 'x=42' failed") |
assert(x=42, "Assertion 'x=42' failed") |
||
put "this will never show up" |
put "this will never show up" |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang=Lisaac>? { n = 42 };</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang=lua>a = 5 |
||
assert (a == 42) |
assert (a == 42) |
||
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')</ |
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
Line 1,098: | Line 1,098: | ||
< |
<syntaxhighlight lang=M2000 Interpreter> |
||
Module Assert { |
Module Assert { |
||
\\ This is a global object named Rec |
\\ This is a global object named Rec |
||
Line 1,159: | Line 1,159: | ||
} |
} |
||
Assert |
Assert |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
(Taken from Lua, above.) |
(Taken from Lua, above.) |
||
< |
<syntaxhighlight lang=Maple>a := 5: |
||
ASSERT( a = 42 ); |
ASSERT( a = 42 ); |
||
ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );</ |
ASSERT( a = 42, "a is not the answer to life, the universe, and everything" );</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang=Mathematica>Assert[var===42]</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang=MATLAB>assert(x == 42,'x = %d, not 42.',x);</syntaxhighlight> |
||
Sample Output: |
Sample Output: |
||
< |
<syntaxhighlight lang=MATLAB>x = 3; |
||
assert(x == 42,'Assertion Failed: x = %d, not 42.',x); |
assert(x == 42,'Assertion Failed: x = %d, not 42.',x); |
||
??? Assertion Failed: x = 3, not 42. |
??? Assertion Failed: x = 3, not 42. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 1,185: | Line 1,185: | ||
Metafont has no really an assert built in, but it can easily created: |
Metafont has no really an assert built in, but it can easily created: |
||
< |
<syntaxhighlight lang=metafont>def assert(expr t) = if not (t): errmessage("assertion failed") fi enddef;</syntaxhighlight> |
||
This <code>assert</code> macro uses the <code>errmessage</code> built in to show the "error". The |
This <code>assert</code> macro uses the <code>errmessage</code> built in to show the "error". The |
||
Line 1,192: | Line 1,192: | ||
Usage example: |
Usage example: |
||
< |
<syntaxhighlight lang=metafont>n := 41; |
||
assert(n=42); |
assert(n=42); |
||
message "ok";</ |
message "ok";</syntaxhighlight> |
||
Output (failed assertion): |
Output (failed assertion): |
||
Line 1,209: | Line 1,209: | ||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
<code>ASSERT</code> is a pragma, that creates a run-time error if it returns <code>FALSE</code>. |
<code>ASSERT</code> is a pragma, that creates a run-time error if it returns <code>FALSE</code>. |
||
< |
<syntaxhighlight lang=modula3><*ASSERT a = 42*></syntaxhighlight> |
||
Assertions can be ignored in the compiler by using the <code>-a</code> switch. |
Assertions can be ignored in the compiler by using the <code>-a</code> switch. |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang=Nanoquery>a = 5 |
||
assert (a = 42)</ |
assert (a = 42)</syntaxhighlight> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
A basic assertion uses the <tt>assert</tt> keyword: |
A basic assertion uses the <tt>assert</tt> keyword: |
||
< |
<syntaxhighlight lang=Nemerle>assert (foo == 42, $"foo == $foo, not 42.")</syntaxhighlight> |
||
Assertion violations throw an <tt>AssertionException</tt> with the line number where the assertion failed and the message provided as the second parameter to assert. |
Assertion violations throw an <tt>AssertionException</tt> with the line number where the assertion failed and the message provided as the second parameter to assert. |
||
Nemerle also provides macros in the <tt>Nemerle.Assertions</tt> namespace to support preconditions, postconditions and class invariants: |
Nemerle also provides macros in the <tt>Nemerle.Assertions</tt> namespace to support preconditions, postconditions and class invariants: |
||
< |
<syntaxhighlight lang=Nemerle>using Nemerle.Assertions; |
||
class SampleClass |
class SampleClass |
||
Line 1,235: | Line 1,235: | ||
ensures value.Length > 0 // ensures keyword indicates postcondition |
ensures value.Length > 0 // ensures keyword indicates postcondition |
||
{ ... } // value is a special symbol that indicates the method's return value |
{ ... } // value is a special symbol that indicates the method's return value |
||
}</ |
}</syntaxhighlight> |
||
The design by contract macros throw <tt>Nemerle.AssertionException</tt>'s unless another Exception is specified using the <tt>otherwise</tt> keyword after the <tt>requires/ensures</tt> statement. |
The design by contract macros throw <tt>Nemerle.AssertionException</tt>'s unless another Exception is specified using the <tt>otherwise</tt> keyword after the <tt>requires/ensures</tt> statement. |
||
For further details on design by contract macros, see [http://nemerle.org/wiki/index.php?title=Design_by_contract_macros here]. |
For further details on design by contract macros, see [http://nemerle.org/wiki/index.php?title=Design_by_contract_macros here]. |
||
Line 1,248: | Line 1,248: | ||
* it is a pattern, numbers match themselves exactly, other patterns that would match: <tt>Int</tt>, <tt>0..100</tt>, <tt>Any</tt> |
* it is a pattern, numbers match themselves exactly, other patterns that would match: <tt>Int</tt>, <tt>0..100</tt>, <tt>Any</tt> |
||
< |
<syntaxhighlight lang=NGS>a = 42 |
||
assert(a==42) |
assert(a==42) |
||
assert(a, 42) |
assert(a, 42) |
||
assert(a==42, "Not 42!") |
assert(a==42, "Not 42!") |
||
assert(a, 42, "Not 42!")</ |
assert(a, 42, "Not 42!")</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
In Nim there are two main ways to check assertions. |
In Nim there are two main ways to check assertions. |
||
< |
<syntaxhighlight lang=Nim>var a = 42 |
||
assert(a == 42, "Not 42!")</ |
assert(a == 42, "Not 42!")</syntaxhighlight> |
||
This first kind of assertion may be disabled by compiling with --assertions:off or -d:danger. |
This first kind of assertion may be disabled by compiling with --assertions:off or -d:danger. |
||
< |
<syntaxhighlight lang=Nim>var a = 42 |
||
doAssert(a == 42, "Not 42!")</ |
doAssert(a == 42, "Not 42!")</syntaxhighlight> |
||
This second kind of assertion cannot be disabled. |
This second kind of assertion cannot be disabled. |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Oxford Oberon-2 |
Oxford Oberon-2 |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE Assertions; |
MODULE Assertions; |
||
VAR |
VAR |
||
Line 1,274: | Line 1,274: | ||
ASSERT(a = 42); |
ASSERT(a = 42); |
||
END Assertions. |
END Assertions. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,284: | Line 1,284: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
If variable is not equal to 42 a stack trace is generated and the program is halts. |
If variable is not equal to 42 a stack trace is generated and the program is halts. |
||
< |
<syntaxhighlight lang=objeck>class Test { |
||
function : Main(args : String[]) ~ Nil { |
function : Main(args : String[]) ~ Nil { |
||
if(args->Size() = 1) { |
if(args->Size() = 1) { |
||
Line 1,292: | Line 1,292: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
For use within an Objective-C method: |
For use within an Objective-C method: |
||
< |
<syntaxhighlight lang=objc>NSAssert(a == 42, @"Error message");</syntaxhighlight> |
||
If you want to use formatting arguments, you need to use the assertion macro corresponding to your number of formatting arguments: |
If you want to use formatting arguments, you need to use the assertion macro corresponding to your number of formatting arguments: |
||
< |
<syntaxhighlight lang=objc>NSAssert1(a == 42, @"a is not 42, a is actually %d", a); # has 1 formatting arg, so use NSAssert"1"</syntaxhighlight> |
||
Within a regular C function you should use <code>NSCAssert</code> or <code>NSCAssert''N''</code> instead. |
Within a regular C function you should use <code>NSCAssert</code> or <code>NSCAssert''N''</code> instead. |
||
Line 1,306: | Line 1,306: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang=ocaml>let a = get_some_value () in |
||
assert (a = 42); (* throws Assert_failure when a is not 42 *) |
assert (a = 42); (* throws Assert_failure when a is not 42 *) |
||
(* evaluate stuff to return here when a is 42 *)</ |
(* evaluate stuff to return here when a is 42 *)</syntaxhighlight> |
||
It is possible to compile with the parameter <code>-noassert</code> then the compiler won't compile the assertion checks. |
It is possible to compile with the parameter <code>-noassert</code> then the compiler won't compile the assertion checks. |
||
Line 1,320: | Line 1,320: | ||
If an assertion is ko (and if oforth is launched using --a), an exception is raised. |
If an assertion is ko (and if oforth is launched using --a), an exception is raised. |
||
< |
<syntaxhighlight lang=Oforth>: testInteger(n, m) |
||
assert: [ n isInteger ] |
assert: [ n isInteger ] |
||
assert: [ n 42 == ] |
assert: [ n 42 == ] |
||
System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;</ |
System.Out "Assertions are ok, parameters are : " << n << ", " << m << cr ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,336: | Line 1,336: | ||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang=scheme> |
||
(define i 24) |
(define i 24) |
||
(assert i ===> 42) |
(assert i ===> 42) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,356: | Line 1,356: | ||
Oz does not have an assert statement. But if different values are assigned to the same dataflow variable, an exception will be thrown (similar to Erlang). |
Oz does not have an assert statement. But if different values are assigned to the same dataflow variable, an exception will be thrown (similar to Erlang). |
||
< |
<syntaxhighlight lang=oz>declare |
||
proc {PrintNumber N} |
proc {PrintNumber N} |
||
N=42 %% assert |
N=42 %% assert |
||
Line 1,363: | Line 1,363: | ||
in |
in |
||
{PrintNumber 42} %% ok |
{PrintNumber 42} %% ok |
||
{PrintNumber 11} %% throws </ |
{PrintNumber 11} %% throws </syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,378: | Line 1,378: | ||
PARI can use any of the usual C methods for making assertions. GP has no built-in assertions. |
PARI can use any of the usual C methods for making assertions. GP has no built-in assertions. |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang=C>#include <assert.h> |
||
#include <pari/pari.h> |
#include <pari/pari.h> |
||
Line 1,388: | Line 1,388: | ||
assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */ |
assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */ |
||
}</ |
}</syntaxhighlight> |
||
More common is the use of <code>pari_err_BUG</code> in such cases: |
More common is the use of <code>pari_err_BUG</code> in such cases: |
||
< |
<syntaxhighlight lang=C>if (!equalis(a, 42)) pari_err_BUG("this_function_name (expected a = 42)");</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Line 1,399: | Line 1,399: | ||
While not exactly an assertion, a common Perl idiom is to use <code>or die</code> to throw an exception when a certain statement is false. |
While not exactly an assertion, a common Perl idiom is to use <code>or die</code> to throw an exception when a certain statement is false. |
||
< |
<syntaxhighlight lang=perl>print "Give me a number: "; |
||
chomp(my $a = <>); |
chomp(my $a = <>); |
||
Line 1,407: | Line 1,407: | ||
die "Error message\n" unless $a == 42; |
die "Error message\n" unless $a == 42; |
||
die "Error message\n" if not $a == 42; |
die "Error message\n" if not $a == 42; |
||
die "Error message\n" if $a != 42;</ |
die "Error message\n" if $a != 42;</syntaxhighlight> |
||
This idiom is typically used during file operations: |
This idiom is typically used during file operations: |
||
< |
<syntaxhighlight lang=perl>open my $fh, '<', 'file' |
||
or die "Cannot open file: $!\n"; # $! contains the error message from the last error</ |
or die "Cannot open file: $!\n"; # $! contains the error message from the last error</syntaxhighlight> |
||
It is not needed whith the "autodie" pragma: |
It is not needed whith the "autodie" pragma: |
||
< |
<syntaxhighlight lang=perl>use autodie; |
||
open my $fh, '<', 'file'; # automatically throws an exception on failure</ |
open my $fh, '<', 'file'; # automatically throws an exception on failure</syntaxhighlight> |
||
Some third-party modules provide other ways of using assertions in Perl: |
Some third-party modules provide other ways of using assertions in Perl: |
||
< |
<syntaxhighlight lang=perl>use Carp::Assert; |
||
assert($a == 42);</ |
assert($a == 42);</syntaxhighlight> |
||
There is also a number of ways to test assertions in test suites, for example: |
There is also a number of ways to test assertions in test suites, for example: |
||
< |
<syntaxhighlight lang=perl>is $a, 42; |
||
ok $a == 42; |
ok $a == 42; |
||
cmp_ok $a, '==', 42, 'The answer should be 42'; |
cmp_ok $a, '==', 42, 'The answer should be 42'; |
||
# etc.</ |
# etc.</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
User defined types allow the value to be automatically tested whenever it changes, and |
User defined types allow the value to be automatically tested whenever it changes, and |
||
can be disabled using the "without type_check" directive: |
can be disabled using the "without type_check" directive: |
||
<!--< |
<!--<syntaxhighlight lang=Phix>(phixonline)--> |
||
<span style="color: #008080;">type</span> <span style="color: #000000;">int42</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">type</span> <span style="color: #000000;">int42</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span> |
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span> |
||
Line 1,437: | Line 1,437: | ||
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">41</span> <span style="color: #000080;font-style:italic;">-- type-check failure (desktop/Phix only)</span> |
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">41</span> <span style="color: #000080;font-style:italic;">-- type-check failure (desktop/Phix only)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
When a type check occurs, program execution halts and if the program was run from the |
When a type check occurs, program execution halts and if the program was run from the |
||
editor, it automatically jumps to the offending source file and line. |
editor, it automatically jumps to the offending source file and line. |
||
Line 1,448: | Line 1,448: | ||
You can also use constants to reduce code output on release versions: |
You can also use constants to reduce code output on release versions: |
||
<!--< |
<!--<syntaxhighlight lang=Phix>(phixonline)--> |
||
<span style="color: #008080;">global</span> <span style="color: #008080;">constant</span> <span style="color: #000000;">DEBUG</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- (or any other identifier name can be used)</span> |
<span style="color: #008080;">global</span> <span style="color: #008080;">constant</span> <span style="color: #000000;">DEBUG</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- (or any other identifier name can be used)</span> |
||
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- see also assert() below</span> |
<span style="color: #008080;">global</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- see also assert() below</span> |
||
Line 1,462: | Line 1,462: | ||
<span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span> |
<span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
Note that while the body of check() and the call to it are suppressed, the calculation |
Note that while the body of check() and the call to it are suppressed, the calculation |
||
of the expression (i=42) may still generate code; sometimes further improvements to the |
of the expression (i=42) may still generate code; sometimes further improvements to the |
||
Line 1,473: | Line 1,473: | ||
first line terminates with a divide by zero, whereas the second and third produce a |
first line terminates with a divide by zero, whereas the second and third produce a |
||
slightly more user-friendly, and therefore potentially less developer-friendly message: |
slightly more user-friendly, and therefore potentially less developer-friendly message: |
||
<!--< |
<!--<syntaxhighlight lang=Phix>(phixonline)--> |
||
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">42</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">42</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
||
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">42</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">42</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
||
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"i is not 42!!"</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
The assert statment is really just shorthand for the crash statement above it, except that |
The assert statment is really just shorthand for the crash statement above it, except that |
||
the error message is optional (defaults to "assertion failure"). |
the error message is optional (defaults to "assertion failure"). |
||
Line 1,484: | Line 1,484: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang=php><?php |
||
$a = 5 |
$a = 5 |
||
#...input or change $a here |
#...input or change $a here |
||
assert($a == 42) # when $a is not 42, take appropriate actions, |
assert($a == 42) # when $a is not 42, take appropriate actions, |
||
# which is set by assert_options() |
# which is set by assert_options() |
||
?></ |
?></syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
Line 1,497: | Line 1,497: | ||
The predicate/function that is tested but be "escaped" by <code>$</code> in order to not be evaluated before the test. |
The predicate/function that is tested but be "escaped" by <code>$</code> in order to not be evaluated before the test. |
||
< |
<syntaxhighlight lang=Picat>go => |
||
% |
% |
||
Line 1,533: | Line 1,533: | ||
println(Name ++ ": " ++ cond(apply(A) == Expected, "ok", "not ok")). |
println(Name ++ ": " ++ cond(apply(A) == Expected, "ok", "not ok")). |
||
assert_failure(Name, A, Expected) => |
assert_failure(Name, A, Expected) => |
||
println(Name ++ ": " ++ cond(apply(A) != Expected , "ok", "not ok")).</ |
println(Name ++ ": " ++ cond(apply(A) != Expected , "ok", "not ok")).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,549: | Line 1,549: | ||
The '[http://software-lab.de/doc/refA.html#assert assert]' function, in |
The '[http://software-lab.de/doc/refA.html#assert assert]' function, in |
||
combination with the tilde read macro, generates code only in debug mode: |
combination with the tilde read macro, generates code only in debug mode: |
||
< |
<syntaxhighlight lang=PicoLisp>... |
||
~(assert (= N 42)) # Exists only in debug mode |
~(assert (= N 42)) # Exists only in debug mode |
||
...</ |
...</syntaxhighlight> |
||
Other possibilities are either to break into an error handler: |
Other possibilities are either to break into an error handler: |
||
< |
<syntaxhighlight lang=PicoLisp>(let N 41 |
||
(unless (= N 42) (quit "Incorrect N" N)) ) # 'quit' throws an error |
(unless (= N 42) (quit "Incorrect N" N)) ) # 'quit' throws an error |
||
41 -- Incorrect N |
41 -- Incorrect N |
||
?</ |
?</syntaxhighlight> |
||
or to stop at a debug break point, allowing to continue with the program: |
or to stop at a debug break point, allowing to continue with the program: |
||
< |
<syntaxhighlight lang=PicoLisp>(let N 41 |
||
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint |
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint |
||
(setq N 42) # Manually fix the value |
(setq N 42) # Manually fix the value |
||
! # Hit ENTER to leave the breakpoint |
! # Hit ENTER to leave the breakpoint |
||
-> 42</ |
-> 42</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
Line 1,584: | Line 1,584: | ||
assert(a, 42); |
assert(a, 42); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
{{works with|SWI Prolog}} |
{{works with|SWI Prolog}} |
||
< |
<syntaxhighlight lang=prolog> |
||
test(A):- |
test(A):- |
||
assertion(A==42). |
assertion(A==42). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Line 1,599: | Line 1,599: | ||
The Macro below will only be included in the code if is compiled in debug mode, if so it will test the condition and if it fails it will inform with the message defined by the programmer, the line where it happened and in which source code file. |
The Macro below will only be included in the code if is compiled in debug mode, if so it will test the condition and if it fails it will inform with the message defined by the programmer, the line where it happened and in which source code file. |
||
< |
<syntaxhighlight lang=PureBasic>Macro Assert(TEST,MSG="Assert: ") |
||
CompilerIf #PB_Compiler_Debugger |
CompilerIf #PB_Compiler_Debugger |
||
If Not (TEST) |
If Not (TEST) |
||
Line 1,606: | Line 1,606: | ||
EndIf |
EndIf |
||
CompilerEndIf |
CompilerEndIf |
||
EndMacro</ |
EndMacro</syntaxhighlight> |
||
A implementation as defined above could be; |
A implementation as defined above could be; |
||
< |
<syntaxhighlight lang=PureBasic>A=42 |
||
Assert(A=42,"Assert that A=42") |
Assert(A=42,"Assert that A=42") |
||
A=42-1 |
A=42-1 |
||
Assert(A=42)</ |
Assert(A=42)</syntaxhighlight> |
||
Where the second test would fail resulting in a message to the programmer with cause (if given by programmer), code line & file. |
Where the second test would fail resulting in a message to the programmer with cause (if given by programmer), code line & file. |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang=python>a = 5 |
||
#...input or change a here |
#...input or change a here |
||
assert a == 42 # throws an AssertionError when a is not 42 |
assert a == 42 # throws an AssertionError when a is not 42 |
||
assert a == 42, "Error message" # throws an AssertionError |
assert a == 42, "Error message" # throws an AssertionError |
||
# when a is not 42 with "Error message" for the message |
# when a is not 42 with "Error message" for the message |
||
# the error message can be any expression</ |
# the error message can be any expression</syntaxhighlight> |
||
It is possible to turn off assertions by running Python with the <tt>-O</tt> (optimizations) flag. |
It is possible to turn off assertions by running Python with the <tt>-O</tt> (optimizations) flag. |
||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
< |
<syntaxhighlight lang=vb>$ASSERTS:CONSOLE |
||
DO |
DO |
||
Line 1,640: | Line 1,640: | ||
IF value > 1 THEN plural$ = "s" |
IF value > 1 THEN plural$ = "s" |
||
myFunc$ = STRING$(value, "*") + STR$(value) + " star" + plural$ + " :-)" |
myFunc$ = STRING$(value, "*") + STR$(value) + " star" + plural$ + " :-)" |
||
END FUNCTION</ |
END FUNCTION</syntaxhighlight> |
||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang=R>stopifnot(a==42)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Line 1,649: | Line 1,649: | ||
Racket has higher-order assertions known as ''contracts'' that can protect any values including functions and objects. Contracts are typically applied on the imports or exports of a module. |
Racket has higher-order assertions known as ''contracts'' that can protect any values including functions and objects. Contracts are typically applied on the imports or exports of a module. |
||
< |
<syntaxhighlight lang=Racket>#lang racket |
||
(define/contract x |
(define/contract x |
||
Line 1,662: | Line 1,662: | ||
(f 42) ; succeeds |
(f 42) ; succeeds |
||
(f "foo") ; contract error! |
(f "foo") ; contract error! |
||
</syntaxhighlight> |
|||
</lang> |
|||
If typical assertion checking (i.e. error unless some boolean condition holds) is needed, that is also possible: |
If typical assertion checking (i.e. error unless some boolean condition holds) is needed, that is also possible: |
||
< |
<syntaxhighlight lang=Racket>#lang racket |
||
(define x 80) |
(define x 80) |
||
(unless (= x 42) |
(unless (= x 42) |
||
(error "a is not 42")) ; will error |
(error "a is not 42")) ; will error |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
< |
<syntaxhighlight lang=perl6>my $a = (1..100).pick; |
||
$a == 42 or die '$a ain\'t 42';</ |
$a == 42 or die '$a ain\'t 42';</syntaxhighlight> |
||
{{works with|pugs}} |
{{works with|pugs}} |
||
''Note: This example uses an experimental feature, and does not work in the primary Perl 6 compiler, Rakudo.'' |
''Note: This example uses an experimental feature, and does not work in the primary Perl 6 compiler, Rakudo.'' |
||
< |
<syntaxhighlight lang=perl6># with a (non-hygienic) macro |
||
macro assert ($x) { "$x or die 'assertion failed: $x'" } |
macro assert ($x) { "$x or die 'assertion failed: $x'" } |
||
assert('$a == 42');</ |
assert('$a == 42');</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===version 1=== |
===version 1=== |
||
< |
<syntaxhighlight lang=REXX>/* REXX *************************************************************** |
||
* There's no assert feature in Rexx. That's how I'd implement it |
* There's no assert feature in Rexx. That's how I'd implement it |
||
* 10.08.2012 Walter Pachl |
* 10.08.2012 Walter Pachl |
||
Line 1,709: | Line 1,709: | ||
End |
End |
||
Return |
Return |
||
Syntax: Say 'program terminated'</ |
Syntax: Say 'program terminated'</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,732: | Line 1,732: | ||
<br>possible actions. Here, it just returns to the next REXX statement after the |
<br>possible actions. Here, it just returns to the next REXX statement after the |
||
'''call assert'''. |
'''call assert'''. |
||
< |
<syntaxhighlight lang=rexx>/*REXX program implements a simple ASSERT function; the expression can be compound. */ |
||
a = 1 /*assign a value to the A variable.*/ |
a = 1 /*assign a value to the A variable.*/ |
||
b = -2 /* " " " " " B " */ |
b = -2 /* " " " " " B " */ |
||
Line 1,746: | Line 1,746: | ||
assert: if arg(1)=1 then return; parse value sourceline(sigl) with x; say |
assert: if arg(1)=1 then return; parse value sourceline(sigl) with x; say |
||
say '===== ASSERT failure in REXX line' sigl", the statement is:"; say '=====' x |
say '===== ASSERT failure in REXX line' sigl", the statement is:"; say '=====' x |
||
say; return</ |
say; return</syntaxhighlight> |
||
{{out|output|text= when using the internal defaults:}} |
{{out|output|text= when using the internal defaults:}} |
||
<pre> |
<pre> |
||
Line 1,758: | Line 1,758: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang=ring> |
||
x = 42 |
x = 42 |
||
assert( x = 42 ) |
assert( x = 42 ) |
||
assert( x = 100 ) |
assert( x = 100 ) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
RLaB does not have a special function to deal with assertions. The following workaround will do the trick: |
RLaB does not have a special function to deal with assertions. The following workaround will do the trick: |
||
< |
<syntaxhighlight lang=RLaB> |
||
// test if 'a' is 42, and if not stop the execution of the code and print |
// test if 'a' is 42, and if not stop the execution of the code and print |
||
// some error message |
// some error message |
||
Line 1,774: | Line 1,774: | ||
stop("a is not 42 as expected, therefore I stop until this issue is resolved!"); |
stop("a is not 42 as expected, therefore I stop until this issue is resolved!"); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
This uses test/unit from the standard library. |
This uses test/unit from the standard library. |
||
< |
<syntaxhighlight lang=ruby>require "test/unit/assertions" |
||
include Test::Unit::Assertions |
include Test::Unit::Assertions |
||
Line 1,789: | Line 1,789: | ||
# Ruby 1.9: e is a MiniTest::Assertion |
# Ruby 1.9: e is a MiniTest::Assertion |
||
puts e |
puts e |
||
end</ |
end</syntaxhighlight> |
||
Output: <pre><42> expected but was |
Output: <pre><42> expected but was |
||
Line 1,795: | Line 1,795: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust> |
||
let x = 42; |
let x = 42; |
||
assert!(x == 42); |
assert!(x == 42); |
||
assert_eq!(x, 42); |
assert_eq!(x, 42); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang=sather>class MAIN is |
||
main is |
main is |
||
i ::= 41; |
i ::= 41; |
||
Line 1,808: | Line 1,808: | ||
-- ... |
-- ... |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
(The current GNU Sather compiler v1.2.3 I am using to test the code seems to ignore the assertion and no fatal error is raised, despite Sather should, see e.g. [http://www.gnu.org/software/sather/docs-1.2/tutorial/safety2208.html here]). |
(The current GNU Sather compiler v1.2.3 I am using to test the code seems to ignore the assertion and no fatal error is raised, despite Sather should, see e.g. [http://www.gnu.org/software/sather/docs-1.2/tutorial/safety2208.html here]). |
||
Line 1,814: | Line 1,814: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
These two are the same thing, and are tagged <code>@elidable(ASSERTION)</code>: |
These two are the same thing, and are tagged <code>@elidable(ASSERTION)</code>: |
||
< |
<syntaxhighlight lang=scala>assert(a == 42) |
||
assert(a == 42, "a isn't equal to 42") |
assert(a == 42, "a isn't equal to 42") |
||
assume(a == 42) |
assume(a == 42) |
||
assume(a == 42, "a isn't equal to 42")</ |
assume(a == 42, "a isn't equal to 42")</syntaxhighlight> |
||
The next one does the same thing as above, but it is not tagged. Often used as a pre-condition |
The next one does the same thing as above, but it is not tagged. Often used as a pre-condition |
||
checker on class constructors. |
checker on class constructors. |
||
< |
<syntaxhighlight lang=scala>require(a == 42) |
||
require(a == 42, "a isn't equal to 42")</ |
require(a == 42, "a isn't equal to 42")</syntaxhighlight> |
||
This one checks a value and returns it for further use (here shown being printed). It |
This one checks a value and returns it for further use (here shown being printed). It |
||
uses <code>assert</code>, which, as explained, gets tagged. |
uses <code>assert</code>, which, as explained, gets tagged. |
||
< |
<syntaxhighlight lang=scala>println(a.ensuring(a == 42)) |
||
println(a.ensuring(a == 42, "a isn't equal to 42")) |
println(a.ensuring(a == 42, "a isn't equal to 42")) |
||
println(a.ensuring(_ == 42)) |
println(a.ensuring(_ == 42)) |
||
println(a.ensuring(_ == 42, "a isn't equal to 42"))</ |
println(a.ensuring(_ == 42, "a isn't equal to 42"))</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
Line 1,835: | Line 1,835: | ||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
< |
<syntaxhighlight lang=scheme>(let ((x 42)) |
||
(assert (and (integer? x) (= x 42))))</ |
(assert (and (integer? x) (= x 42))))</syntaxhighlight> |
||
=={{header|SETL}}== |
=={{header|SETL}}== |
||
< |
<syntaxhighlight lang=ada>assert( n = 42 );</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang=ruby>var num = pick(0..100); |
||
assert_eq(num, 42); # dies when "num" is not 42</ |
assert_eq(num, 42); # dies when "num" is not 42</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,850: | Line 1,850: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang=slate>load: 'src/lib/assert.slate'. |
||
define: #n -> 7. |
define: #n -> 7. |
||
assert: n = 42 &description: 'That is not the Answer.'.</ |
assert: n = 42 &description: 'That is not the Answer.'.</syntaxhighlight> |
||
raises an <tt>AssertionFailed</tt> condition (an <tt>Error</tt>). |
raises an <tt>AssertionFailed</tt> condition (an <tt>Error</tt>). |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang=smalltalk>foo := 41. |
||
... |
... |
||
self assert: (foo == 42).</ |
self assert: (foo == 42).</syntaxhighlight> |
||
In TestCase and subclasses, a number of check methods are inherited; among them: |
In TestCase and subclasses, a number of check methods are inherited; among them: |
||
< |
<syntaxhighlight lang=smalltalk>self assert: (... somethingMustEvaluateToTrue.. ) |
||
self should:[ some code ] raise: someException "ensures that an exception is raised</ |
self should:[ some code ] raise: someException "ensures that an exception is raised</syntaxhighlight> |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
Object also implements assert:; these are evaluated dynamically, but can be disabled via a flag setting. Also the compiler can be instructed to ignore them for production code (which is not normally done; disabled instead by default): |
Object also implements assert:; these are evaluated dynamically, but can be disabled via a flag setting. Also the compiler can be instructed to ignore them for production code (which is not normally done; disabled instead by default): |
||
< |
<syntaxhighlight lang=smalltalk>self assert: (... somethingMustEvaluateToTrue.. ) "implemented in Object"</syntaxhighlight> |
||
the implementation in Object raises an AssertionFailedError exception, which usually opens a debugger when in the IDE, but can be caught in deployed apps. |
the implementation in Object raises an AssertionFailedError exception, which usually opens a debugger when in the IDE, but can be caught in deployed apps. |
||
Line 1,874: | Line 1,874: | ||
Assertions are analysed statically, before compilation or execution. They can appear in various places: |
Assertions are analysed statically, before compilation or execution. They can appear in various places: |
||
:inline in the code, either |
:inline in the code, either |
||
< |
<syntaxhighlight lang=ada>-# check X = 42;</syntaxhighlight> |
||
::or |
::or |
||
< |
<syntaxhighlight lang=ada>-# assert X = 42;</syntaxhighlight> |
||
:as a precondition on an operation: |
:as a precondition on an operation: |
||
< |
<syntaxhighlight lang=ada>procedure P (X : in out Integer); |
||
--# derives X from *; |
--# derives X from *; |
||
--# pre X = 42;</ |
--# pre X = 42;</syntaxhighlight> |
||
:or as a postcondition on an operation: |
:or as a postcondition on an operation: |
||
< |
<syntaxhighlight lang=ada>procedure P (X : in out Integer); |
||
--# derives X from *; |
--# derives X from *; |
||
--# post X = 42;</ |
--# post X = 42;</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang=ada>X := 7; |
||
--# check X = 42;</ |
--# check X = 42;</syntaxhighlight> |
||
produces the following output: |
produces the following output: |
||
<pre>H1: true . |
<pre>H1: true . |
||
Line 1,896: | Line 1,896: | ||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
Using exceptions: |
Using exceptions: |
||
< |
<syntaxhighlight lang=sml>fun assert cond = |
||
if cond then () else raise Fail "assert" |
if cond then () else raise Fail "assert" |
||
val () = assert (x = 42)</ |
val () = assert (x = 42)</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Line 1,906: | Line 1,906: | ||
For instance, if a dataset contains two variables x, y, z, one can check if x<y for all data lines for which z>0, with: |
For instance, if a dataset contains two variables x, y, z, one can check if x<y for all data lines for which z>0, with: |
||
< |
<syntaxhighlight lang=stata>assert x<y if z>0</syntaxhighlight> |
||
There is another command, '''[http://www.stata.com/help.cgi?confirm confirm]''', that can be used to check existence and type of program arguments or files. For instance, to check that the file titanium.dta exists: |
There is another command, '''[http://www.stata.com/help.cgi?confirm confirm]''', that can be used to check existence and type of program arguments or files. For instance, to check that the file titanium.dta exists: |
||
<lang |
<syntaxhighlight lang=stata>confirm file titanium.dta</syntaxhighlight> |
||
If the file does not exist, an error is thrown with return code 601. |
If the file does not exist, an error is thrown with return code 601. |
||
Line 1,916: | Line 1,916: | ||
It's also possible to use '''[http://www.stata.com/help.cgi?error error]''' to throw an error if some condition is satisfied. However, this command can only print predefined error messages: it takes the error number as an argument. For instance: |
It's also possible to use '''[http://www.stata.com/help.cgi?error error]''' to throw an error if some condition is satisfied. However, this command can only print predefined error messages: it takes the error number as an argument. For instance: |
||
< |
<syntaxhighlight lang=stata>if (`n'==42) error 3 |
||
* Will print "no dataset in use"</ |
* Will print "no dataset in use"</syntaxhighlight> |
||
To print a more sensible message, one would do instead: |
To print a more sensible message, one would do instead: |
||
< |
<syntaxhighlight lang=stata>if (`n'==42) { |
||
display as error "The correct answer is not 42." |
display as error "The correct answer is not 42." |
||
exit 54 |
exit 54 |
||
}</ |
}</syntaxhighlight> |
||
Then, if '''[http://www.stata.com/help.cgi?capture capture]''' is used to trap the error, the return code (here 54) can be retrieved in '''[http://www.stata.com/help.cgi?_variables _rc]'''. |
Then, if '''[http://www.stata.com/help.cgi?capture capture]''' is used to trap the error, the return code (here 54) can be retrieved in '''[http://www.stata.com/help.cgi?_variables _rc]'''. |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang=swift>var a = 5 |
||
//...input or change a here |
//...input or change a here |
||
assert(a == 42) // aborts program when a is not 42 |
assert(a == 42) // aborts program when a is not 42 |
||
assert(a == 42, "Error message") // aborts program |
assert(a == 42, "Error message") // aborts program |
||
// when a is not 42 with "Error message" for the message |
// when a is not 42 with "Error message" for the message |
||
// the error message must be a static string</ |
// the error message must be a static string</syntaxhighlight> |
||
In release mode assertion checks are turned off. |
In release mode assertion checks are turned off. |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{tcllib|control}} |
{{tcllib|control}} |
||
< |
<syntaxhighlight lang=tcl>package require control |
||
set x 5 |
set x 5 |
||
control::assert {$x == 42}</ |
control::assert {$x == 42}</syntaxhighlight> |
||
Produces the output: |
Produces the output: |
||
<pre>assertion failed: $x == 42</pre> |
<pre>assertion failed: $x == 42</pre> |
||
Line 1,952: | Line 1,952: | ||
{{works with|bash}} |
{{works with|bash}} |
||
Assertions are not builtin commands, but we can add a function easily. |
Assertions are not builtin commands, but we can add a function easily. |
||
< |
<syntaxhighlight lang=bash>assert() { |
||
if test ! $1; then |
if test ! $1; then |
||
[[ $2 ]] && echo "$2" >&2 |
[[ $2 ]] && echo "$2" >&2 |
||
Line 1,962: | Line 1,962: | ||
((x--)) |
((x--)) |
||
assert "$x -eq 42" "that's not the answer" |
assert "$x -eq 42" "that's not the answer" |
||
echo "won't get here"</ |
echo "won't get here"</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang=vala>int a = 42; |
||
int b = 33; |
int b = 33; |
||
assert (a == 42); |
assert (a == 42); |
||
assert (b == 42); // will break the program with "assertion failed" error</ |
assert (b == 42); // will break the program with "assertion failed" error</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang=vb>Sub test() |
||
Dim a As Integer |
Dim a As Integer |
||
a = 41 |
a = 41 |
||
Debug.Assert a = 42 |
Debug.Assert a = 42 |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
When run in the development area executing halts and highlights with yellow background the debug.assert line. |
When run in the development area executing halts and highlights with yellow background the debug.assert line. |
||
Line 1,981: | Line 1,981: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
====Definition==== |
====Definition==== |
||
< |
<syntaxhighlight lang=vb>sub Assert( boolExpr, strOnFail ) |
||
if not boolExpr then |
if not boolExpr then |
||
Err.Raise vbObjectError + 99999, , strOnFail |
Err.Raise vbObjectError + 99999, , strOnFail |
||
end if |
end if |
||
end sub |
end sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
====Invocation==== |
====Invocation==== |
||
< |
<syntaxhighlight lang=vb>dim i |
||
i = 43 |
i = 43 |
||
Assert i=42, "There's got to be more to life than this!"</ |
Assert i=42, "There's got to be more to life than this!"</syntaxhighlight> |
||
====Output==== |
====Output==== |
||
< |
<syntaxhighlight lang=VBScript>>cscript "C:\foo\assert.vbs" |
||
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!</ |
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!</syntaxhighlight> |
||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
VB's <code>Assert</code> only fires when run from within the IDE. When compiled, all <code>Debug</code> lines are ignored. |
VB's <code>Assert</code> only fires when run from within the IDE. When compiled, all <code>Debug</code> lines are ignored. |
||
< |
<syntaxhighlight lang=vb>Debug.Assert i = 42</syntaxhighlight> |
||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
Line 2,004: | Line 2,004: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Wren does not have assertions as such though we can write something similar. |
Wren does not have assertions as such though we can write something similar. |
||
< |
<syntaxhighlight lang=ecmascript>var assertEnabled = true |
||
var assert = Fn.new { |cond| |
var assert = Fn.new { |cond| |
||
Line 2,015: | Line 2,015: | ||
assert.call(x > 42) // no error |
assert.call(x > 42) // no error |
||
assertEnabled = true |
assertEnabled = true |
||
assert.call(x > 42) // error</ |
assert.call(x > 42) // error</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,028: | Line 2,028: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang=ecmascript>fn main(){ |
||
x := 43 |
x := 43 |
||
assert x == 43 // Fine |
assert x == 43 // Fine |
||
assert x > 42 // Fine |
assert x > 42 // Fine |
||
assert x == 42 // Fails |
assert x == 42 // Fails |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,055: | Line 2,055: | ||
synthesized something like this. |
synthesized something like this. |
||
< |
<syntaxhighlight lang=XPL0>proc Fatal(Str); \Display error message and terminate program |
||
char Str; |
char Str; |
||
[\return; uncomment this if "assertions" are to be disabled |
[\return; uncomment this if "assertions" are to be disabled |
||
Line 2,064: | Line 2,064: | ||
]; |
]; |
||
if X#42 then Fatal("X#42");</ |
if X#42 then Fatal("X#42");</syntaxhighlight> |
||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang=Yabasic>sub assert(a) |
||
if not a then |
if not a then |
||
error "Assertion failed" |
error "Assertion failed" |
||
Line 2,073: | Line 2,073: | ||
end sub |
end sub |
||
assert(myVar = 42)</ |
assert(myVar = 42)</syntaxhighlight> |
||
=={{header|Zig}}== |
=={{header|Zig}}== |
||
< |
<syntaxhighlight lang=zig>const assert = @import("std").debug.assert; |
||
pub fn main() void { |
pub fn main() void { |
||
assert(1 == 0); // On failure, an `unreachable` is reached |
assert(1 == 0); // On failure, an `unreachable` is reached |
||
}</ |
}</syntaxhighlight> |
||
Zig's assert gives a stack trace for debugging on failure. |
Zig's assert gives a stack trace for debugging on failure. |
||
Line 2,088: | Line 2,088: | ||
There is no hardware support for error handling, but the programmer can do this the same way they would create any other <code>if</code> statement: |
There is no hardware support for error handling, but the programmer can do this the same way they would create any other <code>if</code> statement: |
||
< |
<syntaxhighlight lang=z80>ld a,(&C005) ;load A from memory (this is an arbitrary memory location designated as the home of our variable) |
||
cp 42 |
cp 42 |
||
jp nz,ErrorHandler</ |
jp nz,ErrorHandler</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang=zkl>n:=42; (n==42) or throw(Exception.AssertionError); |
||
n=41; (n==42) or throw(Exception.AssertionError("I wanted 42!"));</ |
n=41; (n==42) or throw(Exception.AssertionError("I wanted 42!"));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,105: | Line 2,105: | ||
=={{header|zonnon}}== |
=={{header|zonnon}}== |
||
< |
<syntaxhighlight lang=zonnon> |
||
module Assertions; |
module Assertions; |
||
var |
var |
||
Line 2,113: | Line 2,113: | ||
assert(a = 42,100) |
assert(a = 42,100) |
||
end Assertions. |
end Assertions. |
||
</syntaxhighlight> |
|||
</lang> |