diff --git a/docs/language/api.rst b/docs/language/api.rst index 7391367..0d861de 100644 --- a/docs/language/api.rst +++ b/docs/language/api.rst @@ -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 diff --git a/hy/compiler.py b/hy/compiler.py index 23db815..e82758a 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -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) diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py index 14217db..4a63b6b 100644 --- a/tests/compilers/test_ast.py +++ b/tests/compilers/test_ast.py @@ -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():