-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
438 lines (366 loc) · 13.3 KB
/
core.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
from io import StringIO
from pathlib import PurePath
from traceback import FrameSummary
from typing import Union, Literal, List, Any, Optional, Callable, Tuple, Dict, Set, Sequence, Iterable, TypedDict, TypeAlias, cast
import inspect
import json
import os
import traceback
# TODOO: currently, crashes must be reported by students for them to
# be noticed. their incentive is to get their homework in, so they'll
# probably resubmit until it does not crash. however, the goal is to
# make sure that as many crashes as possible are reported. it might be
# better to do automated crash reporting so the burden isn't on
# students AND we catch more bugs.
WHERE_THE_RESULTS_GO: str = "results/results.json"
WHERE_THE_SUBMISSION_IS: str = "submission"
OUTPUT_FORMAT: "JsonOutputFormat" = "md"
EXIT_SUCCESS: int = 0
EXIT_FAILURE: int = 1
JsonOutputFormat: TypeAlias = Union[
Literal["text"],
Literal["html"],
Literal["simple_format"],
Literal["md"],
Literal["ansi"],
]
JsonStatus: TypeAlias = Union[
Literal["passed"],
Literal["failed"],
]
JsonVisibility: TypeAlias = Union[
Literal["visible"],
Literal["hidden"],
Literal["after_due_date"],
]
JsonSummary: TypedDict = TypedDict(
"JsonSummary",
{
"score": float,
"execution_time": int,
"output": str,
"output_format": JsonOutputFormat,
"test_name_format": JsonOutputFormat,
"visibility": JsonVisibility,
"stdout_visibility": JsonVisibility,
"extra_data": Dict[str, Any],
"tests": List["JsonTestCase"],
},
total=False,
)
JsonTestCase: TypedDict = TypedDict(
"JsonTestCase",
{
"score": float,
"max_score": float,
"status": JsonStatus,
"name": str,
"name_format": str,
"number": str,
"output": str,
"output_format": JsonOutputFormat,
"tags": List[str],
"visibility": str,
"extra_data": Dict[str, Any],
},
total=False,
)
JsonMetadataAssignment: TypedDict = TypedDict(
"JsonMetadataAssignment",
{
"due_date": str,
"group_size": int,
"group_submission": bool,
"id": int,
"course_id": int,
"late_due_date": Optional[str],
"release_date": str,
"title": str,
"total_points": float,
},
)
JsonMetadataUser: TypedDict = TypedDict(
"JsonMetadataUser",
{
"email": str,
"id": int,
"name": str,
},
)
JsonMetadataPrevious: TypedDict = TypedDict(
"JsonMetadataPrevious",
{
"submission_time": str,
"score": float,
"results": "JsonMetadata",
},
)
JsonMetadata: TypedDict = TypedDict(
"JsonMetadata",
{
"id": int,
"created_at": str,
"assignment": JsonMetadataAssignment,
"submission_method": Literal["upload"] | Literal["GitHub"] | Literal["BitBucket"],
"users": List[JsonMetadataUser],
"previous_submissions": List[JsonMetadataPrevious],
},
)
class AutograderError(Exception):
msg: str
inner: Optional[Exception]
def __init__(self, exception: Optional[Exception], msg: str):
self.msg = msg
self.inner = exception
def format_traceback(payload: Exception) -> str:
def frame_predicate(filename: str) -> bool:
path = PurePath(filename)
parent_dir = os.path.basename(path.parent)
return parent_dir == WHERE_THE_SUBMISSION_IS
def filter_tb(exc: BaseException, seen: Set[int]) -> None:
if id(exc) in seen:
return
seen.add(id(exc))
tb = exc.__traceback__ # https://peps.python.org/pep-3134/
while tb is not None:
tb_info = inspect.getframeinfo(tb)
tb = tb.tb_next # https://docs.python.org/3/reference/datamodel.html#traceback.tb_next
# TODO: absolute path of student submission pulls back curtain on gradescope directory hierarchy
if frame_predicate(tb_info.filename):
break
else:
exc.__traceback__ = tb
cause = exc.__cause__
context = exc.__context__
if cause is not None:
filter_tb(cause, seen)
if context is not None:
filter_tb(context, seen)
f = StringIO("")
# don't want to print an AutograderError.
# keep getting at the inner exception.
exception: Optional[Exception] = payload
while type(exception) == AutograderError:
print(exception.msg, file=f)
exception = exception.inner
if exception is not None:
filter_tb(exception, set())
print("```text", file=f)
for line in traceback.format_exception(exception): # @fragile: signature changed slightly in 3.10
print(line, end="", file=f)
print("```", file=f)
return f.getvalue()
class Case:
# Passed to Gradescope as either "visible" or "hidden".
visible: bool
# Short description of the test. Passed to Gradescope.
name: str
# Whether this Case's failure should be permissible.
warning: bool
# `True` if the `run` method has been called and completed exactly once.
has_run: bool
# `True` if the Case has been `run` and all checks passed.
passed: Optional[bool]
def __init__(self,
visible: bool,
name: str,
warning: bool) -> None:
self.visible = visible
self.name = name
self.warning = warning
self.has_run = False
self.passed = None
def check_passed(self) -> None:
assert False, "Case.check_passed should be overridden to suit use case"
def run_post(self) -> None:
assert not self.has_run, "case should only be run once"
self.has_run = True
self.check_passed()
def run(self) -> None:
assert False, "Case.run should be overridden to suit use case (ex. CaseFunc.run)"
def format_output(self) -> str:
assert False, "Case.format_output should be overridden to suit use case"
# Summary of test cases. It is "Good" because nothing went wrong while
# loading them, eg. the submission can be tested.
class SummaryGood:
output: str
max_score: float
score: float
tests: List[JsonTestCase]
num_visible: int
num_passed_visible: int
num_scored: int
num_passed_scored: int
def __init__(self, tests: List[JsonTestCase], max_score: float) -> None:
self.output = ""
self.max_score = max_score
self.score = 0.0
self.tests = tests
self.num_visible = 0
self.num_passed_visible = 0
self.num_scored = 0
self.num_passed_scored = 0
self._format()
def all_passed(self) -> bool:
return self.num_passed_scored == self.num_scored
def _format(self) -> None:
"""Populate the summary with the results of the tests. Already called by constructor."""
hidden_failing: bool = False
for test in self.tests:
passed: bool = test["status"] == "passed"
visible: bool = test["visibility"] == "visible"
scored: bool = "score" in test
if visible:
self.num_visible += 1
if passed and visible:
self.num_passed_visible += 1
if scored:
self.num_scored += 1
if passed and scored:
self.num_passed_scored += 1
if not passed and not visible:
hidden_failing = True
all_passed: bool = self.all_passed()
assert self.num_passed_scored <= self.num_scored, "unreachable"
if all_passed:
self.output += "# All tests pass!\n"
else:
self.output += "# Some tests are failing!\n"
if hidden_failing:
self.output += "One or more hidden tests are failing.\n"
# also add a test case that indicates this for extra clarity
self.tests.append({
"name": "Hidden tests failing!",
"status": "failed",
"output": "Double-check that your submission is correctly handling all valid inputs.\n",
"output_format": OUTPUT_FORMAT,
"visibility": "visible",
})
self.output += f"{self.num_passed_visible}/{self.num_visible} visible tests passed.\n"
# compute score: all or nothing
if all_passed:
self.score = self.max_score
else:
self.score = 0.0
def get_summary(self) -> JsonSummary:
return {
"score": self.score,
"output": self.output,
"output_format": OUTPUT_FORMAT,
"stdout_visibility": "hidden", # hidden so as to not reveal hidden test cases (if they write to stdout)
"tests": self.tests,
}
def report(self, should_print_summary: bool) -> None:
summary = self.get_summary()
write_summary(summary)
if should_print_summary:
print_summary(summary)
# Summary of exceptions while loading test cases. It is "Bad" because
# the submission could not be tested, eg. something went wrong!
class SummaryBad:
output_f: StringIO
score: float
exception: AutograderError
def __init__(self, exception: AutograderError) -> None:
self.output_f = StringIO("")
self.score = 0.0
self.exception = exception
self._format()
def _format(self) -> None:
"""Populate the summary with the exception info. Already called by constructor."""
print("The student submission cannot be tested!", file=self.output_f)
print("The autograder thinks this is an issue on the student's end, but please reach out if you don't think so, or if you have questions.", file=self.output_f)
print(file=self.output_f)
print(format_traceback(self.exception), end="", file=self.output_f)
def get_summary(self) -> JsonSummary:
return {
"score": self.score,
"output": self.output_f.getvalue(),
"output_format": OUTPUT_FORMAT,
"stdout_visibility": "visible",
"tests": [],
}
def report(self, should_print_summary: bool) -> None:
summary = self.get_summary()
write_summary(summary)
if should_print_summary:
print_summary(summary)
def run_test_cases(cases: List[Case]) -> List[JsonTestCase]:
tests = []
for i, case in enumerate(cases):
passed: bool
output: str
try:
case.run() # @raise
assert case.passed is not None, "unreachable"
passed = case.passed
output = case.format_output()
except AutograderError as e:
passed = False
output = format_traceback(e)
status: JsonStatus = "passed" if passed else "failed"
test_info: JsonTestCase = {
"name": case.name,
"status": status,
"output": f"{output}",
"output_format": OUTPUT_FORMAT,
"visibility": "visible" if case.visible else "hidden",
}
if not case.warning:
max_score: float = 1.0
test_info |= {
"score": max_score if passed else 0.0,
"max_score": max_score,
}
else:
# warnings don't have scores, just pass/fail status
pass
tests.append(test_info)
return tests
def load_submission_metadata() -> JsonMetadata:
with open("submission_metadata.json", "r") as f:
s = f.read()
metadata: Dict[str, Any] = json.loads(s)
# HACK: does not check validity. not a clear way to do this in stdlib
return cast(JsonMetadata, metadata)
def write_summary(summary: JsonSummary) -> None:
with open(WHERE_THE_RESULTS_GO, "w") as f:
f.write(json.dumps(summary))
def print_summary(summary: JsonSummary) -> None:
print(f"Assignment Score: {summary['score']}")
print()
print(summary["output"])
for test in summary["tests"]:
# TODO: we're assuming that scripts don't use level 1 or 2 headings
print(f"## [{test['status'].upper()}] {test['name']}")
for line in test["output"].splitlines():
print(line)
print()
def autograder_main(get_test_cases: Callable[[JsonMetadata], List[Case]], should_print_summary: bool) -> int:
metadata = load_submission_metadata()
cases: List[Case]
try:
cases = get_test_cases(metadata) # @raise
except AutograderError as e:
# the submission can't be tested! we need to report this to the student.
summary_bad = SummaryBad(exception=e)
summary_bad.report(should_print_summary)
if should_print_summary:
return EXIT_FAILURE
else:
return EXIT_SUCCESS
# set max_score dynamically based on however many points the assignment is worth
max_score: float = float(metadata["assignment"]["total_points"])
# run the test cases!
tests: List[JsonTestCase] = run_test_cases(cases)
# how did they go?
summary = SummaryGood(tests, max_score=max_score)
# write/summarize the results!
summary.report(should_print_summary)
# the exit code should always be zero if we're running on
# Gradescope, but for local tests it's helpful as an indicator of
# failed tests.
if not summary.all_passed() and should_print_summary:
return EXIT_FAILURE
else:
return EXIT_SUCCESS