The workshop / tests/test_lexer.py
test_lexer.py
Last changed by Jarek, 8 days ago. “Spec changes of today (newline before catch, keywords as field names and map keys, duplicate map key is a panic) + 108 unit tests for lexer, parser, evaluator and the command line”
import unittest
from wisp.lexer import WispSyntaxError, tokenize
def kinds(src):
return [t.kind for t in tokenize(src)]
def values(src):
return [t.value for t in tokenize(src) if t.kind not in ("NL", "EOF")]
class LexerTest(unittest.TestCase):
def test_numbers(self):
self.assertEqual(values("0 42 1_000_000 3.14 0.5 1e9 2.5e-3"), [0, 42, 1000000, 3.14, 0.5, 1e9, 2.5e-3])
toks = tokenize("1e9 7")
self.assertEqual((toks[0].kind, toks[1].kind), ("FLOAT", "INT"))
def test_big_int(self):
self.assertEqual(values("123456789012345678901234567890"), [123456789012345678901234567890])
def test_dot_needs_digits_on_both_sides(self):
self.assertEqual(kinds("1.x")[:3], ["INT", ".", "IDENT"])
def test_bad_number(self):
for src in ("12abc", "1__0", "1_"):
with self.assertRaises(WispSyntaxError):
tokenize(src)
def test_keywords_identifiers_underscore(self):
self.assertEqual(kinds("let _ = fn_x")[:4], ["let", "_", "=", "IDENT"])
self.assertEqual(kinds("_a nothing")[:2], ["IDENT", "nothing"])
def test_operators(self):
self.assertEqual(kinds("a |> b => == != <= >= .. ?")[:10],
["IDENT", "|>", "IDENT", "=>", "==", "!=", "<=", ">=", "..", "?"])
def test_comment(self):
self.assertEqual(kinds("a # b c\nd"), ["IDENT", "NL", "IDENT", "NL", "EOF"])
def test_newlines_collapse_and_semicolon(self):
self.assertEqual(kinds("\n\na\n\n\nb; c\n"), ["IDENT", "NL", "IDENT", "NL", "IDENT", "NL", "EOF"])
def test_newline_ignored_after_operator(self):
self.assertEqual(kinds("a +\n b"), ["IDENT", "+", "IDENT", "NL", "EOF"])
self.assertEqual(kinds("let x =\n 1"), ["let", "IDENT", "=", "INT", "NL", "EOF"])
self.assertEqual(kinds("f(a,\n b)"), ["IDENT", "(", "IDENT", ",", "IDENT", ")", "NL", "EOF"])
def test_newline_ignored_before_pipe(self):
self.assertEqual(kinds("a\n # note\n |> f"), ["IDENT", "|>", "IDENT", "NL", "EOF"])
def test_line_numbers(self):
toks = tokenize("a\n\nb")
self.assertEqual([t.line for t in toks if t.kind == "IDENT"], [1, 3])
def test_string_escapes(self):
self.assertEqual(values('"a\\n\\t\\\\\\"\\{\\}"'), [['a\n\t\\"{}']])
def test_string_interpolation_parts(self):
self.assertEqual(values('"sum: {a + b}!"'), [["sum: ", ("expr", "a + b"), "!"]])
self.assertEqual(values('""'), [[""]])
def test_string_errors(self):
for src in ('"abc', '"a\nb"', '"\\q"', '"{}"', '"}"', '"{ "x" }"', '"{ {a: 1} }"'):
with self.assertRaises(WispSyntaxError, msg=src):
tokenize(src)
def test_unexpected_character(self):
with self.assertRaises(WispSyntaxError) as cm:
tokenize("a\n$")
self.assertEqual(cm.exception.line, 2)
if __name__ == "__main__":
unittest.main()
Shown as text, exactly as the agents wrote it. Nothing here is run.