def test_parse_raises_error_on_invalid_expression(): """ Test that attempting to parse an invalid expression allows a ``CalcError`` to propagate correctly. """ input_text = "+1" calc = Calc(text=input_text) with pytest.raises(CalcError): calc.parse()
def test_parse_sets_eof(): """ Test that successfully parsing an arithmetic expression sets the ``current_token`` attribute of a :class:`Calc` to EOF. """ input_text = "1+1" calc = Calc(text=input_text) calc.parse() assert calc.current_token.type == EOF
def test_calc_raises_error_on_invalid_tokens(): """ Test that invalid tokens cause a ``CalcError`` and that the exception stack trace contains useful information. """ input_text = "lumberjack" # Now with 100% more Monty Python references. calc = Calc(text=input_text) with pytest.raises(CalcError) as err: calc.parse() assert "Invalid token at position 0" in str(err.value)
def test_calc_raises_error_on_unexepected_syntax(): """ Test that unexpected syntax causes a ``CalcError`` and that the exception stack trace contains useful information. """ input_text = "+" calc = Calc(text=input_text) with pytest.raises(CalcError) as err: calc.parse() assert "Expected INTEGER at position 1, found PLUS" in str(err.value)
def main(): """ The main entry point into the ``calc`` program. This function takes input from the user, attempts to parse it, and either returns the result or shows a stack trace to make it easier to identify the root cause of the error. Args: None Returns: None """ while True: # Attempt to get user input. try: text = input('calc> ') except EOFError: # Allow the user to use ctrl+d to exit the calculator. break if not text: continue calc = Calc(text) try: result = calc.parse() except CalcError: traceback.print_exc() # Show a stack trace on errors. else: print(result)
def test_parse_supports_addition(): """Test that a :class:`Calc` can correctly parse the addition operation.""" # Note: This function name was briefly duplicated and therefore didn't run. input_text = "1+1" calc = Calc(text=input_text) assert calc.parse() == 2