Files
agent-orchestrator-benchmark/calculators/builder-adversary-deferred/run-05/calc/test_lexer.py

83 lines
2.4 KiB
Python

import unittest
from calc.lexer import tokenize, Token, LexError
def kinds(src):
return [t.kind for t in tokenize(src)]
def tok(src):
return [(t.kind, t.value) for t in tokenize(src)]
class TestNumbers(unittest.TestCase):
def test_integer(self):
t = tokenize("42")
self.assertEqual(t[0], Token('NUMBER', 42))
self.assertIsInstance(t[0].value, int)
self.assertEqual(t[1].kind, 'EOF')
def test_float(self):
t = tokenize("3.14")
self.assertEqual(t[0], Token('NUMBER', 3.14))
self.assertIsInstance(t[0].value, float)
def test_leading_dot(self):
t = tokenize(".5")
self.assertAlmostEqual(t[0].value, 0.5)
self.assertIsInstance(t[0].value, float)
def test_trailing_dot(self):
t = tokenize("10.")
self.assertAlmostEqual(t[0].value, 10.0)
self.assertIsInstance(t[0].value, float)
class TestOperatorsAndParens(unittest.TestCase):
def test_all_operators(self):
self.assertEqual(kinds("+"), ['PLUS', 'EOF'])
self.assertEqual(kinds("-"), ['MINUS', 'EOF'])
self.assertEqual(kinds("*"), ['STAR', 'EOF'])
self.assertEqual(kinds("/"), ['SLASH', 'EOF'])
self.assertEqual(kinds("("), ['LPAREN', 'EOF'])
self.assertEqual(kinds(")"), ['RPAREN', 'EOF'])
def test_expression(self):
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
class TestWhitespaceAndErrors(unittest.TestCase):
def test_whitespace_skipped(self):
self.assertEqual(kinds(" 12 + 3 "), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_complex_expr(self):
result = tok("3.5*(1-2)")
self.assertEqual(result, [
('NUMBER', 3.5),
('STAR', '*'),
('LPAREN', '('),
('NUMBER', 1),
('MINUS', '-'),
('NUMBER', 2),
('RPAREN', ')'),
('EOF', None),
])
def test_lex_error_at_sign(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('@', str(ctx.exception))
self.assertIn('2', str(ctx.exception)) # position 2
def test_lex_error_letter(self):
with self.assertRaises(LexError):
tokenize("1 + x")
def test_lex_error_dollar(self):
with self.assertRaises(LexError):
tokenize("$")
if __name__ == '__main__':
unittest.main()