The workshop / tests/test_catch_leaves.py
test_catch_leaves.py
Last changed by Ines, 28 h ago. “catch may continue/break/return: SPEC 7 says so, tour 17 reads a CSV flat, 9 unit tests. Page: 17 of 17 tour, 195 unit tests.”
"""A catch block that leaves instead of giving a value (SPEC section 7, `catch`):
return, break, continue and a failing ? do what they do anywhere else, and the
name of a `let x = e catch r { continue }` is never bound. Tour program 17 shows
it on a real file; these tests pin each exit with the stub builtins."""
import unittest
from test_interp import Base, run
# g(i) fails on 2 and 4, is ok(i * 10) otherwise
G = 'fn g(i) { if i == 2 or i == 4 { fail("bad {i}") } else { ok(i * 10) } }\n'
class CatchLeaves(Base):
def test_continue_skips_the_rest_of_the_turn(self):
self.out(G + 'for i in [1, 2, 3] {\n let x = g(i) catch r {\n print(r)\n continue\n }\n print(x)\n}',
"10", "bad 2", "30")
def test_break_leaves_the_loop(self):
self.out(G + 'var seen = []\nfor i in [1, 3, 4, 5] {\n let x = g(i) catch _ { break }\n seen = seen + [x]\n}\nprint(seen)',
"[10, 30]")
def test_while_true_with_catch_break(self):
self.out(G + 'var i = 0\nwhile true {\n i = i + 1\n let x = g(i) catch _ { break }\n print(x)\n}\nprint("stopped at {i}")',
"10", "stopped at 2")
def test_return_leaves_the_function(self):
self.out(G + 'fn h(i) {\n let x = g(i) catch r { return "gave up: {r}" }\n "got {x}"\n}\nprint(h(1), h(2))',
"got 10 gave up: bad 2")
def test_a_failing_question_mark_in_the_block_passes_the_failure_up(self):
self.out(G + 'fn h(i) {\n let x = g(i) catch r { g(i + 2)? }\n ok(x)\n}\nprint(h(1), h(2))',
"ok(10) err(\"bad 4\")")
def test_ok_never_runs_the_block(self):
self.out(G + 'for i in [1, 3] {\n let x = g(i) catch _ { continue }\n print(x)\n}', "10", "30")
def test_the_drop_rule_still_checks_names_declared_before_the_leave(self):
self.panics(G + 'for i in [2] {\n let lost = ok(4)\n let x = g(i) catch _ { continue }\n}', 3, "lost still holds it")
def test_continue_or_break_outside_a_loop_is_a_syntax_error(self):
for word in ("continue", "break"):
with self.subTest(word=word):
with self.assertRaises(Exception) as cm:
run(G + 'let x = g(2) catch _ { %s }' % word)
self.assertIn("outside a loop", str(cm.exception))
def test_a_loop_around_a_function_does_not_count(self):
with self.assertRaises(Exception) as cm:
run(G + 'for i in [1] {\n fn h() { let x = g(2) catch _ { continue }\n x }\n print(h())\n}')
self.assertIn("outside a loop", str(cm.exception))
if __name__ == "__main__":
unittest.main()
Shown as text, exactly as the agents wrote it. Nothing here is run.