def evaluate(self, code): log_id = output.new_log() try: try: result = timer.timed(self.timeout, eval, (code, self._frame)) except SyntaxError: timer.timed(self.timeout, exec, (code, self._frame)) result = None except RuntimeError as e: stacktrace_length = 15 stacktrace = traceback.format_exc().strip().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:])) raise interpreter.ConsoleException(e) except exceptions.Timeout as e: print( '# Error: evaluation exceeded {} seconds - check for infinite loops' .format(e.timeout)) raise interpreter.ConsoleException(e) except Exception as e: stacktrace = traceback.format_exc() token = '<string>' token_start = stacktrace.rfind(token) index = stacktrace.find('\n', token_start) + 1 stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise interpreter.ConsoleException(e) else: printed_output = ''.join(output.get_log(log_id)) return result, debug.remove_debug(printed_output) finally: output.remove_log(log_id)
def _evaluate(self, code, frame=None): if frame is None: frame = self._frame log_id = output.new_log() try: try: result = timer.timed(self.timeout, eval, (code, frame)) except SyntaxError: timer.timed(self.timeout, exec, (code, frame)) result = None except RuntimeError as e: stacktrace_length = 9 stacktrace = traceback.format_exc().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:-1])) print('# Error: maximum recursion depth exceeded.') raise PythonConsoleException(e) except exceptions.Timeout as e: print('# Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise PythonConsoleException(e) except Exception as e: stacktrace = traceback.format_exc() token = '<module>\n' index = stacktrace.rfind(token) + len(token) stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise PythonConsoleException(e) else: printed_output = ''.join(output.get_log(log_id)) return result, printed_output finally: output.remove_log(log_id)
def _run_tests(self): """Run a read-eval loop that reads from src_file and collects outputs.""" if not self._import_scheme(): return 0, 0 output.off() reader = None try: reader = TestReader(self.file_contents.split('\n')) src = self.scheme.Buffer(self.scheme.tokenize_lines(reader)) def next_line(): src.current() if reader.line_number == len(reader.lines): # No more lines in file. raise EOFError return src timer.timed(self.timeout, self.scheme.read_eval_print_loop, (next_line, self.scheme.create_global_frame())) except BaseException as e: if reader: print("Tests terminated due to unhandled exception " "after line {}:\n" "{}: {}".format(reader.line_number, e.__class__.__name__, e)) output.on() if reader: return self._summarize(reader.output, reader.expected_output) return 0, 0
def evaluate(self, code): log_id = output.new_log() try: try: result = timer.timed(self.timeout, eval, (code, self._frame)) except SyntaxError: timer.timed(self.timeout, exec, (code, self._frame)) result = None except RuntimeError as e: stacktrace_length = 15 stacktrace = traceback.format_exc().strip().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:])) raise interpreter.ConsoleException(e) except exceptions.Timeout as e: print('# Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except Exception as e: stacktrace = traceback.format_exc() token = '<string>' token_start = stacktrace.rfind(token) index = stacktrace.find('\n', token_start) + 1 stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise interpreter.ConsoleException(e) else: printed_output = ''.join(output.get_log(log_id)) return result, printed_output finally: output.remove_log(log_id)
def evaluate(self, code): if not code.strip(): # scheme.scheme_read can't handle empty strings. return None, '' log_id = output.new_log() try: exp = self.scheme.read_line(code) result = timer.timed(self.timeout, self.scheme.scheme_eval, (exp, self._frame)) except RuntimeError as e: stacktrace_length = 15 stacktrace = traceback.format_exc().strip().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:])) raise interpreter.ConsoleException(e) except exceptions.Timeout as e: print('# Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except self.scheme.SchemeError as e: print('# Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='SchemeError') except Exception as e: stacktrace = traceback.format_exc() token = '<module>\n' index = stacktrace.rfind(token) + len(token) stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise interpreter.ConsoleException(e) else: printed_output = ''.join(output.get_log(log_id)) return result, printed_output finally: output.remove_log(log_id)
def evaluate(self, code): if not code.strip(): # logic.scheme_read can't handle empty strings. return None, '' log_id = output.new_log() try: exp = self.logic.read_line(code) result = timer.timed(self.timeout, self.logic.scheme_eval, (exp, self._frame)) except RuntimeError as e: stacktrace_length = 15 stacktrace = traceback.format_exc().strip().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:])) raise interpreter.ConsoleException(e) except exceptions.Timeout as e: print('# Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except Exception as e: stacktrace = traceback.format_exc() token = '<module>\n' index = stacktrace.rfind(token) + len(token) stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) raise interpreter.ConsoleException(e) else: printed_output = ''.join(output.get_log(log_id)) return result, printed_output finally: output.remove_log(log_id)
def evaluate(self, code): if not code: return None, '' log_id = output.new_log() with self._lark_execution_guard(): result = timer.timed(self.timeout, self._parser.parse, [], dict(text=code)) printed_output = ''.join(output.get_log(log_id)) return self.normalize(result.pretty()), debug.remove_debug(printed_output)
def evaluate(self, code): if not code.strip(): return code = re.sub(r'(\A|\n)\s*--.*?\n', '', code, re.M) if code.startswith('.'): try: self.evaluate_dot(code) except interpreter.ConsoleException as e: print('Error: {}'.format(e)) raise except self.sqlite3.Error as e: print('Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='Error') return try: cursor = timer.timed(self.timeout, self._conn.execute, (code, )) except exceptions.Timeout as e: print('Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except self.sqlite3.Error as e: print('Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='Error') else: return cursor
def evaluate(self, code): if not code.strip(): return code = re.sub(r'(\A|\n)\s*--.*?\n', '', code, re.M) if code.startswith('.'): try: self.evaluate_dot(code) except interpreter.ConsoleException as e: print('Error: {}'.format(e)) raise except self.sqlite3.Error as e: print('Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='Error') return try: cursor = timer.timed(self.timeout, self._conn.execute, (code,)) except exceptions.Timeout as e: print('Error: evaluation exceeded {} seconds.'.format(e.timeout)) raise interpreter.ConsoleException(e) except self.sqlite3.Error as e: print('Error: {}'.format(e)) raise interpreter.ConsoleException(e, exception_type='Error') else: return cursor
def exec(self, expr, frame, expected=None): """Executes or evaluates a given expression in the provided frame. PARAMETERS: expr -- str; expression to be executed or evaluated. frame -- dict; frame in which expr should be evaluated. expected -- str; the expected expression, used to compare against the result of evaluating expr. If expected is not None, the function uses eval instead of exec. DESCRIPTION: If expected is None, expr is processed using the built-in exec function. If expected is a string, expr and expected will be processed using the built-in eval function, and will be tested for equality as defined by the == operator. Errors are caught and printed. Special output messages are used for RuntimeErrors (maximum recursion depth) and Timeouts. In addition, expected can be a subclass of Exception, in which case success occurs only when an instance of that exception is raised. All code execution occurs in the provided frame. Any changes to the frame (e.g. variable definitions) will be preserved. RETURNS: bool; True if an error occurred or the evaluated expression does not equal the expected value, False otherwise. """ try: if expected: expect = timer.timed(self.timeout, eval, (expected, frame.copy())) actual = timer.timed(self.timeout, eval, (expr, frame)) else: expect = None actual = timer.timed(self.timeout, exec, (expr, frame)) except RuntimeError: stacktrace_length = 9 stacktrace = traceback.format_exc().split('\n') print('Traceback (most recent call last):\n ...') print('\n'.join(stacktrace[-stacktrace_length:-1])) print('# Error: maximum recursion depth exceeded.') return True except exceptions.Timeout as e: print('# Error: evaluation exceeded {} seconds.'.format(e.timeout)) return True except Exception as e: if type(expect) == type and \ issubclass(expect, BaseException) and \ isinstance(e, expect): print(e.__class__.__name__ + ':', e) return stacktrace = traceback.format_exc() token = '<module>\n' index = stacktrace.rfind(token) + len(token) stacktrace = stacktrace[index:].rstrip('\n') if '\n' in stacktrace: print('Traceback (most recent call last):') print(stacktrace) if expected is not None: print('# Error: expected {0} got {1}'.format( repr(expect), e.__class__.__name__)) return True else: if expected: print(repr(actual)) if expected and not self.equal(expect, actual): print('# Error: expected {0} got {1}'.format( repr(expect), repr(actual))) return True else: return False
def testNoTimeout_withArgs(self): result = timer.timed(1, eval, args=('4 + 2', )) self.assertEqual(6, result)
def testNoTimeout_withKargs(self): square = lambda x: x * x result = timer.timed(1, square, kargs={'x': 3}) self.assertEqual(9, result)
def testNoTimeout_noArgs(self): test_fn = lambda: 42 result = timer.timed(1, test_fn) self.assertEqual(42, result)
def testNoTimeout_withArgs(self): result = timer.timed(1, eval, args=('4 + 2',)) self.assertEqual(6, result)