84 lines
2.6 KiB
Python
84 lines
2.6 KiB
Python
import unittest
|
|
from calc.lexer import tokenize, Token, LexError
|
|
|
|
|
|
def kinds(src):
|
|
return [t.kind for t in tokenize(src)]
|
|
|
|
|
|
def pairs(src):
|
|
return [(t.kind, t.value) for t in tokenize(src)]
|
|
|
|
|
|
class TestNumbers(unittest.TestCase):
|
|
def test_integer(self):
|
|
toks = tokenize("42")
|
|
self.assertEqual(len(toks), 2)
|
|
self.assertEqual(toks[0], Token('NUMBER', 42))
|
|
self.assertIsInstance(toks[0].value, int)
|
|
self.assertEqual(toks[1].kind, 'EOF')
|
|
|
|
def test_float(self):
|
|
toks = tokenize("3.14")
|
|
self.assertEqual(toks[0], Token('NUMBER', 3.14))
|
|
self.assertIsInstance(toks[0].value, float)
|
|
|
|
def test_leading_dot(self):
|
|
toks = tokenize(".5")
|
|
self.assertEqual(toks[0], Token('NUMBER', 0.5))
|
|
self.assertIsInstance(toks[0].value, float)
|
|
|
|
def test_trailing_dot(self):
|
|
toks = tokenize("10.")
|
|
self.assertEqual(toks[0], Token('NUMBER', 10.0))
|
|
self.assertIsInstance(toks[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'])
|
|
|
|
def test_complex_expression(self):
|
|
self.assertEqual(kinds("3.5*(1-2)"),
|
|
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
|
|
|
|
|
|
class TestWhitespaceAndErrors(unittest.TestCase):
|
|
def test_spaces_skipped(self):
|
|
self.assertEqual(kinds(" 12 + 3 "),
|
|
['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
|
|
|
def test_tabs_skipped(self):
|
|
self.assertEqual(kinds("1\t+\t2"), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
|
|
|
def test_lex_error_at(self):
|
|
with self.assertRaises(LexError) as ctx:
|
|
tokenize("1 @ 2")
|
|
self.assertIn('@', str(ctx.exception))
|
|
|
|
def test_lex_error_dollar(self):
|
|
with self.assertRaises(LexError):
|
|
tokenize("$")
|
|
|
|
def test_lex_error_letter(self):
|
|
with self.assertRaises(LexError):
|
|
tokenize("abc")
|
|
|
|
def test_lex_error_position(self):
|
|
with self.assertRaises(LexError) as ctx:
|
|
tokenize("1 @ 2")
|
|
self.assertIn('2', str(ctx.exception))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|