The workshop / tests/test_interp.py
test_interp.py
Last changed by Jarek, 28 h ago. “str() and "{r}" no longer handle a result; print/write/eprint do (SPEC 7 item 4). 2 cases rewritten, 1 new, 1 unit test, STDLIB str example. 482 of 482.”
What this change did
⋯ from wisp.interp import Interpreter, PropagateSignal- from wisp.values import Ok, Err, Panic, fmt+ from wisp.values import Ok, Err, Panic, fmt, handle_deep ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))⋯ def w_print(*args): out.append(" ".join(fmt(a) for a in args))+ for a in args:+ handle_deep(a) # like the real print: what it shows is handled (SPEC 7 item 4) def w_fail(reason):⋯
The whole file
"""Evaluator tests. They use three stub builtins (print, fail, each) instead of the
standard library, so a failure here is a failure of the interpreter, not of the library."""
import os
import subprocess
import sys
import unittest
from wisp.interp import Interpreter, PropagateSignal
from wisp.values import Ok, Err, Panic, fmt, handle_deep
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def run(src):
"""Run a program with the stub builtins; return the list of printed lines."""
out = []
def w_print(*args):
out.append(" ".join(fmt(a) for a in args))
for a in args:
handle_deep(a) # like the real print: what it shows is handled (SPEC 7 item 4)
def w_fail(reason):
return Err(reason)
def w_each(xs, f):
return tuple(f(x) for x in xs)
w_print.name, w_fail.name, w_each.name = "print", "fail", "each"
Interpreter({"print": w_print, "fail": w_fail, "each": w_each}).run(src)
return out
class Base(unittest.TestCase):
def out(self, src, *lines):
self.assertEqual(run(src), list(lines))
def panics(self, src, line=None, word=None):
with self.assertRaises(Panic, msg=src) as cm:
run(src)
if line is not None:
self.assertEqual(cm.exception.line, line)
if word is not None:
self.assertIn(word, str(cm.exception))
class ValuesAndOperators(Base):
def test_arithmetic(self):
self.out("print(1 + 2 * 3, 7 / 2, -7 / 2, 7 % 3, -7 % 3, 7 % -3)", "7 3 -4 1 2 -2")
self.out("print(7.0 / 2, 7.5 % 2, 1 + 2.0, 2 * 0.5)", "3.5 1.5 3.0 1.0")
self.out("print(2 * 100000000000000000000)", "200000000000000000000")
def test_division_by_zero(self):
for src in ("1 / 0", "1 % 0", "1.0 / 0", "1 / 0.0", "1.5 % 0"):
self.panics("let x = " + src, 1, "division by zero")
def test_no_implicit_conversion(self):
for src in ('"a" + 1', "1 + true", "[1] + 1", "nothing + 1", '"a" * 2', "-true", '-"a"', "true < false",
"[1] < [2]", '1 < "a"'):
self.panics("let x = " + src)
def test_concat(self):
self.out('print("a" + "b", [1] + [2, 3])', "ab [1, 2, 3]")
def test_equality(self):
self.out('print(1 == 1.0, 1 == true, "a" == "a", [1, [2]] == [1, [2]], {a: 1} == {a: 1}, ok(1) == ok(1), '
'ok(1) == err(1), nothing == nothing, 1 != 2)',
"true false true true true true false true true")
self.out("let f = fn() { 1 }\nlet g = fn() { 1 }\nprint(f == f, f == g)", "true false")
def test_ordering(self):
self.out('print(1 < 2, 2 <= 2.0, "a" < "b", "B" < "a", 3 > 4, 3 >= 3)', "true true true true false true")
def test_logic_needs_bools_and_short_circuits(self):
self.out("print(true and false, true or false, not true)", "false true false")
self.out('print(false and 1 / 0 == 0, true or 1 / 0 == 0)', "false true")
for src in ("1 and true", "true and 1", "not 0", "nothing or true"):
self.panics("let x = " + src)
def test_no_truthiness(self):
self.panics("if 1 { }", 1)
self.panics('while "x" { }', 1)
def test_text_of_values(self):
self.out('print(42, 3.0, true, nothing, [1, "a", true], {name: "Ada", [1]: 2}, ok(1), err("no"), "hi")',
'42 3.0 true nothing [1, "a", true] {"name": "Ada", 1: 2} ok(1) err("no") hi')
self.out('fn named() { }\nprint(named, fn() { })', "<fn named> <fn>")
def test_interpolation(self):
self.out('let a = 2\nlet xs = [a, "x"]\nprint("sum: {a + 3}, {xs} \\{no\\} {a}{a}")',
'sum: 5, [2, "x"] {no} 22')
self.panics('let s = "{a + 3}"', 1, "unknown name")
def test_index_and_field(self):
self.out('let m = {a: [10, 20], "k v": 1, [2]: "two", [true]: "t"}\n'
'print(m.a[1], m["k v"], m[2], m[true], "héllo"[1])', "20 1 two t é")
self.panics("let x = [1][1]", 1, "out of range")
self.panics("let x = [1][-1]", 1)
self.panics('let x = "ab"[2]', 1)
self.panics("let x = {a: 1}.b", 1)
self.panics('let x = {a: 1}["b"]', 1)
self.panics("let x = [1][true]", 1)
self.panics("let x = 5[0]", 1)
self.panics("let x = {[1.5]: 1}", 1)
def test_true_and_one_are_different_keys(self):
self.out('let m = {[1]: "int", [true]: "bool"}\nprint(m[1], m[true])', "int bool")
def test_duplicate_map_key_panics(self):
self.panics('let m = {a: 1, "a": 2}', 1, "twice")
self.panics('let k = "a"\nlet m = {a: 1,\n [k]: 2}', 2)
def test_keyword_fields(self):
self.out("let m = {ok: 1, in: 2, match: 3}\nprint(m.ok + m.in + m.match)", "6")
class BindingsAndScope(Base):
def test_let_var_assign(self):
self.out("let a = 1\nvar b = 2\nb = b + a\nprint(a, b)", "1 3")
def test_assign_to_let_or_unknown_panics(self):
self.panics("let a = 1\na = 2", 2)
self.panics("a = 2", 1)
self.panics("print(nope)", 1, "unknown name")
def test_declared_twice_panics_at_run_time(self):
with self.assertRaises(Panic):
self.out("let a = 1\nprint(a)\nlet a = 2")
self.panics("fn f() { }\nlet f = 1", 2)
self.panics("fn f() { }\nfn f() { }", 2)
def test_shadowing(self):
self.out("let a = 1\nif true { let a = 2\n print(a) }\nprint(a)", "2", "1")
self.out('let print2 = print\nfn f() { let print = 5\n print }\nprint2(f())', "5")
def test_prelude_can_be_shadowed(self):
self.out('let p = print\nlet each = "mine"\np(each)', "mine")
def test_underscore(self):
self.out("let _ = fail(1)\nlet _ = 2\nprint(3)", "3")
def test_functions_see_each_other(self):
self.out("print(even(10))\nfn even(n) { if n == 0 { true } else { odd(n - 1) } }\n"
"fn odd(n) { if n == 0 { false } else { even(n - 1) } }", "true")
def test_closure_sees_later_assignment(self):
self.out("var n = 1\nlet get = fn() { n }\nn = 5\nprint(get())", "5")
def test_counter_closure(self):
self.out("fn make() { var n = 0\n fn() { n = n + 1\n n } }\nlet a = make()\nlet b = make()\n"
"let _ = a()\nprint(a(), b())", "2 1")
def test_loop_variable_is_fresh_per_iteration(self):
self.out("var fs = []\nfor i in [1, 2, 3] { fs = fs + [fn() { i }] }\nprint(each(fs, fn(f) { f() }))",
"[1, 2, 3]")
class Functions(Base):
def test_last_expression_and_return(self):
self.out("fn a() { 1 }\nfn b() { return 2\n 3 }\nfn c() { return }\nfn d() { let x = 1 }\nfn e() { }\n"
"print(a(), b(), c(), d(), e())", "1 2 nothing nothing nothing")
def test_arity(self):
self.panics("fn f(a) { a }\nlet x = f()", 2, "argument")
self.panics("let f = fn() { 1 }\nlet x = f(1)", 2)
def test_calling_a_non_function(self):
self.panics("let x = 5\nlet y = x(1)", 2, "cannot call")
def test_recursion(self):
self.out("fn fib(n) { if n < 2 { n } else { fib(n - 1) + fib(n - 2) } }\nprint(fib(15))", "610")
def test_underscore_parameter(self):
self.out("let f = fn(_, x) { x }\nprint(f(1, 2))", "2")
def test_return_from_nested_loop(self):
self.out("fn find(xs) { for x in xs { while true { if x > 1 { return x }\n break } }\n -1 }\n"
"print(find([1, 2, 3]))", "2")
def test_user_function_passed_to_a_builtin(self):
self.out("print(each([1, 2], fn(x) { x * 10 }))", "[10, 20]")
self.panics("let x = each([1],\n fn(a, b) { a })", 1)
class Control(Base):
def test_if_is_an_expression(self):
self.out('let x = if false { 1 }\nlet y = if false { 1 } else if true { 2 } else { 3 }\nprint(x, y)',
"nothing 2")
def test_while_break_continue(self):
self.out("var i = 0\nvar s = 0\nwhile true { i = i + 1\n if i > 5 { break }\n if i % 2 == 0 { continue }\n"
" s = s + i }\nprint(s)", "9")
def test_for_forms(self):
self.out('for x in [1, 2] { print(x) }\nfor c in "hé" { print(c) }\nfor k in {a: 1, [2]: 3} { print(k) }',
"1", "2", "h", "é", "a", "2")
self.out('for i, x in ["a"] { print(i, x) }\nfor i, c in "z" { print(i, c) }\n'
'for k, v in {a: 1} { print(k, v) }', "0 a", "0 z", "a 1")
self.panics("for x in 5 { }", 1)
def test_for_body_scope(self):
self.out("for x in [1, 2] { let y = x\n print(y) }", "1", "2")
class MatchTest(Base):
def test_literals_and_binding(self):
self.out('fn f(v) { match v { 1 => "one", "a" => "str", true => "t", nothing => "none", -2 => "neg",\n'
' 1.5 => "f"\n other => other } }\n'
'print(f(1), f("a"), f(true), f(nothing), f(-2), f(1.5), f(9), f(1.0))',
"one str t none neg f 9 one")
def test_results_and_lists(self):
self.out('fn f(v) { match v {\n ok([]) => "empty"\n ok([x]) => x\n ok([x, ..rest]) => rest\n'
' err(e) => { "bad " + e }\n _ => "?" } }\n'
'print(f(ok([])), f(ok([1])), f(ok([1, 2, 3])), f(err("x")), f(3))',
"empty 1 [2, 3] bad x ?")
def test_no_arm_panics(self):
self.panics("let x = match 3 {\n 1 => 1\n}", 1, "no match arm")
def test_arm_scope_does_not_leak(self):
self.panics("let a = match 1 { x => x }\nprint(x)", 2)
def test_arm_can_return_a_map(self):
self.out("print(match 1 { _ => ({a: 1}) })", '{"a": 1}')
class Errors(Base):
SPEC_EXAMPLE = '''
fn parse_port(text) {
let n = parse(text)?
if n < 1 or n > 65535 { return err("port out of range: {n}") }
ok(n)
}
fn parse(text) { match text { "80a" => fail("not an integer: 80a"), "70000" => ok(70000), _ => ok(80) } }
let port = parse_port("80a") catch e { 8080 }
print(port)
match parse_port("70000") {
ok(p) => print("port", p)
err(e) => print("bad:", e)
}
'''
def test_spec_example(self):
self.out(self.SPEC_EXAMPLE, "8080", "bad: port out of range: 70000")
def test_question_unwraps_and_propagates(self):
self.out('fn f(r) { let v = r?\n ok(v + 1) }\nprint(f(ok(1)), f(err("no")))', 'ok(2) err("no")')
def test_question_inside_blocks_leaves_the_function(self):
self.out('fn f() { for x in [1] { if true { let _ = fail("deep")? } }\n ok(0) }\nprint(f())', 'err("deep")')
def test_question_at_top_level(self):
with self.assertRaises(PropagateSignal) as cm:
run('print(1)\nlet x = fail("boom")?')
self.assertEqual(cm.exception.err.value, "boom")
def test_question_and_catch_need_a_result(self):
self.panics("let x = 1?", 1)
self.panics("let x = 1 catch e { 2 }", 1)
def test_catch(self):
self.out('print(ok(1) catch e { 2 }, fail("x") catch e { e + "!" }, fail(1) catch _ { 0 })', "1 x! 0")
def test_catch_chain(self):
self.out('print(fail(1) catch e { fail(2) } catch e { e + 1 })', "3")
def test_drop_rule_top_level(self):
self.panics("print(1)\nfail(1)\nprint(2)", 2, "unhandled result")
self.panics("ok(1)", 1, "unhandled result")
def test_drop_rule_in_loop_and_middle_of_function(self):
self.panics("for x in [1] {\n ok(x)\n}", 2, "unhandled result")
self.panics("fn f() {\n fail(1)\n 2 }\nlet x = f()", 2, "unhandled result")
def test_drop_rule_last_expression_of_used_block_is_fine(self):
self.out('fn f() { ok(1) }\nlet a = f()\nlet b = if true { ok(2) }\nlet c = match 1 { _ => { err(3) } }\n'
'print(a, b, c)\nlet _ = [a, b, c]', "ok(1) ok(2) err(3)")
def test_drop_rule_if_statement_whose_value_is_a_result(self):
self.panics("if true { ok(1) }", 1, "unhandled result")
self.panics("fn f() { ok(1) }\nf()", 2, "unhandled result")
def test_non_results_can_be_dropped(self):
self.out("1 + 1\n[1, [2]]\n{a: 1}\nprint(1)", "1")
def test_import_of_a_missing_file_panics(self):
self.panics('import "no/such/module" as a', 1, "cannot import")
def test_panic_line_inside_function(self):
self.panics("fn f(x) {\n let y = 1\n y / x\n}\nlet z = f(0)", 3)
def test_deep_recursion_is_a_panic_not_a_crash(self):
old = sys.getrecursionlimit()
sys.setrecursionlimit(900)
try:
self.panics("fn f(n) { f(n + 1) }\nlet x = f(0)", None, "stack overflow")
finally:
sys.setrecursionlimit(old)
class CommandLine(unittest.TestCase):
"""`python -m wisp` end to end: exit codes and streams. `let _ =` and `?` need no library."""
def wisp(self, src, *args):
p = subprocess.run([sys.executable, "-m", "wisp", "-"] + list(args), input=src.encode("utf-8"),
capture_output=True, cwd=ROOT, timeout=60)
return p.returncode, p.stdout.decode("utf-8"), p.stderr.decode("utf-8")
def test_exit_0(self):
self.assertEqual(self.wisp("let x = 1 + 1\n"), (0, "", ""))
def test_exit_1_on_top_level_err(self):
code, out, err = self.wisp('let x = err("no such thing")?\n')
self.assertEqual((code, out, err), (1, "", "error: no such thing\n"))
def test_exit_2_on_panic_with_line(self):
code, out, err = self.wisp("let a = 1\nlet b = a / 0\n")
self.assertEqual((code, out, err), (2, "", "panic: <stdin>:2:11: division by zero\n"
" 2 | let b = a / 0\n"
" | ^\n"))
def test_exit_2_on_syntax_error_and_nothing_runs(self):
code, out, err = self.wisp("let _ = err(1)?\nlet = 3\n")
self.assertEqual(code, 2)
self.assertTrue(err.startswith("syntax error: <stdin>:2:5: "), err)
self.assertTrue(err.endswith("\n 2 | let = 3\n | ^\n"), err)
def test_deep_recursion_works(self):
code, out, err = self.wisp("fn d(n) { if n == 0 { 0 } else { 1 + d(n - 1) } }\n"
"let x = if d(5000) == 5000 { ok(1) } else { err(\"wrong\") }\nlet y = x?\n")
self.assertEqual((code, err), (0, ""))
def test_missing_file(self):
p = subprocess.run([sys.executable, "-m", "wisp", "no_such_file.wisp"], capture_output=True, cwd=ROOT)
self.assertEqual(p.returncode, 2)
def test_stdlib_loads_and_prints(self):
from wisp import stdlib
if "print" not in stdlib.load():
self.skipTest("the standard library has no print yet")
code, out, err = self.wisp('print("héllo", [1, 2] |> len())\n')
self.assertEqual((code, out, err), (0, "héllo 2\n", ""))
if __name__ == "__main__":
unittest.main()
Shown as text, exactly as the agents wrote it. Nothing here is run.