74 lines
3.0 KiB
Python
74 lines
3.0 KiB
Python
|
|
import os
|
|
from ..models.function import FunctionResponse, FunctionStatus
|
|
def judge(filepath:str, name: str, course_id: str, lesson_name: str, root_path:str):
|
|
"""Call this method to judge the student's solution after they have completed the problem.
|
|
|
|
Args:
|
|
filepath (`str`): The path to the file containing the student's solution.
|
|
name (`str`): The name of the problem.
|
|
course_id (`str`): The id of the course.
|
|
lesson_name (`str`): The name of the lesson.
|
|
root_path (`str`): The root path of the user's workspace project.
|
|
|
|
Returns:
|
|
Report `tuple(int,str)`: The report of the student's solution.
|
|
"""
|
|
# 从books/code_tests/name/中获取所有.in文件
|
|
|
|
directory = 'books/code_tests/'+course_id+'/'+name
|
|
# 如果目录不存在,报错
|
|
if not os.path.exists(directory):
|
|
status = FunctionStatus.FAILED
|
|
return FunctionResponse("judge", status, f"The name {name} is not found.")
|
|
files = os.listdir(directory)
|
|
in_files = [file for file in files if file.endswith('.in')]
|
|
save_dir = root_path
|
|
Report = ""
|
|
passed_num=0
|
|
failed_num=0
|
|
erroroutput = ""
|
|
exceptoutput=""
|
|
for file in in_files:
|
|
file_path = os.path.join(save_dir, f"_{name}.out")
|
|
if os.path.exists(file_path):
|
|
os.remove(file_path)
|
|
with open(file_path, 'w') as ff:
|
|
ff.write("")
|
|
|
|
cmd = "cat " + os.path.join(directory, file) + " | " + "python " + os.path.join(root_path, filepath) +" > " + os.path.join(save_dir, f"_{name}.out")
|
|
os.system(cmd)
|
|
# 比较结果
|
|
re = ""
|
|
if compare_file(os.path.join(save_dir, f"_{name}.out"), os.path.join(directory, file.replace(".in", ".out"))):
|
|
re = f"Passed {file}"
|
|
passed_num += 1
|
|
else:
|
|
re = f"Failed {file}"
|
|
failed_num += 1
|
|
with open(os.path.join(directory, file.replace(".in", ".out")),'r') as f: exceptoutput = f.read()
|
|
with open(os.path.join(save_dir, f"_{name}.out"),'r') as f: erroroutput = f.read()
|
|
Report = Report + re + "\n"
|
|
os.remove(os.path.join(save_dir, f"_{name}.out"))
|
|
score = int (100 * passed_num / (passed_num + failed_num))
|
|
|
|
|
|
|
|
status = FunctionStatus.SUCCESS
|
|
return FunctionResponse("judge", status, f"评测得分为 {score}, 在 {passed_num + failed_num} 个测试用例中通过了 {passed_num}个。最后一个错误样例期望输出:'{exceptoutput}',但你的输出:'{erroroutput}")
|
|
|
|
|
|
def compare_file(path1:str, path2:str):
|
|
"""
|
|
Compare two files and return true if they are the same.
|
|
"""
|
|
with open(path1, 'r') as f1, open(path2, 'r') as f2:
|
|
# 逐行比较
|
|
print('-------------------COMPARE-------------------------')
|
|
for line1, line2 in zip(f1, f2):
|
|
print(line1.strip(), "||",line2.strip())
|
|
if line1.strip() != line2.strip():
|
|
return False
|
|
return True
|
|
|
|
judge_tools = [judge] |