1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
#!/usr/bin/env python
from __future__ import unicode_literals
import sys
import traceback
import os
from os.path import join
import importlib
# Local imports
from .code_evaluator import CodeEvaluator, TimeoutException
from .file_utils import copy_files, delete_files
class PythonAssertionEvaluator(CodeEvaluator):
"""Tests the Python code obtained from Code Server"""
def setup(self):
super(PythonAssertionEvaluator, self).setup()
self.exec_scope = None
self.files = []
def teardown(self):
# Delete the created file.
if self.files:
delete_files(self.files)
super(PythonAssertionEvaluator, self).teardown()
def compile_code(self, user_answer, file_paths, test_case, marks):
if file_paths:
self.files = copy_files(file_paths)
if self.exec_scope:
return None
else:
submitted = compile(user_answer, '<string>', mode='exec')
self.exec_scope = {}
exec(submitted, self.exec_scope)
return self.exec_scope
def check_code(self, user_answer, file_paths, partial_grading, test_case, marks):
success = False
test_case_marks = 0.0
try:
tb = None
_tests = compile(test_case, '<string>', mode='exec')
exec(_tests, self.exec_scope)
except AssertionError:
type, value, tb = sys.exc_info()
info = traceback.extract_tb(tb)
fname, lineno, func, text = info[-1]
text = str(test_case).splitlines()[lineno-1]
err = "{0} {1} in: {2}".format(type.__name__, str(value), text)
except Exception:
raise # Exception will be caught in CodeEvaluator.
else:
success = True
err = 'Correct answer'
test_case_marks = float(marks) if partial_grading else 0.0
del tb
return success, err, test_case_marks
|