mogs 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mogs/__init__.py +17 -0
- mogs/_assertrewrite.py +44 -0
- mogs/_env.py +26 -0
- mogs/_run.py +111 -0
- mogs/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
- mogs/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
- mogs/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
- mogs/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
- mogs/_typst/preview/mitex/0.2.7/LICENSE +176 -0
- mogs/_typst/preview/mitex/0.2.7/lib.typ +1 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
- mogs/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
- mogs/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
- mogs/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
- mogs/_typst/preview/mitex/0.2.7/typst.toml +12 -0
- mogs/assignment.py +172 -0
- mogs/build.py +605 -0
- mogs/check.py +410 -0
- mogs/cli.py +272 -0
- mogs/config.py +619 -0
- mogs/environment.py +118 -0
- mogs/export.py +556 -0
- mogs/grader/__init__.py +1 -0
- mogs/grader/_process.py +383 -0
- mogs/grader/_user.py +7 -0
- mogs/grader/bundle.py +320 -0
- mogs/grader/child.py +317 -0
- mogs/grader/datafiles.py +54 -0
- mogs/grader/main.py +132 -0
- mogs/grader/protocol.py +175 -0
- mogs/grader/results.py +337 -0
- mogs/grader/sandbox.py +462 -0
- mogs/grader/templates/__init__.py +38 -0
- mogs/grader/templates/run_autograder +3 -0
- mogs/grader/templates/setup.sh +28 -0
- mogs/loader.py +260 -0
- mogs/pdf.py +676 -0
- mogs/regrade.py +223 -0
- mogs/requirements.py +232 -0
- mogs/runner.py +281 -0
- mogs/scaffold.py +155 -0
- mogs/selfcheck.py +173 -0
- mogs/source.py +1438 -0
- mogs/transform.py +769 -0
- mogs-0.7.0.dist-info/METADATA +17 -0
- mogs-0.7.0.dist-info/RECORD +49 -0
- mogs-0.7.0.dist-info/WHEEL +4 -0
- mogs-0.7.0.dist-info/entry_points.txt +3 -0
mogs/runner.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Run test functions and record outcomes with short failure messages.
|
|
2
|
+
|
|
3
|
+
The notebook `check()` panel and the Gradescope grader share this runner.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import linecache
|
|
7
|
+
import textwrap
|
|
8
|
+
import time
|
|
9
|
+
import traceback
|
|
10
|
+
from collections.abc import Callable, Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from enum import StrEnum
|
|
13
|
+
from typing import Self
|
|
14
|
+
|
|
15
|
+
MAX_LINES = 25
|
|
16
|
+
MAX_BYTES = 4096
|
|
17
|
+
MAX_STATEMENT_LINES = 5
|
|
18
|
+
MAX_SOURCE_WIDTH = 200
|
|
19
|
+
TRUNCATED = "... (truncated)"
|
|
20
|
+
UNAVAILABLE = "<failure details unavailable>"
|
|
21
|
+
|
|
22
|
+
type TestFunction = Callable[[], object]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class FailureReason(StrEnum):
|
|
26
|
+
"""Why a test did not pass."""
|
|
27
|
+
|
|
28
|
+
ASSERTION = "assertion"
|
|
29
|
+
ERROR = "error"
|
|
30
|
+
TIMEOUT = "timeout"
|
|
31
|
+
KILLED = "killed"
|
|
32
|
+
OUT_OF_MEMORY = "out_of_memory"
|
|
33
|
+
BUDGET = "budget"
|
|
34
|
+
LOAD_FAILED = "load_failed"
|
|
35
|
+
NOT_RUN = "not_run"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True)
|
|
39
|
+
class Outcome:
|
|
40
|
+
"""Result of one test.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
name: Test name.
|
|
44
|
+
passed: Whether the test passed.
|
|
45
|
+
message: Failure message, empty when passed.
|
|
46
|
+
reason: Why the test failed, `None` when passed.
|
|
47
|
+
seconds: Wall time spent in the test.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
name: str
|
|
51
|
+
passed: bool
|
|
52
|
+
message: str = ""
|
|
53
|
+
reason: FailureReason | None = None
|
|
54
|
+
seconds: float = 0.0
|
|
55
|
+
|
|
56
|
+
def to_dict(self) -> dict[str, object]:
|
|
57
|
+
"""JSON-ready fields; `reason` becomes its string value."""
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
"name": self.name,
|
|
61
|
+
"passed": self.passed,
|
|
62
|
+
"message": self.message,
|
|
63
|
+
"reason": None if self.reason is None else self.reason.value,
|
|
64
|
+
"seconds": self.seconds,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_dict(cls, data: object) -> Self:
|
|
69
|
+
"""Inverse of `to_dict`.
|
|
70
|
+
|
|
71
|
+
Raises:
|
|
72
|
+
ValueError: If a field is missing or has the wrong type, or `reason` is unknown.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
match data:
|
|
76
|
+
case {
|
|
77
|
+
"name": str() as name,
|
|
78
|
+
"passed": bool() as passed,
|
|
79
|
+
"message": str() as message,
|
|
80
|
+
"reason": None | str() as reason,
|
|
81
|
+
"seconds": int() | float() as seconds,
|
|
82
|
+
} if not isinstance(seconds, bool):
|
|
83
|
+
kind = None if reason is None else FailureReason(reason)
|
|
84
|
+
return cls(name, passed, message, kind, float(seconds))
|
|
85
|
+
|
|
86
|
+
raise ValueError(f"not an outcome: {data!r}")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def run_test(name: str, fn: TestFunction) -> Outcome:
|
|
90
|
+
"""Call one test function and record its outcome.
|
|
91
|
+
|
|
92
|
+
Never raises: every `BaseException`, including `SystemExit` and `KeyboardInterrupt`, becomes
|
|
93
|
+
a failed outcome. `AssertionError` gives `ASSERTION`, `MemoryError` gives `OUT_OF_MEMORY`,
|
|
94
|
+
anything else gives `ERROR`.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
name: Test name for the outcome.
|
|
98
|
+
fn: The test, called without arguments.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
The outcome.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
start = time.perf_counter()
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
fn()
|
|
108
|
+
except BaseException as exc:
|
|
109
|
+
seconds = time.perf_counter() - start
|
|
110
|
+
|
|
111
|
+
# A hostile exception can break any step of describing it.
|
|
112
|
+
try:
|
|
113
|
+
return Outcome(name, False, failure_message(exc), failure_reason(exc), seconds)
|
|
114
|
+
except BaseException:
|
|
115
|
+
return Outcome(name, False, UNAVAILABLE, FailureReason.ERROR, seconds)
|
|
116
|
+
|
|
117
|
+
return Outcome(name, True, seconds=time.perf_counter() - start)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def failure_reason(exc: BaseException) -> FailureReason:
|
|
121
|
+
"""Classify an exception raised by a test."""
|
|
122
|
+
|
|
123
|
+
# `type()` and `issubclass` ignore an instance's own `__class__` attribute.
|
|
124
|
+
kind = type(exc)
|
|
125
|
+
|
|
126
|
+
if issubclass(kind, AssertionError):
|
|
127
|
+
return FailureReason.ASSERTION
|
|
128
|
+
|
|
129
|
+
if issubclass(kind, MemoryError):
|
|
130
|
+
return FailureReason.OUT_OF_MEMORY
|
|
131
|
+
|
|
132
|
+
return FailureReason.ERROR
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def failure_message(exc: BaseException) -> str:
|
|
136
|
+
"""Describe a test failure in at most `MAX_LINES` lines and `MAX_BYTES` bytes.
|
|
137
|
+
|
|
138
|
+
The message has the failing statement in the test function, then, when the error came from
|
|
139
|
+
deeper code, the statement there, then `ExcType: message`.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
summary = exception_summary(exc)
|
|
143
|
+
|
|
144
|
+
try:
|
|
145
|
+
location = failure_location(exc)
|
|
146
|
+
except BaseException:
|
|
147
|
+
location = []
|
|
148
|
+
|
|
149
|
+
return cap("\n".join([*location, summary]))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def failure_location(exc: BaseException) -> list[str]:
|
|
153
|
+
"""Lines naming the failing statement in the test and, if different, the innermost one."""
|
|
154
|
+
|
|
155
|
+
# The first traceback entry is `run_test` itself; the next is the test function.
|
|
156
|
+
tb = exc.__traceback__
|
|
157
|
+
tb = tb.tb_next if tb is not None else None
|
|
158
|
+
|
|
159
|
+
# Frames that set `__tracebackhide__`, as pytest does, only raise a readable error.
|
|
160
|
+
frames = [
|
|
161
|
+
summary
|
|
162
|
+
for (frame, _), summary in zip(traceback.walk_tb(tb), traceback.extract_tb(tb), strict=True)
|
|
163
|
+
if not frame.f_locals.get("__tracebackhide__")
|
|
164
|
+
]
|
|
165
|
+
|
|
166
|
+
if not frames:
|
|
167
|
+
return []
|
|
168
|
+
|
|
169
|
+
first, last, depth = frames[0], frames[-1], len(frames)
|
|
170
|
+
|
|
171
|
+
lines = frame_lines(first)
|
|
172
|
+
|
|
173
|
+
if depth > 1:
|
|
174
|
+
lines += ["..."] if depth > 2 else []
|
|
175
|
+
lines += frame_lines(last)
|
|
176
|
+
|
|
177
|
+
return lines
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def frame_lines(frame: traceback.FrameSummary) -> list[str]:
|
|
181
|
+
"""The header and statement lines for one traceback entry."""
|
|
182
|
+
|
|
183
|
+
header = f"In {frame.name}, line {frame.lineno}:"
|
|
184
|
+
|
|
185
|
+
if frame.lineno is None:
|
|
186
|
+
return [header]
|
|
187
|
+
|
|
188
|
+
end = frame.end_lineno or frame.lineno
|
|
189
|
+
end = min(end, frame.lineno + MAX_STATEMENT_LINES - 1)
|
|
190
|
+
statement = "".join(linecache.getline(frame.filename, n) for n in range(frame.lineno, end + 1))
|
|
191
|
+
|
|
192
|
+
if not statement.strip():
|
|
193
|
+
return [header]
|
|
194
|
+
|
|
195
|
+
# Short lines keep the exception summary inside the byte cap.
|
|
196
|
+
source = textwrap.dedent(statement).rstrip().splitlines()
|
|
197
|
+
|
|
198
|
+
return [header, *(f" {shorten(line)}" for line in source)]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def shorten(line: str) -> str:
|
|
202
|
+
"""Cut a source line to `MAX_SOURCE_WIDTH` characters."""
|
|
203
|
+
|
|
204
|
+
return line if len(line) <= MAX_SOURCE_WIDTH else line[: MAX_SOURCE_WIDTH - 3] + "..."
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def exception_summary(exc: BaseException) -> str:
|
|
208
|
+
"""`ExcType: message`, or `ExcType` alone when the message is empty."""
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
kind = str.__str__(type(exc).__name__)
|
|
212
|
+
except BaseException:
|
|
213
|
+
kind = "<unnamed exception>"
|
|
214
|
+
|
|
215
|
+
try:
|
|
216
|
+
# `__str__` may return a `str` subclass; make it a plain `str`.
|
|
217
|
+
text = str.__str__(str(exc))
|
|
218
|
+
except BaseException:
|
|
219
|
+
return f"{kind}: <str() of the exception failed>"
|
|
220
|
+
|
|
221
|
+
return f"{kind}: {text}" if text else kind
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def cap(message: str) -> str:
|
|
225
|
+
"""Cut a message to `MAX_LINES` lines and `MAX_BYTES` UTF-8 bytes.
|
|
226
|
+
|
|
227
|
+
Characters UTF-8 cannot encode, such as lone surrogates, become `?`.
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
data = message.encode(errors="replace")
|
|
231
|
+
message = data.decode()
|
|
232
|
+
|
|
233
|
+
if len(message.splitlines()) <= MAX_LINES and len(data) <= MAX_BYTES:
|
|
234
|
+
return message
|
|
235
|
+
|
|
236
|
+
# Keep a prefix that leaves room for the marker line in both limits.
|
|
237
|
+
room = MAX_BYTES - len(TRUNCATED.encode()) - 1
|
|
238
|
+
head = data[:room].decode(errors="ignore").splitlines()[: MAX_LINES - 1]
|
|
239
|
+
|
|
240
|
+
return "\n".join([*head, TRUNCATED])
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def run_test_source(
|
|
244
|
+
source: str, filename: str, names: Sequence[str], namespace: dict[str, object]
|
|
245
|
+
) -> list[Outcome]:
|
|
246
|
+
"""Run test source as a module in `namespace`, then each test it defines in `names`.
|
|
247
|
+
|
|
248
|
+
The source is compiled with assertion rewriting, so failed asserts show their values. When
|
|
249
|
+
it raises while loading, `SystemExit` included, every test fails with `LOAD_FAILED`. With
|
|
250
|
+
no tests named, one outcome named `filename` reports the failure.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
source: Module source with the test functions.
|
|
254
|
+
filename: Name for tracebacks and for a load failure without tests.
|
|
255
|
+
names: The tests to run, in order.
|
|
256
|
+
namespace: Globals for the source. It gets the source's names.
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
One outcome per name.
|
|
260
|
+
"""
|
|
261
|
+
|
|
262
|
+
from mogs._assertrewrite import compile_tests
|
|
263
|
+
|
|
264
|
+
try:
|
|
265
|
+
exec(compile_tests(source, filename), namespace)
|
|
266
|
+
except BaseException as exc:
|
|
267
|
+
message = cap(f"the tests failed to load ({exception_summary(exc)})")
|
|
268
|
+
failed = names or (filename,)
|
|
269
|
+
return [Outcome(name, False, message, FailureReason.LOAD_FAILED) for name in failed]
|
|
270
|
+
|
|
271
|
+
outcomes = []
|
|
272
|
+
|
|
273
|
+
for name in names:
|
|
274
|
+
match namespace.get(name):
|
|
275
|
+
case test if callable(test):
|
|
276
|
+
outcomes.append(run_test(name, test))
|
|
277
|
+
case _:
|
|
278
|
+
message = f"`{name}` is not defined by its tests"
|
|
279
|
+
outcomes.append(Outcome(name, False, message, FailureReason.ERROR))
|
|
280
|
+
|
|
281
|
+
return outcomes
|
mogs/scaffold.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""`mogs init`: a new assignment folder with a notebook to start from."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from string import Template
|
|
6
|
+
|
|
7
|
+
from mogs.config import check_name
|
|
8
|
+
from mogs.transform import python_literal
|
|
9
|
+
|
|
10
|
+
NOTEBOOK = Template('''\
|
|
11
|
+
# /// script
|
|
12
|
+
# requires-python = ">=3.13"
|
|
13
|
+
# dependencies = ["marimo", "mogs"]
|
|
14
|
+
# ///
|
|
15
|
+
|
|
16
|
+
import marimo
|
|
17
|
+
|
|
18
|
+
__generated_with = $marimo
|
|
19
|
+
app = marimo.App()
|
|
20
|
+
|
|
21
|
+
with app.setup:
|
|
22
|
+
import marimo as mo
|
|
23
|
+
import mogs
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@app.cell
|
|
27
|
+
def _():
|
|
28
|
+
mogs.assignment(name=$name)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@app.cell(hide_code=True)
|
|
32
|
+
def instructor_guide():
|
|
33
|
+
mo.md(r"""
|
|
34
|
+
## How to write this assignment
|
|
35
|
+
|
|
36
|
+
See docs: https://mogs.kristia.de/instructors
|
|
37
|
+
|
|
38
|
+
The two questions below are examples. Change them into your own questions or delete
|
|
39
|
+
them. Each question ends with a `mogs.grade("<id>", points=...)` cell.
|
|
40
|
+
|
|
41
|
+
**Auto-graded question `q1`:**
|
|
42
|
+
|
|
43
|
+
1. The question text, as Markdown.
|
|
44
|
+
2. The function students write. Put your solution between `# BEGIN SOLUTION` and
|
|
45
|
+
`# END SOLUTION`, or by putting an inline comment `# SOLUTION`.
|
|
46
|
+
3. Public tests: a cell of functions named `test_q1_<anything>`.
|
|
47
|
+
4. Hidden tests, optional: another such cell, with `# HIDDEN` as its first line.
|
|
48
|
+
5. `mogs.grade("q1", points=4)`
|
|
49
|
+
|
|
50
|
+
**Written question `q2`:**
|
|
51
|
+
|
|
52
|
+
1. The question text, as Markdown.
|
|
53
|
+
2. Your answer, as Markdown between `<!-- BEGIN SOLUTION -->` and
|
|
54
|
+
`<!-- END SOLUTION -->`.
|
|
55
|
+
3. `mogs.grade("q2", points=5)`
|
|
56
|
+
""")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@app.cell(hide_code=True)
|
|
60
|
+
def _():
|
|
61
|
+
mo.md(r"""
|
|
62
|
+
## Question 1
|
|
63
|
+
|
|
64
|
+
Write `mean(xs)`, the average of a list of numbers.
|
|
65
|
+
""")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@app.function
|
|
69
|
+
def mean(xs):
|
|
70
|
+
# BEGIN SOLUTION
|
|
71
|
+
return sum(xs) / len(xs)
|
|
72
|
+
# END SOLUTION
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@app.cell
|
|
76
|
+
def _():
|
|
77
|
+
def test_q1_basic():
|
|
78
|
+
assert mean([1, 2, 3]) == 2
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@app.cell
|
|
82
|
+
def _():
|
|
83
|
+
# HIDDEN
|
|
84
|
+
def test_q1_single():
|
|
85
|
+
assert mean([7]) == 7
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@app.cell
|
|
89
|
+
def _():
|
|
90
|
+
mogs.grade("q1", points=4)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@app.cell(hide_code=True)
|
|
94
|
+
def _():
|
|
95
|
+
mo.md(r"""
|
|
96
|
+
## Question 2
|
|
97
|
+
|
|
98
|
+
What does `mean([])` do?
|
|
99
|
+
""")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@app.cell
|
|
103
|
+
def _():
|
|
104
|
+
mo.md(r"""
|
|
105
|
+
<!-- BEGIN SOLUTION -->
|
|
106
|
+
It divides by zero and raises `ZeroDivisionError`.
|
|
107
|
+
<!-- END SOLUTION -->
|
|
108
|
+
""")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@app.cell
|
|
112
|
+
def _():
|
|
113
|
+
mogs.grade("q2", points=5)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
if __name__ == "__main__":
|
|
117
|
+
app.run()
|
|
118
|
+
''')
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class InitError(Exception):
|
|
122
|
+
"""The assignment folder cannot be created."""
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def init(folder: Path) -> Path:
|
|
126
|
+
"""Create `folder` with one notebook, `<folder name>.py`, to start an assignment from.
|
|
127
|
+
|
|
128
|
+
The notebook holds the assignment cell, a guide for the instructor and two example
|
|
129
|
+
questions. It builds as it is.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
folder: The assignment folder. It may exist if it is empty.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
The notebook's path.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
InitError: If `folder` is a file or a folder with files in it.
|
|
139
|
+
ConfigError: If the folder name does not work as an assignment name.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
name = check_name(folder.resolve().name)
|
|
143
|
+
|
|
144
|
+
if folder.exists() and not folder.is_dir():
|
|
145
|
+
raise InitError(f"{folder} is not a folder.")
|
|
146
|
+
|
|
147
|
+
if folder.is_dir() and any(folder.iterdir()):
|
|
148
|
+
raise InitError(f"{folder} is not empty. Pick a new folder for the assignment.")
|
|
149
|
+
|
|
150
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
path = folder / f"{name}.py"
|
|
152
|
+
text = NOTEBOOK.substitute(name=python_literal(name), marimo=python_literal(version("marimo")))
|
|
153
|
+
path.write_text(text, encoding="utf-8")
|
|
154
|
+
|
|
155
|
+
return path
|
mogs/selfcheck.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Run the public tests of a saved notebook and print a summary as JSON.
|
|
2
|
+
|
|
3
|
+
Usage: `python -m mogs.selfcheck NOTEBOOK [FOLDER]`. The export button runs this
|
|
4
|
+
in a subprocess on the saved file, so the tests see the file on disk, not the kernel. It runs
|
|
5
|
+
from FOLDER, by default the notebook's folder, as marimo does, so relative paths in the
|
|
6
|
+
notebook work.
|
|
7
|
+
|
|
8
|
+
Tests are found statically and run the way the grader's public phase runs them: the setup
|
|
9
|
+
cell first, then the student names bound from the notebook, then each test cell compiled with
|
|
10
|
+
assertion rewriting. A student copy has no test cells; its grade calls name the files that
|
|
11
|
+
hold its public tests (`test_file`), and those run the same way. A file that cannot be read
|
|
12
|
+
counts as one failed test named after it. There is no per-test timer here; the caller caps
|
|
13
|
+
the whole run.
|
|
14
|
+
|
|
15
|
+
The last line of stdout is the JSON summary, `{"questions": {qid: {"passed": k, "total": n,
|
|
16
|
+
"failed": [names]}}, "unavailable": {name: reason}}`. `unavailable` holds each name the tests
|
|
17
|
+
use that the notebook could not provide, such as a name lost to a failed notebook run,
|
|
18
|
+
with the reason. Prints from the notebook go to stderr. On a notebook that cannot be read or
|
|
19
|
+
parsed, the exit status is 1 and stderr says why.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import contextlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import TypedDict
|
|
28
|
+
|
|
29
|
+
from mogs.config import AssignmentConfig
|
|
30
|
+
from mogs.grader.bundle import Phase, TestCell, bundle_from_notebook
|
|
31
|
+
from mogs.loader import bind, unavailable
|
|
32
|
+
from mogs.runner import (
|
|
33
|
+
FailureReason,
|
|
34
|
+
Outcome,
|
|
35
|
+
cap,
|
|
36
|
+
exception_summary,
|
|
37
|
+
run_test_source,
|
|
38
|
+
)
|
|
39
|
+
from mogs.source import (
|
|
40
|
+
Notebook,
|
|
41
|
+
SourceError,
|
|
42
|
+
cell_names,
|
|
43
|
+
module_tests,
|
|
44
|
+
parse_notebook,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Summary(TypedDict):
|
|
49
|
+
"""The JSON summary: results per question, and the reason for each unavailable name."""
|
|
50
|
+
|
|
51
|
+
questions: dict[str, dict[str, object]]
|
|
52
|
+
unavailable: dict[str, str]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def public_results(path: Path) -> Summary:
|
|
56
|
+
"""Run the public tests of the notebook at `path` in this process.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
OSError: If the file cannot be read.
|
|
60
|
+
UnicodeDecodeError: If it is not UTF-8.
|
|
61
|
+
SourceError: If it does not parse as a notebook.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
src = path.read_text(encoding="utf-8")
|
|
65
|
+
nb = parse_notebook(src)
|
|
66
|
+
|
|
67
|
+
# The bundle keeps the config but does not read it; a student copy has none.
|
|
68
|
+
cfg = AssignmentConfig(name=path.stem, notebook=path.name, questions={})
|
|
69
|
+
bundle = bundle_from_notebook(nb, cfg).for_phase(Phase.PUBLIC)
|
|
70
|
+
# Each cell with the name it reports a load failure under.
|
|
71
|
+
cells = [(cell, f"{cell.qid}-tests") for cell in bundle.cells]
|
|
72
|
+
outcomes: dict[str, list[Outcome]] = {}
|
|
73
|
+
students = nb.student_names()
|
|
74
|
+
|
|
75
|
+
for qid, relative in test_files(nb):
|
|
76
|
+
try:
|
|
77
|
+
source = (path.parent / relative).read_text(encoding="utf-8")
|
|
78
|
+
names = module_tests(source)
|
|
79
|
+
uses = tuple(sorted(cell_names(source)[1] & students))
|
|
80
|
+
except (OSError, UnicodeDecodeError, SyntaxError) as exc:
|
|
81
|
+
message = cap(f"cannot read {relative} ({exception_summary(exc)})")
|
|
82
|
+
outcome = Outcome(relative, False, message, FailureReason.LOAD_FAILED)
|
|
83
|
+
outcomes.setdefault(qid, []).append(outcome)
|
|
84
|
+
continue
|
|
85
|
+
|
|
86
|
+
cells.append((TestCell(qid, False, source, names, uses), relative))
|
|
87
|
+
|
|
88
|
+
base: dict[str, object] = {"__name__": "__mogs_selfcheck__"}
|
|
89
|
+
setup_error = None
|
|
90
|
+
missing: dict[str, str] = {}
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
exec(compile(bundle.setup_code, "<mogs-setup>", "exec", dont_inherit=True), base)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
setup_error = cap(f"the setup cell failed ({exception_summary(exc)})")
|
|
96
|
+
|
|
97
|
+
if setup_error is None:
|
|
98
|
+
uses = sorted({name for cell, _ in cells for name in cell.uses})
|
|
99
|
+
bound = bind(path, uses)
|
|
100
|
+
base.update(bound)
|
|
101
|
+
missing = {
|
|
102
|
+
name: reason
|
|
103
|
+
for name, value in bound.items()
|
|
104
|
+
if (reason := unavailable(value)) is not None
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
for cell, label in cells:
|
|
108
|
+
results = outcomes.setdefault(cell.qid, [])
|
|
109
|
+
|
|
110
|
+
if setup_error is not None:
|
|
111
|
+
reason = FailureReason.LOAD_FAILED
|
|
112
|
+
results += [Outcome(name, False, setup_error, reason) for name in cell.tests]
|
|
113
|
+
continue
|
|
114
|
+
|
|
115
|
+
results += run_test_source(cell.source, label, cell.tests, dict(base))
|
|
116
|
+
|
|
117
|
+
questions: dict[str, dict[str, object]] = {
|
|
118
|
+
qid: {
|
|
119
|
+
"passed": sum(outcome.passed for outcome in results),
|
|
120
|
+
"total": len(results),
|
|
121
|
+
"failed": [outcome.name for outcome in results if not outcome.passed],
|
|
122
|
+
}
|
|
123
|
+
for qid, results in outcomes.items()
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {"questions": questions, "unavailable": missing}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_files(nb: Notebook) -> list[tuple[str, str]]:
|
|
130
|
+
"""Question id and `test_file` of each grade call that names one, without repeats."""
|
|
131
|
+
|
|
132
|
+
calls = [cell for cell in nb.cells if cell.grade_qid is not None and not cell.hidden]
|
|
133
|
+
pairs = [(cell.grade_qid, nb.grade_test_file(cell)) for cell in calls]
|
|
134
|
+
|
|
135
|
+
return list(
|
|
136
|
+
dict.fromkeys((qid, file) for qid, file in pairs if qid is not None and file is not None)
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def main(path: str | Path, folder: str | Path | None = None) -> int:
|
|
141
|
+
"""Print the public-test summary of the notebook at `path` as one JSON line.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
path: The notebook file.
|
|
145
|
+
folder: Working directory for the tests; the notebook's folder when `None`.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
The exit status: 0, or 1 when the notebook cannot be read or parsed.
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
sys.dont_write_bytecode = True
|
|
152
|
+
notebook = Path(path).resolve()
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
os.chdir(notebook.parent if folder is None else folder)
|
|
156
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
157
|
+
summary = public_results(notebook)
|
|
158
|
+
except (OSError, UnicodeDecodeError, SourceError) as exc:
|
|
159
|
+
print(f"Cannot check {notebook.name}: {exc}", file=sys.stderr)
|
|
160
|
+
return 1
|
|
161
|
+
|
|
162
|
+
print(json.dumps(summary))
|
|
163
|
+
return 0
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
if __name__ == "__main__":
|
|
167
|
+
match sys.argv[1:]:
|
|
168
|
+
case [path]:
|
|
169
|
+
sys.exit(main(path))
|
|
170
|
+
case [path, folder]:
|
|
171
|
+
sys.exit(main(path, folder))
|
|
172
|
+
case _:
|
|
173
|
+
sys.exit("Usage: python -m mogs.selfcheck NOTEBOOK [FOLDER]")
|