From 0db9b895bc32c3a09fc527ae7886e543d492057d Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:34:34 -0500 Subject: [PATCH 01/17] fix(cli): say 1 pt, not 1 pts, in the build report --- src/mogs/cli.py | 3 ++- tests/test_build.py | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/mogs/cli.py b/src/mogs/cli.py index 85cac72..380c8b4 100644 --- a/src/mogs/cli.py +++ b/src/mogs/cli.py @@ -9,6 +9,7 @@ from mogs import __version__ from mogs.build import BuildError, BuildResult, build, failure_report, source_notebook +from mogs.check import format_points from mogs.config import ConfigError from mogs.regrade import GradeResult, grade_submission from mogs.requirements import RequirementsError @@ -156,7 +157,7 @@ def report(result: BuildResult) -> str: for score in result.scores: if score.solution is None or score.blank is None: how = ( - f"{score.points:g} pts, graded by hand" + f"{format_points(score.points)}, graded by hand" if score.points else "collected in the PDF, not graded" ) diff --git a/tests/test_build.py b/tests/test_build.py index 789f9f4..682bbd9 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -635,3 +635,11 @@ def test_data_files_skip_junk(tmp_path): files = data_files(folder, read_config(src, folder / "hw.py")) assert [str(rel) for rel in files] == ["data/scores.csv"] + + +def test_report_says_one_pt(tmp_path): + result = fake_result(tmp_path / "dist", scores=(QuestionScore("q3", "Proof", 1, None, None),)) + + text = report(result) + + assert "- q3 Proof: 1 pt, graded by hand" in text From a3c6bf044d3633cef586dc320c9db91c418b88c7 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:35:08 -0500 Subject: [PATCH 02/17] fix(build): skip 0-point questions in the free-points warning --- src/mogs/build.py | 13 ++++++++++--- tests/test_build.py | 21 ++++++++++++++++++++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/mogs/build.py b/src/mogs/build.py index f339a58..7533efd 100644 --- a/src/mogs/build.py +++ b/src/mogs/build.py @@ -314,7 +314,7 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes ) blank = _self_grade(bundle, student_path, check / "blank", assignment_dir, python) - warnings += _blank_warnings(blank) + warnings += free_points_warnings(blank.outcomes, cfg) # Output, written in full before it replaces the old one. out = stage / DIST @@ -472,8 +472,15 @@ def _failed_tests(names: list[str], load_failed: bool) -> str: return f"{tests} of {questions}" -def _blank_warnings(blank: _Graded) -> list[str]: - passing = [outcome.name for outcome in blank.outcomes.values() if outcome.passed] +def free_points_warnings(blank: Mapping[str, Outcome], cfg: AssignmentConfig) -> list[str]: + """A warning naming the tests that pass on the blank notebook, in questions worth points.""" + + passing = [ + outcome.name + for outcome in blank.values() + if outcome.passed and cfg.questions[question_id(outcome.name)].points > 0 + ] + if not passing: return [] diff --git a/tests/test_build.py b/tests/test_build.py index 682bbd9..0c9de12 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -19,9 +19,10 @@ data_files, failure_report, find_notebook, + free_points_warnings, ) from mogs.cli import main, report -from mogs.config import ConfigError, read_config +from mogs.config import AssignmentConfig, ConfigError, Question, read_config from mogs.runner import FailureReason, Outcome DEMO = Path(__file__).parent.parent / "examples" / "demo" @@ -643,3 +644,21 @@ def test_report_says_one_pt(tmp_path): text = report(result) assert "- q3 Proof: 1 pt, graded by hand" in text + + +def test_free_points_warning_names_tests_that_pass_blank(): + cfg = AssignmentConfig("A", "hw.py", {"q1": Question("q1", "Q", 4)}) + outcomes = {"test_q1_a": Outcome("test_q1_a", True), "test_q1_b": Outcome("test_q1_b", False)} + + [warning] = free_points_warnings(outcomes, cfg) + + assert "test_q1_a" in warning + assert "test_q1_b" not in warning + + +def test_free_points_warning_skips_zero_point_questions(): + questions = {"q1": Question("q1", "Q", 4), "q2": Question("q2", "Practice", 0)} + cfg = AssignmentConfig("A", "hw.py", questions) + outcomes = {"test_q1_a": Outcome("test_q1_a", False), "test_q2_a": Outcome("test_q2_a", True)} + + assert free_points_warnings(outcomes, cfg) == [] From c1bc18467ac15a3225eae7c438cf1c64f1ad2d5a Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:36:07 -0500 Subject: [PATCH 03/17] fix(build): warn when # HIDDEN comes after code in its cell --- src/mogs/build.py | 10 +++++++++- src/mogs/source.py | 20 ++++++++++++++++++-- tests/test_source.py | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/src/mogs/build.py b/src/mogs/build.py index 7533efd..ba64186 100644 --- a/src/mogs/build.py +++ b/src/mogs/build.py @@ -48,7 +48,14 @@ from mogs.grader.templates import run_autograder_script, setup_script from mogs.requirements import gradescope_requirements from mogs.runner import FailureReason, Outcome -from mogs.source import Notebook, parse_notebook, prompt_previews, question_id, validate +from mogs.source import ( + Notebook, + parse_notebook, + prompt_previews, + question_id, + source_warnings, + validate, +) from mogs.transform import ( TESTS_FOLDER, pinned_requirement, @@ -277,6 +284,7 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes tests = public_test_files(nb) requirement = tool_requirement or f"{TOOL}=={__version__}" requirements, warnings = gradescope_requirements(src, cfg, requirement) + warnings = source_warnings(nb) + warnings entries = { "setup.sh": setup_script(cfg).encode(), "run_autograder": run_autograder_script().encode(), diff --git a/src/mogs/source.py b/src/mogs/source.py index 02c8f4a..b021c90 100644 --- a/src/mogs/source.py +++ b/src/mogs/source.py @@ -94,6 +94,7 @@ class Cell: hidden: The cell holds a `# HIDDEN` line. grade_qid: Question id of the cell's `grade(...)` call, if any. assignment: The cell holds an `assignment(...)` call. + late_hidden: Line of a `# HIDDEN` that comes after the cell's first statement, if any. """ kind: CellKind @@ -104,6 +105,7 @@ class Cell: hidden: bool grade_qid: str | None assignment: bool = False + late_hidden: int | None = None @property def instructor(self) -> bool: @@ -520,12 +522,14 @@ def parse_notebook(src: str) -> Notebook: end = _trailing_comments_end(lines, _end(node)) text = lines[start - 1 : end] tests = _tests(node, kind) - hidden = any(line.strip() == HIDDEN for line in text) + markers = [start + i for i, line in enumerate(text) if line.strip() == HIDDEN] + first_statement = node.body[0].lineno + late = next((line for line in markers if line > first_statement), None) plain = kind is CellKind.CELL grade = _call_qid(tree, node, Api.GRADE) if plain else None assignment = bool(api_calls(tree, node, Api.ASSIGNMENT)) - cells.append(Cell(kind, name, start, end, tests, hidden, grade, assignment)) + cells.append(Cell(kind, name, start, end, tests, bool(markers), grade, assignment, late)) return Notebook(tuple(cells), src) @@ -683,6 +687,18 @@ def _returned_names(node: ast.stmt) -> set[str]: # Validation +def source_warnings(nb: Notebook) -> list[str]: + """Things in the notebook that build but may not do what the instructor meant.""" + + return [ + f"line {cell.late_hidden}: `{HIDDEN}` hides the whole cell at line {cell.start}, not " + "only the code after it. Move it to the cell's first line, or move the hidden tests " + "to a cell of their own." + for cell in nb.cells + if cell.late_hidden is not None + ] + + def validate(nb: Notebook, cfg: AssignmentConfig) -> list[str]: """Check the notebook against its config and the authoring rules. diff --git a/tests/test_source.py b/tests/test_source.py index 6ad3447..8675cf5 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -12,6 +12,7 @@ module_tests, parse_notebook, prompt_previews, + source_warnings, validate, ) @@ -1446,3 +1447,40 @@ def test_validate_test_reading_its_own_cell_names_ok(): hidden = hidden_cell("n_missing = 3\n\ndef test_q1_h():\n assert n_missing == 3") assert errors(PUBLIC + CHECK + hidden) == [] + + +# Warnings + + +LATE_HIDDEN = """ +@app.cell +def _(): + def test_q1_a(): + assert True + + # HIDDEN + def test_q1_b(): + assert True + + return +""" + + +def test_hidden_after_code_warns_that_it_hides_the_whole_cell(): + [warning] = source_warnings(parse_notebook(nb(LATE_HIDDEN))) + + line = nb(LATE_HIDDEN).splitlines().index(" # HIDDEN") + 1 + assert f"line {line}" in warning + assert "whole cell" in warning + + +@pytest.mark.parametrize( + "cell", + [ + "\n@app.cell\ndef _():\n # HIDDEN\n def test_q1_a():\n assert True\n", + "\n@app.function\n# HIDDEN\ndef test_q1_a():\n assert True\n", + "\n@app.function\ndef test_q1_a():\n # HIDDEN\n assert True\n", + ], +) +def test_hidden_on_the_first_line_does_not_warn(cell): + assert source_warnings(parse_notebook(nb(cell))) == [] From 92cd33e5e7a601b8ede78f5429c919819cada223 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:38:35 -0500 Subject: [PATCH 04/17] fix(source): report a misnamed test, not a cell mixing questions --- src/mogs/source.py | 10 +++++++--- tests/test_source.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/mogs/source.py b/src/mogs/source.py index b021c90..eec613b 100644 --- a/src/mogs/source.py +++ b/src/mogs/source.py @@ -724,7 +724,10 @@ def _test_name_errors(nb: Notebook, cfg: AssignmentConfig) -> list[str]: seen: set[str] = set() for cell in nb.cells: - if len({question_id(name) for name in cell.tests}) > 1: + # A test of an unknown question gets its own error below, usually a misnamed test. + known = {question_id(name) for name in cell.tests} & cfg.questions.keys() + + if len(known) > 1: errors.append( f"line {cell.start}: tests of different questions share a cell " f"({', '.join(cell.tests)}). Put each question's tests in their own cell." @@ -738,8 +741,9 @@ def _test_name_errors(nb: Notebook, cfg: AssignmentConfig) -> list[str]: qid = question_id(name) if qid not in cfg.questions: errors.append( - f"`{name}` (line {cell.start}): no question `{qid}`. Declare it in a cell " - f'with `mogs.grade("{qid}", points=...)`.' + f"`{name}` (line {cell.start}): no question `{qid}`. Tests are named " + f"`test__`, so rename it, or declare `{qid}` in a cell with " + f'`mogs.grade("{qid}", points=...)`.' ) if cell.grade_qid is not None and cell.grade_qid not in cfg.questions: diff --git a/tests/test_source.py b/tests/test_source.py index 8675cf5..4fabe17 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -557,6 +557,17 @@ def test_validate_unknown_qid_in_test(): assert "`q9`" in error +def test_validate_misnamed_test_next_to_good_ones_reports_only_the_name(): + misnamed = PUBLIC.replace( + " return", " def test_row_count():\n assert True\n return" + ) + error = one_error(misnamed + CHECK) + + assert "`test_row_count`" in error + assert "no question `row`" in error + assert "`test__`" in error + + def test_validate_unknown_qid_in_grade(): error = one_error(PUBLIC + CHECK + CHECK.replace("q1", "q9")) From b97848cfcb1e3fa352a735011085a7d73177bcd5 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:39:13 -0500 Subject: [PATCH 05/17] fix(build): remove the old dist/ output when a build fails --- docs/src/content/docs/instructors.md | 2 +- src/mogs/build.py | 15 ++++++++++++++- tests/test_build.py | 18 ++++++++++++++++-- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/docs/src/content/docs/instructors.md b/docs/src/content/docs/instructors.md index 5147317..45734b3 100644 --- a/docs/src/content/docs/instructors.md +++ b/docs/src/content/docs/instructors.md @@ -341,7 +341,7 @@ examples/demo/ Upload `-autograder-.zip` to Gradescope as the autograder. The directory also contains the solved notebook, i.e., the student notebook with the solutions, together with its public tests, the data files and `requirements.txt`. -Each build replaces both directories. +Each build replaces both directories, and a failed build removes them. Before writing them, the build checks the assignment by grading two notebooks with the real grader: the solved notebook and the blank student notebook. It does this in a fresh environment with the same pinned requirements that Gradescope gets. diff --git a/src/mogs/build.py b/src/mogs/build.py index ba64186..c61c603 100644 --- a/src/mogs/build.py +++ b/src/mogs/build.py @@ -254,7 +254,8 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes """Build and self-check the assignment in `assignment_dir`. The output is written in full to a temporary folder first. Only when every step succeeds - does it replace `dist/student/` and `dist/autograder/`, so only the newest zip is kept. + does it replace `dist/student/` and `dist/autograder/`, so only the newest zip is kept. A + failed build removes them. Args: assignment_dir: Folder with the source notebook and its data files. @@ -273,6 +274,18 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes RequirementsError: If the dependencies cannot be pinned or installed. """ + try: + return _build(assignment_dir, tool_requirement) + except Exception: + for part in ("student", "autograder"): + shutil.rmtree(assignment_dir / DIST / part, ignore_errors=True) + + raise + + +def _build(assignment_dir: Path, tool_requirement: str | None) -> BuildResult: + """`build` without the cleanup of a failed build.""" + require_posix() assignment = read_assignment(assignment_dir) src, cfg, nb = assignment.src, assignment.cfg, assignment.nb diff --git a/tests/test_build.py b/tests/test_build.py index 0c9de12..2b4f78d 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -414,11 +414,12 @@ def test_help_is_short(capsys): @pytest.mark.network -def test_failed_write_keeps_the_old_dist(tmp_path, monkeypatch, capsys): +def test_failed_write_removes_the_old_dist(tmp_path, monkeypatch, capsys): folder = demo_copy(tmp_path / "demo") old = folder / "dist" / "student" / "old.txt" old.parent.mkdir(parents=True) old.write_text("old", encoding="utf-8") + (folder / "dist" / "notes.txt").write_text("mine", encoding="utf-8") def broken(path, entries): raise OSError("disk full") @@ -428,7 +429,20 @@ def broken(path, entries): assert code == 1 assert "disk full" in capsys.readouterr().err - assert tree(folder / "dist") == ["student/old.txt"] + assert tree(folder / "dist") == ["notes.txt"] + + +def test_invalid_notebook_removes_the_old_dist(tmp_path, capsys): + folder = demo_copy(tmp_path / "demo") + old = folder / "dist" / "autograder" / "old.zip" + old.parent.mkdir(parents=True) + old.write_text("old", encoding="utf-8") + edit(folder / "hw.py", "def test_q1_single", "def test_q9_single") + + code = main(["build", str(folder)]) + + assert code == 1 + assert not old.parent.exists() def test_name_cannot_escape_dist(tmp_path): From 335d90cb65944a51a82f92ff36f8645ea6e39788 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:40:35 -0500 Subject: [PATCH 06/17] fix(grade): skip public test files when looking for the notebook --- src/mogs/config.py | 2 ++ src/mogs/grader/results.py | 31 ++++++++++++++++++++++--------- src/mogs/transform.py | 2 +- tests/test_results.py | 17 +++++++++++++++++ 4 files changed, 42 insertions(+), 10 deletions(-) diff --git a/src/mogs/config.py b/src/mogs/config.py index 6a478d5..2452368 100644 --- a/src/mogs/config.py +++ b/src/mogs/config.py @@ -20,6 +20,8 @@ TOOL = "mogs" PACKAGE = "mogs" ASSIGNMENT = "mogs.assignment()" +# Folder next to the student notebook with its public tests, `tests/.py`. +TESTS_FOLDER = "tests" MIN_MEMORY_MB = 2048 # The reference regex from PEP 723, for the `script` block. diff --git a/src/mogs/grader/results.py b/src/mogs/grader/results.py index 1ba5de1..ae8829c 100644 --- a/src/mogs/grader/results.py +++ b/src/mogs/grader/results.py @@ -13,6 +13,7 @@ from pathlib import Path from typing import NotRequired, TypedDict +from mogs.config import TESTS_FOLDER from mogs.grader.bundle import GradingBundle from mogs.runner import Outcome, cap @@ -80,26 +81,38 @@ def find_submission(sub_dir: Path, notebook: str) -> Submission: files = sorted(_regular_files(sub_dir)) scripts = [path for path in files if path.suffix == ".py"] exact = [path for path in scripts if path.name == notebook] + # The public tests the student copy ships in `tests/`. + others = [path for path in scripts if path.parent.name != TESTS_FOLDER] pdfs = [path for path in files if path.suffix.lower() == ".pdf"] fallback = f"{Path(notebook).stem}_answers.md".casefold() markdown = [path for path in files if path.name.casefold() == fallback] answers = next(iter(pdfs or markdown), None) + wanted = inline_code(notebook) - match exact or scripts: - case [py]: + match exact, others: + case [py], _: return Submission(py, answers, None) - case []: - error = f"No `.py` file found in your upload. Upload {inline_code(notebook)}." - case several: - names = ", ".join(inline_code(str(path.relative_to(sub_dir))) for path in several) - error = ( - f"Found several notebooks: {names}. Upload only {inline_code(notebook)}, " - "or a single `.py` file." + case [], [py]: + return Submission(py, answers, None) + case [], []: + error = f"No `.py` file found in your upload. Upload {wanted}." + case [], several: + names = _names(several, sub_dir) + error = f"No {wanted} in your upload, and several other `.py` files: {names}. " + ( + f"Upload {wanted}, or a single `.py` file." ) + case several, _: + error = f"Found {wanted} more than once: {_names(several, sub_dir)}. Upload one." return Submission(None, answers, error) +def _names(paths: Sequence[Path], root: Path) -> str: + """The paths relative to `root`, as inline code, comma separated.""" + + return ", ".join(inline_code(str(path.relative_to(root))) for path in paths) + + def _regular_files(root: Path) -> list[Path]: """Regular files under `root`, skipping junk folders, dot names and symlinks.""" diff --git a/src/mogs/transform.py b/src/mogs/transform.py index 9afecf9..2217b09 100644 --- a/src/mogs/transform.py +++ b/src/mogs/transform.py @@ -16,6 +16,7 @@ from mogs import __version__ from mogs.config import ( PACKAGE, + TESTS_FOLDER, AssignmentConfig, normalize_newlines, set_dependency, @@ -41,7 +42,6 @@ MARKDOWN_PLACEHOLDER = "*Write your answer here.*" DEFAULT_ALIAS = "mogs" MARIMO_ALIAS = "mo" -TESTS_FOLDER = "tests" # Solution lines that may appear in the student copy by chance: no letters, or a bare keyword. TRIVIAL_LINE_RE = re.compile(r"[^A-Za-z]*|(?:pass|return|break|continue|else|try|finally):?") diff --git a/tests/test_results.py b/tests/test_results.py index b3e53df..7beebbb 100644 --- a/tests/test_results.py +++ b/tests/test_results.py @@ -183,6 +183,23 @@ def test_two_py_files_are_both_named(tmp_path): assert "hw.py" in found.error +def test_public_test_files_are_not_notebooks(tmp_path): + touch(tmp_path, "hw2/student_file.py", "hw2/tests/q1.py", "hw2/tests/q2.py") + + found = find_submission(tmp_path, "hw.py") + + assert found.py == tmp_path / "hw2" / "student_file.py" + + +def test_two_py_files_are_not_called_notebooks(tmp_path): + touch(tmp_path, "one.py", "two.py") + + error = find_submission(tmp_path, "hw.py").error or "" + + assert "notebooks" not in error + assert "No `hw.py`" in error + + def test_no_py_file(tmp_path): touch(tmp_path, "notes.txt") From 87dfcdb08817b095fd888b38e7fe5726d2538315 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:41:08 -0500 Subject: [PATCH 07/17] fix(config): title question ids Question , like q --- docs/src/content/docs/instructors.md | 2 +- src/mogs/config.py | 4 ++-- tests/test_config.py | 18 ++++++++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/src/content/docs/instructors.md b/docs/src/content/docs/instructors.md index 45734b3..be0d0e1 100644 --- a/docs/src/content/docs/instructors.md +++ b/docs/src/content/docs/instructors.md @@ -70,7 +70,7 @@ The questions appear on Gradescope in the order of these cells. | ----------- | ----------- | -------------------------- | ----------------------------------------------------------------------------------------- | | question id | required | `"q1"` | The first argument. | | `points` | required | `points=25` | Points for the question. A written question can be worth 0. | -| `title` | from the id | `title="Gradient descent"` | Name on Gradescope and in the PDF. `q1` becomes `Question 1`; other ids stay as they are. | +| `title` | from the id | `title="Gradient descent"` | Name on Gradescope and in the PDF. `q1` and `question1` become `Question 1`; other ids stay as they are. | Question ids are letters and digits, and start with a letter, e.g., `q1` or `bonus`. They can't contain `_`: test names use `_` to separate the id from the rest of the name. diff --git a/src/mogs/config.py b/src/mogs/config.py index 2452368..8b12108 100644 --- a/src/mogs/config.py +++ b/src/mogs/config.py @@ -392,9 +392,9 @@ def _points(where: str, value: object) -> float: def default_title(qid: str) -> str: - """`q1` → `Question 1`, `q2b` → `Question 2b`; other ids stay as they are.""" + """`q1` → `Question 1`, `question_2b` → `Question 2b`, any case; other ids stay as they are.""" - match = re.fullmatch(r"q(\d\w*)", qid) + match = re.fullmatch(r"(?:q|question)_?(\d\w*)", qid, re.IGNORECASE) return f"Question {match.group(1)}" if match else qid diff --git a/tests/test_config.py b/tests/test_config.py index 1e49d16..09ae3d5 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,6 +6,7 @@ AssignmentConfig, ConfigError, Question, + default_title, read_config, read_header, remove_dependency, @@ -398,3 +399,20 @@ def test_question_ids_must_make_portable_file_names(qids, message): with pytest.raises(ConfigError, match=message): read_config(src, Path("hw.py")) + + +@pytest.mark.parametrize( + ("qid", "title"), + [ + ("q1", "Question 1"), + ("q2b", "Question 2b"), + ("Q3", "Question 3"), + ("question6", "Question 6"), + ("Question7", "Question 7"), + ("question_8", "Question 8"), + ("bonus", "bonus"), + ("quiz1", "quiz1"), + ], +) +def test_default_title(qid, title): + assert default_title(qid) == title From 0521c0ff6896c36ed3cda950df5fea0b524059a7 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:42:15 -0500 Subject: [PATCH 08/17] fix(check): word the source notebook's grade cells for the instructor Discovered tests in the source include the hidden ones, so the panel says "tests passed", and a written question's panel no longer points to an export button the source doesn't have. --- src/mogs/check.py | 29 ++++++++++++++++++++++------- tests/test_check.py | 27 ++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/src/mogs/check.py b/src/mogs/check.py index dbf695b..17d38a6 100644 --- a/src/mogs/check.py +++ b/src/mogs/check.py @@ -122,15 +122,23 @@ def grade( found = discover(qid, namespace) if tests is None else tests if not found and tests is None and _written_in_source(qid, namespace): - return mo.Html(written_panel(qid, points, title)) + return mo.Html(written_panel(qid, points, title, source=True)) outcomes = [run_test(name_of(test), with_rewritten_asserts(test)) for test in found] - return mo.Html(panel(qid, outcomes, points, hidden, title, problem)) + # Tests found in the source notebook include the hidden ones. + public = tests is not None or test_file is not None + return mo.Html(panel(qid, outcomes, points, hidden, title, problem, public=public)) -def written_panel(qid: str, points: float | None, title: str | None) -> str: - """HTML for a written question: its title and points, and where the answer goes.""" + +def written_panel( + qid: str, points: float | None, title: str | None, *, source: bool = False +) -> str: + """HTML for a written question: its title and points, and where the answer goes. + + In the `source` notebook, which has no export button, it says where the student's answer goes. + """ title = question_title(qid) if title is None else title @@ -140,7 +148,10 @@ def written_panel(qid: str, points: float | None, title: str | None) -> str: else: note = "Written answer, not graded." - note += " Write it in the cell above. It goes into the PDF when you export." + if source: + note += " Students write it in the cell above, and it goes into the PDF they export." + else: + note += " Write it in the cell above. It goes into the PDF when you export." return ( f'
' @@ -333,10 +344,13 @@ def panel( hidden: int, title: str | None = None, problem: str | None = None, + *, + public: bool = True, ) -> str: """HTML for the panel, headed by `title`, or by `question_title(qid)` when it is `None`. - `problem` says why there are no outcomes; it defaults to "No tests found". + `problem` says why there are no outcomes; it defaults to "No tests found". `public` says the + outcomes are of public tests only, and the title calls them so. """ title = question_title(qid) if title is None else title @@ -351,7 +365,8 @@ def panel( else: passed = sum(outcome.passed for outcome in outcomes) accent = PASS if passed == len(outcomes) else FAIL - title += f" · {passed}/{len(outcomes)} public tests passed" + kind = "public tests" if public else "tests" + title += f" · {passed}/{len(outcomes)} {kind} passed" items = "".join(outcome_item(outcome) for outcome in outcomes) body = f'
    {items}
' diff --git a/tests/test_check.py b/tests/test_check.py index 7489ec2..36456c8 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -360,7 +360,7 @@ def test_q2_d(): ) text = text_of(ns["panel"]) - assert "1/2 public tests passed" in text + assert "1/2 tests passed" in text assert "test_q1_a" in text assert "test_q1_b" in text assert "test_q10_c" not in text @@ -633,6 +633,31 @@ def test_grade_in_the_source_finds_written_questions_in_the_saved_notebook(qid, assert shown in text_of(namespace["panel"]) +def test_written_panel_in_the_source_does_not_mention_export(tmp_path): + notebook = tmp_path / "hw.py" + notebook.write_text(WRITTEN_SOURCE, encoding="utf-8") + namespace: dict[str, Any] = {"__file__": str(notebook), "grade": grade} + + exec('panel = grade("q2", points=5)', namespace) + + text = text_of(namespace["panel"]) + assert "when you export" not in text + assert "PDF" in text + + +def test_written_panel_in_the_student_copy_mentions_export(): + assert "when you export" in text_of(grade("q3", points=5, manual=True)) + + +def test_source_panel_does_not_call_hidden_tests_public(): + namespace: dict[str, Any] = {"grade": grade} + exec("def test_q1_a():\n assert True\n\npanel = grade('q1', points=1)", namespace) + + text = text_of(namespace["panel"]) + assert "1/1 tests passed" in text + assert "public" not in text + + def test_grade_without_a_saved_notebook_shows_no_tests(): namespace: dict[str, Any] = {"grade": grade} From 1dcf6d30b2a16ec8d6dd53ea7b37dee7b80fffa0 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:44:43 -0500 Subject: [PATCH 09/17] fix(export): name the submission files after the assignment With name="HW2" the export is now HW2_submission.zip with HW2.pdf, like the HW2 zip and folder. The grader looks for the Markdown fallback under that name too. --- src/mogs/grader/main.py | 2 +- src/mogs/grader/results.py | 12 +++++++----- src/mogs/transform.py | 5 ++--- tests/test_results.py | 8 ++++++++ tests/test_transform.py | 12 +++++++++--- 5 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/mogs/grader/main.py b/src/mogs/grader/main.py index 70d173c..e0ee3e6 100644 --- a/src/mogs/grader/main.py +++ b/src/mogs/grader/main.py @@ -68,7 +68,7 @@ def run(bundle: GradingBundle, source: Path, submission: Path, workdir: Path) -> """ config = bundle.config - found = find_submission(submission, config.notebook) + found = find_submission(submission, config.notebook, config.name) notices = [] if found.error is None else [found.error] if any(question.manual for question in config.questions.values()): diff --git a/src/mogs/grader/results.py b/src/mogs/grader/results.py index ae8829c..db016f8 100644 --- a/src/mogs/grader/results.py +++ b/src/mogs/grader/results.py @@ -62,17 +62,19 @@ class Submission: error: str | None -def find_submission(sub_dir: Path, notebook: str) -> Submission: +def find_submission(sub_dir: Path, notebook: str, name: str | None = None) -> Submission: """Find the notebook and the written answers anywhere under `sub_dir`. Skips `__MACOSX`, `__pycache__`, dot files and dot folders, and never follows or picks a - symlink. A file named `notebook` wins; otherwise the only `.py` file is taken. Any PDF - counts as the written answers. Of Markdown files, only the export's fallback - `_answers.md` (any case) does, so a stray `README.md` does not. + symlink. A file named `notebook` wins; otherwise the only `.py` file outside a `tests/` + folder is taken. Any PDF counts as the written answers. Of Markdown files, only the + export's fallback `_answers.md` (any case) does, so a stray `README.md` does not. Args: sub_dir: The unpacked upload. notebook: File name of the student notebook. + name: Assignment name, which the export names its files after. Defaults to the + notebook's stem. Returns: The files found, with an error message when the notebook is missing or ambiguous. @@ -84,7 +86,7 @@ def find_submission(sub_dir: Path, notebook: str) -> Submission: # The public tests the student copy ships in `tests/`. others = [path for path in scripts if path.parent.name != TESTS_FOLDER] pdfs = [path for path in files if path.suffix.lower() == ".pdf"] - fallback = f"{Path(notebook).stem}_answers.md".casefold() + fallback = f"{name or Path(notebook).stem}_answers.md".casefold() markdown = [path for path in files if path.name.casefold() == fallback] answers = next(iter(pdfs or markdown), None) wanted = inline_code(notebook) diff --git a/src/mogs/transform.py b/src/mogs/transform.py index 2217b09..135a19a 100644 --- a/src/mogs/transform.py +++ b/src/mogs/transform.py @@ -11,7 +11,7 @@ from collections.abc import Mapping, Sequence from collections.abc import Set as AbstractSet from enum import StrEnum -from pathlib import Path, PurePosixPath +from pathlib import PurePosixPath from mogs import __version__ from mogs.config import ( @@ -309,12 +309,11 @@ def export_cells( marimo: Which cell has `import marimo as mo`; `MISSING` adds a cell that does. """ - stem = Path(cfg.notebook).stem manual = [question.id for question in cfg.questions.values() if question.manual] titles = {qid: question.title for qid, question in cfg.questions.items()} name = alias or DEFAULT_ALIAS call = ( - f"{name}.export({EXPORT_BUTTON}, name={python_literal(stem)}, " + f"{name}.export({EXPORT_BUTTON}, name={python_literal(cfg.name)}, " f"manual={python_literal(manual)}, titles={python_literal(titles)}, " f"placeholders={python_literal(dict(placeholders or {}))})" ) diff --git a/tests/test_results.py b/tests/test_results.py index 7beebbb..5476c56 100644 --- a/tests/test_results.py +++ b/tests/test_results.py @@ -200,6 +200,14 @@ def test_two_py_files_are_not_called_notebooks(tmp_path): assert "No `hw.py`" in error +def test_markdown_answers_are_named_after_the_assignment(tmp_path): + touch(tmp_path, "hw2.py", "homework2_answers.md") + + assert find_submission(tmp_path, "hw2.py", "homework2").answers == ( + tmp_path / "homework2_answers.md" + ) + + def test_no_py_file(tmp_path): touch(tmp_path, "notes.txt") diff --git a/tests/test_transform.py b/tests/test_transform.py index 4e128e1..2aa2fdd 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -812,13 +812,19 @@ def test_export_cells_appended_before_main_guard(): assert "import mogs" not in tail assert " export_button\n" in tail assert ( - 'mogs.export(export_button, name="solution", manual=["q3"], titles={"q1": "Question 1", ' + 'mogs.export(export_button, name="Fixture", manual=["q3"], titles={"q1": "Question 1", ' '"q2": "Vowels", "q3": "Question 3"}, ' 'placeholders={"answer_q3": "Because the order of the terms does not change the sum."})' in tail ) +def test_export_files_are_named_after_the_assignment(): + cfg = AssignmentConfig("HW2", "hw2.py", {"q1": Question("q1", "Q1", 1)}) + + assert 'name="HW2"' in export_cells(cfg, None) + + def test_export_cells_parse_as_cells(): nb = parse_notebook(student(SOLUTION)) exporting = [cell for cell in nb.cells if "export_button" in nb.cell_body_source(cell)] @@ -990,7 +996,7 @@ def test_export_cells_quote_titles_safely(): def test_export_call_round_trips_non_bmp_text(): config = AssignmentConfig( - name="nb", + name="nb 🎉", notebook="hw 🎉.py", questions={"q1": Question("q1", "Bonus 🎉", 1, manual=True)}, ) @@ -1005,7 +1011,7 @@ def test_export_call_round_trips_non_bmp_text(): values = {k.arg: ast.literal_eval(k.value) for k in call.keywords} assert values == { - "name": "hw 🎉", + "name": "nb 🎉", "manual": ["q1"], "titles": {"q1": "Bonus 🎉"}, "placeholders": {"q1": "*Answer 🎉 here.*"}, From 06fa456bb64692748f9d2a4249261ce87c88c689 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:46:16 -0500 Subject: [PATCH 10/17] fix(pdf): drop a prompt heading that repeats the question title --- src/mogs/pdf.py | 25 +++++++++++++++++++++++++ tests/test_pdf.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/mogs/pdf.py b/src/mogs/pdf.py index b3c6e67..823bbbb 100644 --- a/src/mogs/pdf.py +++ b/src/mogs/pdf.py @@ -338,9 +338,34 @@ def part(cell: Cell, role: Role) -> Part: if not answers: parts += (Part(f"*No answer cell `answer_{qid}` found.*", Role.ANSWER),) + match parts: + case (Part(role=Role.PROMPT, style=Style.MARKDOWN) as first, *rest): + parts = (replace(first, text=without_title_heading(first.text, title)), *rest) + return Question(title, parts) +def without_title_heading(text: str, title: str) -> str: + """`text` without a leading Markdown heading whose words `title` already has. + + `## Derive the slope` goes under the title `Question 4: Derive the slope`; `## Question 4: + Derive the slope` stays under the title `Question 4`, since it says more. + """ + + match = re.match(r"\s*#{1,6}[ \t]+(.+?)[ \t#]*(?:\n|$)", text) + + if match is None or _words(match.group(1)) not in _words(title): + return text + + return text[match.end() :].lstrip("\n") + + +def _words(text: str) -> str: + """The words of `text` in lower case, each with a space on both sides: ` question 4 `.""" + + return f" {' '.join(re.findall(r'\w+', text.casefold()))} " + + def cell_markdown(nb: Notebook, cell: Cell) -> str: """The Markdown of a cell that is just `mo.md("...")`; else its source as a code block.""" diff --git a/tests/test_pdf.py b/tests/test_pdf.py index 6659e90..35f82af 100644 --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -210,6 +210,43 @@ def test_pdf_has_title_prompt_and_answer(tmp_path): assert sorted(path.name for path in tmp_path.iterdir()) == ["answers.pdf", "hw.py"] +@pytest.mark.parametrize( + ("title", "heading"), + [ + ("Question 4: Derive the slope", "### Derive the slope"), + ("Question 4", "## Question 4"), + ("Derive the slope", "## Derive the Slope."), + ], +) +def test_prompt_heading_the_title_already_says_is_dropped(tmp_path, title, heading): + reader = render( + tmp_path, + {"q4": "It is 2."}, + prompts={"q4": f"{heading}\n\nFind the slope of $y = 2x$."}, + titles={"q4": title}, + ) + + text = text_of(reader) + shown = heading.lstrip("#").strip().rstrip(".").casefold() + assert text.casefold().count(shown) == 1 + assert "Find the slope" in text + + +@pytest.mark.parametrize( + ("title", "heading"), + [("Question 4", "Question 4: Derive the slope"), ("Question 10", "Question 1")], +) +def test_prompt_heading_with_more_than_the_title_stays(tmp_path, title, heading): + reader = render( + tmp_path, + {"q4": "It is 2."}, + prompts={"q4": f"## {heading}\n\nFind it."}, + titles={"q4": title}, + ) + + assert f"{title} {heading}" in text_of(reader) + + PART_B = """ @app.cell def _(): From 84459162075d34d48e9b0a9728f40ec34bf91a6e Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:46:48 -0500 Subject: [PATCH 11/17] fix(source): fail the build when the notebook imports pytest without listing it --- src/mogs/source.py | 30 +++++++++++++++++++++++++++++- tests/test_source.py | 19 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/mogs/source.py b/src/mogs/source.py index eec613b..f18366d 100644 --- a/src/mogs/source.py +++ b/src/mogs/source.py @@ -20,7 +20,9 @@ AssignmentConfig, api_calls, normalize_newlines, + normalized_name, question_id, + read_header, split_lines, ) @@ -710,7 +712,7 @@ def validate(nb: Notebook, cfg: AssignmentConfig) -> list[str]: errors = _near_marker_errors(nb) + _near_html_marker_errors(nb) errors += _test_name_errors(nb, cfg) + _question_errors(nb, cfg) errors += _hidden_grade_errors(nb) + _public_cell_errors(nb) + _marker_errors(nb) - errors += _assignment_errors(nb) + _instructor_errors(nb) + errors += _assignment_errors(nb) + _instructor_errors(nb) + _pytest_dependency_errors(nb) errors += _public_marker_errors(nb) errors += _hidden_name_errors(nb) + _cell_variable_errors(nb) @@ -800,6 +802,32 @@ def _hidden_grade_errors(nb: Notebook) -> list[str]: ] +def _pytest_dependency_errors(nb: Notebook) -> list[str]: + """A notebook that imports `pytest` lists it in the header's `dependencies`. + + The grader has pytest either way, but marimo adds a pinned `pytest` to the header of a + student notebook that imports it without one. + """ + + if any(normalized_name(dep) == "pytest" for dep in read_header(nb.src).get("dependencies", [])): + return [] + + lines = [ + node.lineno + for node in ast.walk(ast.parse(nb.src)) + if isinstance(node, ast.Import) + and any(alias.name.split(".")[0] == "pytest" for alias in node.names) + or isinstance(node, ast.ImportFrom) + and (node.module or "").split(".")[0] == "pytest" + ] + + return [ + f"line {line}: the notebook imports `pytest`, but the header's `dependencies` doesn't " + "list it. Add `pytest` there, or marimo adds a pinned one to each student's header." + for line in lines[:1] + ] + + def _assignment_errors(nb: Notebook) -> list[str]: """The `assignment(...)` call sits alone in a plain cell, which the build drops.""" diff --git a/tests/test_source.py b/tests/test_source.py index 4fabe17..0b51cc3 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -1495,3 +1495,22 @@ def test_hidden_after_code_warns_that_it_hides_the_whole_cell(): ) def test_hidden_on_the_first_line_does_not_warn(cell): assert source_warnings(parse_notebook(nb(cell))) == [] + + +@pytest.mark.parametrize( + "statement", ["import pytest", "import pytest as pt", "from pytest import approx"] +) +def test_validate_pytest_import_needs_the_dependency(statement): + cell = f"\n@app.cell\ndef _():\n {statement}\n return\n" + + error = one_error(cell + PUBLIC + CHECK) + + assert "`pytest`" in error + assert "`dependencies`" in error + + +def test_validate_pytest_import_with_the_dependency_ok(): + header = HEADER.replace('dependencies = ["marimo"]', 'dependencies = ["marimo", "pytest>=8"]') + cell = "\n@app.cell\ndef _():\n import pytest\n return\n" + + assert errors(cell + PUBLIC + CHECK, header=header) == [] From 1997516c365322e63c130829089d902c576d015a Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:47:52 -0500 Subject: [PATCH 12/17] fix(build): warn when pytest on the notebook would skip a cell's tests marimo collects only cells that hold nothing but tests, so a hidden cell with data next to its tests runs on Gradescope but not under `pytest notebook.py`. --- docs/src/content/docs/instructors.md | 2 +- src/mogs/source.py | 30 +++++++++++++++++++++++++++- tests/test_source.py | 15 ++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/docs/src/content/docs/instructors.md b/docs/src/content/docs/instructors.md index be0d0e1..b9aef99 100644 --- a/docs/src/content/docs/instructors.md +++ b/docs/src/content/docs/instructors.md @@ -223,7 +223,7 @@ def _(): ``` The build removes this cell from the student notebook, and only Gradescope runs it. -A hidden cell can also hold data or helpers that the hidden tests need. +Data or helpers that the hidden tests need go in a hidden cell of their own: `pytest notebook.py` skips the tests in a cell that holds anything else. The question ends with a grade cell, which also sets its points: diff --git a/src/mogs/source.py b/src/mogs/source.py index f18366d..04eefae 100644 --- a/src/mogs/source.py +++ b/src/mogs/source.py @@ -692,13 +692,41 @@ def _returned_names(node: ast.stmt) -> set[str]: def source_warnings(nb: Notebook) -> list[str]: """Things in the notebook that build but may not do what the instructor meant.""" - return [ + late = [ f"line {cell.late_hidden}: `{HIDDEN}` hides the whole cell at line {cell.start}, not " "only the code after it. Move it to the cell's first line, or move the hidden tests " "to a cell of their own." for cell in nb.cells if cell.late_hidden is not None ] + uncollected = [ + f"line {cell.start}: `pytest` on the notebook skips {', '.join(cell.tests)}, since " + "marimo collects only cells that hold nothing but tests. Gradescope still runs them. " + "Move the other code to a cell of its own." + for cell in nb.cells + if cell.kind is CellKind.CELL and cell.tests and not _only_tests(nb, cell) + ] + + return late + uncollected + + +def _only_tests(nb: Notebook, cell: Cell) -> bool: + """Whether marimo's pytest plugin collects the cell: its body defines only `test*` names. + + Mirrors `contains_only_tests` in marimo's compiler, without pytest fixtures, which the + grader doesn't support. + """ + + for node in ast.parse(nb.cell_body_source(cell)).body: + match node: + case ast.FunctionDef() | ast.AsyncFunctionDef() | ast.ClassDef() if ( + node.name.lower().startswith("test") + ): + continue + case _: + return False + + return True def validate(nb: Notebook, cfg: AssignmentConfig) -> list[str]: diff --git a/tests/test_source.py b/tests/test_source.py index 0b51cc3..c891ad1 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -1497,6 +1497,21 @@ def test_hidden_on_the_first_line_does_not_warn(cell): assert source_warnings(parse_notebook(nb(cell))) == [] +def test_tests_next_to_other_code_warn_that_pytest_skips_them(): + cell = hidden_cell("expected = 7\n\ndef test_q1_h():\n assert expected == 7") + + [warning] = source_warnings(parse_notebook(nb(PUBLIC + CHECK + cell))) + + assert "test_q1_h" in warning + assert "pytest" in warning + + +def test_cell_of_only_tests_does_not_warn(): + cell = hidden_cell("def test_q1_h():\n assert True\n\nclass TestMore:\n pass") + + assert source_warnings(parse_notebook(nb(PUBLIC + CHECK + cell))) == [] + + @pytest.mark.parametrize( "statement", ["import pytest", "import pytest as pt", "from pytest import approx"] ) From 0aaa6eaeb62ec0bbf6f707990b4bce39b2d5e4f7 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 15:52:53 -0500 Subject: [PATCH 13/17] test: expect the new submission messages and answers name in grader tests --- tests/e2e/test_gradescope_docker.py | 2 +- tests/test_main.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/e2e/test_gradescope_docker.py b/tests/e2e/test_gradescope_docker.py index fff8117..d25f3fa 100644 --- a/tests/e2e/test_gradescope_docker.py +++ b/tests/e2e/test_gradescope_docker.py @@ -202,7 +202,7 @@ class Expect: "segfault": Expect(0, 6, shown="SIGSEGV"), "impure_fn": Expect(4, 6), "stdout_flood": Expect(4, 6), - "two_py": Expect(0, 0, notice="Found several notebooks"), + "two_py": Expect(0, 0, notice="several other `.py` files"), "nested_zip": Expect(4, 6), "macosx_zip": Expect(4, 6), "missing_pdf": Expect(4, 6, notice="No PDF"), diff --git a/tests/test_main.py b/tests/test_main.py index 94f333d..f2fa70b 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -110,13 +110,13 @@ def test_missing_pdf_gives_a_notice(paths): def test_markdown_answers_are_accepted_with_a_notice(paths): paths.add("solution.py") - paths.add("solution_answers.md", "Because.") + paths.add("Fixture_answers.md", "Because.") results = paths.run() first = results["tests"][0] assert first["name"] == "Submission" - assert "solution_answers.md" in first["output"] + assert "Fixture_answers.md" in first["output"] assert rows(results)["q2"]["score"] == 6 From 2bbdb2f8a4fa0f37b6f83640ae4d2971d634b29a Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 16:09:27 -0500 Subject: [PATCH 14/17] fix(grade): find a notebook named like a public test file --- src/mogs/grader/results.py | 4 ++-- tests/test_results.py | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/mogs/grader/results.py b/src/mogs/grader/results.py index db016f8..8522b13 100644 --- a/src/mogs/grader/results.py +++ b/src/mogs/grader/results.py @@ -82,9 +82,9 @@ def find_submission(sub_dir: Path, notebook: str, name: str | None = None) -> Su files = sorted(_regular_files(sub_dir)) scripts = [path for path in files if path.suffix == ".py"] - exact = [path for path in scripts if path.name == notebook] - # The public tests the student copy ships in `tests/`. + # Not the public tests the student copy ships in `tests/`. others = [path for path in scripts if path.parent.name != TESTS_FOLDER] + exact = [path for path in others if path.name == notebook] pdfs = [path for path in files if path.suffix.lower() == ".pdf"] fallback = f"{name or Path(notebook).stem}_answers.md".casefold() markdown = [path for path in files if path.name.casefold() == fallback] diff --git a/tests/test_results.py b/tests/test_results.py index 5476c56..2bb625a 100644 --- a/tests/test_results.py +++ b/tests/test_results.py @@ -191,6 +191,14 @@ def test_public_test_files_are_not_notebooks(tmp_path): assert found.py == tmp_path / "hw2" / "student_file.py" +def test_notebook_named_like_a_public_test_file_is_found(tmp_path): + touch(tmp_path, "hw/q1.py", "hw/tests/q1.py") + + found = find_submission(tmp_path, "q1.py") + + assert found.py == tmp_path / "hw" / "q1.py" + + def test_two_py_files_are_not_called_notebooks(tmp_path): touch(tmp_path, "one.py", "two.py") From 06b62296157daad620db71f989596527cfb4f435 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 16:09:27 -0500 Subject: [PATCH 15/17] fix(source): read the header only when the notebook imports pytest --- src/mogs/source.py | 23 +++++++++++++++++------ tests/test_source.py | 15 +++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/mogs/source.py b/src/mogs/source.py index 04eefae..5d6ed8d 100644 --- a/src/mogs/source.py +++ b/src/mogs/source.py @@ -18,6 +18,7 @@ ASSIGNMENT, Api, AssignmentConfig, + ConfigError, api_calls, normalize_newlines, normalized_name, @@ -837,9 +838,6 @@ def _pytest_dependency_errors(nb: Notebook) -> list[str]: student notebook that imports it without one. """ - if any(normalized_name(dep) == "pytest" for dep in read_header(nb.src).get("dependencies", [])): - return [] - lines = [ node.lineno for node in ast.walk(ast.parse(nb.src)) @@ -849,10 +847,23 @@ def _pytest_dependency_errors(nb: Notebook) -> list[str]: and (node.module or "").split(".")[0] == "pytest" ] + if not lines: + return [] + + try: + dependencies = read_header(nb.src).get("dependencies", []) + except ConfigError as error: + return [ + f"line {lines[0]}: the notebook imports `pytest`, but its header is unreadable: {error}" + ] + + if any(normalized_name(dep) == "pytest" for dep in dependencies): + return [] + return [ - f"line {line}: the notebook imports `pytest`, but the header's `dependencies` doesn't " - "list it. Add `pytest` there, or marimo adds a pinned one to each student's header." - for line in lines[:1] + f"line {lines[0]}: the notebook imports `pytest`, but the header's `dependencies` " + "doesn't list it. Add `pytest` there, or marimo adds a pinned one to each student's " + "header." ] diff --git a/tests/test_source.py b/tests/test_source.py index c891ad1..ebf7871 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -1524,6 +1524,21 @@ def test_validate_pytest_import_needs_the_dependency(statement): assert "`dependencies`" in error +BAD_HEADER = HEADER.replace('dependencies = ["marimo"]', "dependencies = [") + + +def test_validate_does_not_read_a_broken_header_without_pytest_imports(): + assert errors(PUBLIC + CHECK, header=BAD_HEADER) == [] + + +def test_validate_reports_a_broken_header_when_pytest_is_imported(): + cell = "\n@app.cell\ndef _():\n import pytest\n return\n" + + error = one_error(cell + PUBLIC + CHECK, header=BAD_HEADER) + + assert "header" in error + + def test_validate_pytest_import_with_the_dependency_ok(): header = HEADER.replace('dependencies = ["marimo"]', 'dependencies = ["marimo", "pytest>=8"]') cell = "\n@app.cell\ndef _():\n import pytest\n return\n" From cadf03fc53df16bd10f27247ad898a50a07e2260 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 16:09:38 -0500 Subject: [PATCH 16/17] fix(pdf): keep math symbols when matching a prompt heading to the title --- src/mogs/pdf.py | 8 ++++++-- tests/test_pdf.py | 6 +++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/mogs/pdf.py b/src/mogs/pdf.py index 823bbbb..ae135a6 100644 --- a/src/mogs/pdf.py +++ b/src/mogs/pdf.py @@ -361,9 +361,13 @@ def without_title_heading(text: str, title: str) -> str: def _words(text: str) -> str: - """The words of `text` in lower case, each with a space on both sides: ` question 4 `.""" + """The words and symbols of `text` in lower case, spaced: `x + y.` → ` x + y `. - return f" {' '.join(re.findall(r'\w+', text.casefold()))} " + Sentence punctuation is dropped, so `Question 4:` matches `Question 4`; other symbols, such + as `+` and `-` in math, are kept. + """ + + return f" {' '.join(re.findall(r'\w+|[^\w\s.,:;!?]', text.casefold()))} " def cell_markdown(nb: Notebook, cell: Cell) -> str: diff --git a/tests/test_pdf.py b/tests/test_pdf.py index 35f82af..8ee9928 100644 --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -234,7 +234,11 @@ def test_prompt_heading_the_title_already_says_is_dropped(tmp_path, title, headi @pytest.mark.parametrize( ("title", "heading"), - [("Question 4", "Question 4: Derive the slope"), ("Question 10", "Question 1")], + [ + ("Question 4", "Question 4: Derive the slope"), + ("Question 10", "Question 1"), + ("Question 4: x + y", "x - y"), + ], ) def test_prompt_heading_with_more_than_the_title_stays(tmp_path, title, heading): reader = render( From 4238d823d5356fb98622a9e132bf2052715a1d5c Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 16:16:27 -0500 Subject: [PATCH 17/17] fix(grade): skip tests/ files only when they sit next to a notebook --- src/mogs/grader/results.py | 16 +++++++++++----- tests/test_results.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/mogs/grader/results.py b/src/mogs/grader/results.py index 8522b13..faad8a9 100644 --- a/src/mogs/grader/results.py +++ b/src/mogs/grader/results.py @@ -66,9 +66,10 @@ def find_submission(sub_dir: Path, notebook: str, name: str | None = None) -> Su """Find the notebook and the written answers anywhere under `sub_dir`. Skips `__MACOSX`, `__pycache__`, dot files and dot folders, and never follows or picks a - symlink. A file named `notebook` wins; otherwise the only `.py` file outside a `tests/` - folder is taken. Any PDF counts as the written answers. Of Markdown files, only the - export's fallback `_answers.md` (any case) does, so a stray `README.md` does not. + symlink. Public tests, the `.py` files in a `tests/` folder next to another `.py` file, are + never the notebook. Of the rest, a file named `notebook` wins; otherwise the only `.py` file + is taken. Any PDF counts as the written answers. Of Markdown files, only the export's + fallback `_answers.md` (any case) does, so a stray `README.md` does not. Args: sub_dir: The unpacked upload. @@ -82,8 +83,13 @@ def find_submission(sub_dir: Path, notebook: str, name: str | None = None) -> Su files = sorted(_regular_files(sub_dir)) scripts = [path for path in files if path.suffix == ".py"] - # Not the public tests the student copy ships in `tests/`. - others = [path for path in scripts if path.parent.name != TESTS_FOLDER] + # Not the public tests the student copy ships in `tests/`, next to the notebook. + folders = {path.parent for path in scripts} + others = [ + path + for path in scripts + if path.parent.name != TESTS_FOLDER or path.parent.parent not in folders + ] exact = [path for path in others if path.name == notebook] pdfs = [path for path in files if path.suffix.lower() == ".pdf"] fallback = f"{name or Path(notebook).stem}_answers.md".casefold() diff --git a/tests/test_results.py b/tests/test_results.py index 2bb625a..5fe456b 100644 --- a/tests/test_results.py +++ b/tests/test_results.py @@ -199,6 +199,20 @@ def test_notebook_named_like_a_public_test_file_is_found(tmp_path): assert found.py == tmp_path / "hw" / "q1.py" +def test_assignment_named_tests_is_found(tmp_path): + touch(tmp_path, "tests/hw.py", "tests/tests/q1.py") + + found = find_submission(tmp_path, "hw.py") + + assert found.py == tmp_path / "tests" / "hw.py" + + +def test_lone_tests_folder_still_counts(tmp_path): + touch(tmp_path, "tests/my_homework.py") + + assert find_submission(tmp_path, "hw.py").py == tmp_path / "tests" / "my_homework.py" + + def test_two_py_files_are_not_called_notebooks(tmp_path): touch(tmp_path, "one.py", "two.py")