parser.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import sys
  2. from src.calc import Parser
  3. class TestParser(Parser):
  4. def __init__(self, **kwargs):
  5. Parser.__init__(self, **kwargs)
  6. self.input_buffer = []
  7. self.input_position = 0
  8. def run(self, input_buffer, *args, **kwargs):
  9. map(self.append, input_buffer)
  10. return Parser.run(self, *args, **kwargs)
  11. def append(self, input):
  12. self.input_buffer.append(input + '\n')
  13. def read(self, nbytes):
  14. buffer = ''
  15. try:
  16. buffer = self.input_buffer[self.input_position]
  17. if self.verbose:
  18. print 'read:', buffer
  19. except IndexError:
  20. return ''
  21. self.input_position += 1
  22. return buffer
  23. def run_expressions(expressions, keepfiles=1, fail=True, silent=False,
  24. verbose=0):
  25. """
  26. Run a list of mathematical expression through the term rewriting system and
  27. check if the output matches the expected output. The list of EXPRESSIONS
  28. consists of tuples (expression, output), where expression is the
  29. mathematical expression to evaluate (String) and output is the expected
  30. output of the evaluation (thus, the output can be Float, Int or None).
  31. If KEEPFILES is non-zero or True, the generated Flex and Bison files will
  32. be kept. Otherwise, those temporary files will be deleted. If FAIL is True,
  33. and the output of the expression is not equal to the expected output, an
  34. assertion error is raised. If SILENT is False, and an assertion error is
  35. raised, an error message is printed on stderr. If SILENT is True, no error
  36. message will be printed.
  37. If VERBOSE is non-zero and a positive integer number, verbosity of the term
  38. rewriting system will be increased. This will output debug messages and a
  39. higher value will print more types of debug messages.
  40. """
  41. parser = TestParser(keepfiles=keepfiles, verbose=verbose)
  42. for exp, out in expressions:
  43. res = None
  44. try:
  45. res = parser.run([exp])
  46. assert res == out
  47. except:
  48. if not silent:
  49. print >>sys.stderr, 'error: %s = %s, but expected: %s' \
  50. % (exp, str(res), str(out))
  51. if fail:
  52. raise