Assert now may take an optional label, like in Python

This commit is contained in:
Adrià Garriga-Alonso 2015-02-22 17:34:19 +01:00
parent 49e7376b0e
commit f7b5486b69
3 changed files with 28 additions and 9 deletions

View File

@ -163,15 +163,23 @@ other case, the first false value will be returned. Example usage:
assert
------
``assert`` is used to verify conditions while the program is running. If the
condition is not met, an ``AssertionError`` is raised. Example usage:
``assert`` is used to verify conditions while the program is
running. If the condition is not met, an :exc:`AssertionError` is
raised. ``assert`` may take one or two parameters. The first
parameter is the condition to check, and it should evaluate to either
``True`` or ``False``. The second parameter, optional, is a label for
the assert, and is the string that will be raised with the
:exc:`AssertionError`. For example:
.. code-block:: clj
(assert (= variable expected-value))
(assert (= variable expected-value))
``assert`` takes a single parameter, a conditional that evaluates to either
``True`` or ``False``.
(assert False)
; AssertionError
(assert (= 1 2) "one should equal two")
; AssertionError: one should equal two
assoc

View File

@ -1028,13 +1028,17 @@ class HyASTCompiler(object):
return ret
@builds("assert")
@checkargs(1)
@checkargs(min=1, max=2)
def compile_assert_expression(self, expr):
expr.pop(0) # assert
e = expr.pop(0)
if len(expr) == 1:
msg = self.compile(expr.pop(0)).force_expr
else:
msg = None
ret = self.compile(e)
ret += ast.Assert(test=ret.force_expr,
msg=None,
msg=msg,
lineno=e.start_line,
col_offset=e.start_column)

View File

@ -198,14 +198,21 @@ def test_ast_bad_except():
def test_ast_good_assert():
"Make sure AST can compile valid assert"
"""Make sure AST can compile valid asserts. Asserts may or may not
include a label."""
can_compile("(assert 1)")
can_compile("(assert 1 \"Assert label\")")
can_compile("(assert 1 (+ \"spam \" \"eggs\"))")
can_compile("(assert 1 12345)")
can_compile("(assert 1 nil)")
can_compile("(assert 1 (+ 2 \"incoming eggsception\"))")
def test_ast_bad_assert():
"Make sure AST can't compile invalid assert"
cant_compile("(assert)")
cant_compile("(assert 1 2)")
cant_compile("(assert 1 2 3)")
cant_compile("(assert 1 [1 2] 3)")
def test_ast_good_global():