|
| 1 | +import tempfile |
| 2 | +import subprocess |
| 3 | +import os |
| 4 | +import xml.etree.ElementTree as xmlElementTree |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +STDOUT_DEV = "con" if os.name == "nt" else "/dev/stdout" |
| 8 | + |
| 9 | +__all__ = ["TestlibChecker"] |
| 10 | + |
| 11 | + |
| 12 | +class TestlibCheckerResult: |
| 13 | + |
| 14 | + def __init__(self, result: Optional[str], outcome: str, |
| 15 | + pctype: Optional[str]): |
| 16 | + self.result = result |
| 17 | + self.outcome = outcome |
| 18 | + self.pctype = pctype |
| 19 | + |
| 20 | + def __str__(self): |
| 21 | + return ' '.join([self.outcome] + |
| 22 | + ([] if self.pctype is None else [f'({self.pctype})']) + |
| 23 | + ([] if self.result is None else [self.result])) |
| 24 | + |
| 25 | + |
| 26 | +class TestlibChecker: |
| 27 | + """ |
| 28 | + A grader that uses the testlib checker. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__(self, checker_path: str): |
| 32 | + self.checker_path = checker_path |
| 33 | + |
| 34 | + def __call__(self, outs: str, ans: str, ins: str): |
| 35 | + with tempfile.NamedTemporaryFile( |
| 36 | + 'w') as inf, tempfile.NamedTemporaryFile( |
| 37 | + 'w') as outf, tempfile.NamedTemporaryFile('w') as ansf: |
| 38 | + inf.write(ins) |
| 39 | + outf.write(outs) |
| 40 | + ansf.write(ans) |
| 41 | + inf.flush() |
| 42 | + outf.flush() |
| 43 | + ansf.flush() |
| 44 | + result = subprocess.run((self.checker_path, inf.name, outf.name, |
| 45 | + ansf.name, STDOUT_DEV, '-appes'), |
| 46 | + stdout=subprocess.PIPE, |
| 47 | + stderr=subprocess.PIPE, |
| 48 | + text=True, |
| 49 | + check=False) |
| 50 | + checker_output = result.stdout |
| 51 | + |
| 52 | + result_element = xmlElementTree.fromstring(checker_output) |
| 53 | + if result_element.tag != 'result': |
| 54 | + raise ValueError("Invalid output from checker") |
| 55 | + result_text = result_element.text |
| 56 | + result_outcome = result_element.get('outcome') |
| 57 | + if result_outcome is None: |
| 58 | + raise ValueError("Invalid output from checker") |
| 59 | + result_pctype = result_element.get('pctype') |
| 60 | + return result_outcome == 'accepted', TestlibCheckerResult( |
| 61 | + result_text, result_outcome, result_pctype) |
0 commit comments