test_calc.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import sys
  2. import unittest
  3. from src.calc import Parser
  4. class TestParser(Parser):
  5. def __init__(self, input_buffer, **kwargs):
  6. Parser.__init__(self, **kwargs)
  7. self.input_buffer = []
  8. self.input_position = 0
  9. map(self.append, input_buffer)
  10. def append(self, input):
  11. self.input_buffer.append(input + '\n')
  12. def read(self, nbytes):
  13. buffer = ''
  14. try:
  15. buffer = self.input_buffer[self.input_position]
  16. except IndexError:
  17. return ''
  18. self.input_position += 1
  19. return buffer
  20. class TestCalc(unittest.TestCase):
  21. def setUp(self):
  22. pass
  23. def tearDown(self):
  24. pass
  25. def run_expressions(self, expressions, fail=True):
  26. for exp, out in expressions:
  27. try:
  28. res = TestParser([exp], keepfiles=1).run()
  29. assert res == out
  30. except:
  31. print >>sys.stderr, 'error: %s = %s, but expected: %s' \
  32. % (exp, str(res), str(out))
  33. if fail:
  34. raise
  35. def test_constructor(self):
  36. assert TestParser(['1+4'], keepfiles=1).run() == 5.0
  37. def test_basic_on_exp(self):
  38. expressions = [('4', 4.0),
  39. ('3+4', 7.0),
  40. ('3-4', -1.0),
  41. ('3/4', .75),
  42. ('-4', -4.0),
  43. ('3^4', 81.0),
  44. ('(4)', 4.0)]
  45. self.run_expressions(expressions)
  46. def test_infinity(self):
  47. expressions = [('2^9999', None),
  48. ('2^-9999', 0.0),
  49. ('2^99999999999', None),
  50. ('2^-99999999999', 0.0)]
  51. self.run_expressions(expressions, fail=False)