From 7175ec5e4f6dae3926b7d7116a01519437d98de9 Mon Sep 17 00:00:00 2001
From: Nessar
Date: Thu, 26 Nov 2026 15:55:55 +0100
Subject: [PATCH] Mock: Ctrl+C asks before ending and saves; validate accepts
finished exercises
A Ctrl+C during a mock threw away every answer. Ctrl+C now asks
"End the exam now? [y/N]"; yes (or a second Ctrl+C) ends the exam and
saves the answers given so far, as 'q' does. The marker check in
validate and test_repo skips exercises the learner has finished.
Co-Authored-By: Claude Opus 5.5
---
awslings/cli.py | 2 +-
awslings/quiz.py | 20 +++++++++++++++++---
tests/test_quiz_cli.py | 27 ++++++++++++++++++++++++---
tests/test_repo.py | 3 ++-
4 files changed, 44 insertions(+), 8 deletions(-)
diff --git a/awslings/cli.py b/awslings/cli.py
index 3a9e562..f13cdeb 100644
--- a/awslings/cli.py
+++ b/awslings/cli.py
@@ -286,7 +286,7 @@ def cmd_validate(root, exercises, state, args) -> int:
problems.append(f"info.toml: {e.name}: missing solution {e.solution.relative_to(root)}")
elif ex_mod.tests_section(e.source()) != ex_mod.tests_section(e.solution.read_text(encoding="utf-8")):
problems.append(f"{e.name}: tests section differs between exercise and solution")
- if not e.has_marker():
+ if not e.has_marker() and not state.is_done(e): # finished exercises lose their marker
problems.append(f"{e.name}: exercise file has no `# I AM NOT DONE` marker")
if not e.hint:
problems.append(f"{e.name}: missing hint")
diff --git a/awslings/quiz.py b/awslings/quiz.py
index 110c087..f73b62d 100644
--- a/awslings/quiz.py
+++ b/awslings/quiz.py
@@ -421,6 +421,20 @@ def run_quiz(root: Path, questions: list[Question], mode: str = "quiz") -> dict:
return _finish(root, session, mode, entries, questions)
+def _mock_input(prompt: str) -> str:
+ """input() for a mock: Ctrl+C asks before ending, so one keystroke cannot throw the answers away."""
+ while True:
+ try:
+ return input(prompt)
+ except KeyboardInterrupt:
+ try:
+ sure = input(ui.yellow("\nEnd the exam now? Your answers so far will be saved. [y/N] "))
+ except (KeyboardInterrupt, EOFError):
+ sure = "y"
+ if sure.strip().lower().startswith("y"):
+ return "q"
+
+
def run_mock(root: Path, questions: list[Question], minutes: int = EXAM_MINUTES, timer: bool = True) -> dict:
"""Exam simulation: no feedback until the end, flag for review, time limit."""
session = uuid.uuid4().hex[:8]
@@ -449,7 +463,7 @@ def run_mock(root: Path, questions: list[Question], minutes: int = EXAM_MINUTES,
if deadline is not None and time.monotonic() > deadline:
print(ui.red("Time is up!"))
return False
- raw = input(ui.cyan("Your answer: ")).strip()
+ raw = _mock_input(ui.cyan("Your answer: ")).strip()
if raw.lower() in ("q", "quit", "exit"):
return False
if not raw and current:
@@ -483,8 +497,8 @@ def run_mock(root: Path, questions: list[Question], minutes: int = EXAM_MINUTES,
while not stopped and flagged and (deadline is None or time.monotonic() < deadline):
print(ui.rule())
print(ui.yellow(f"{len(flagged)} question(s) flagged for review."))
- choice = input(ui.cyan("Review flagged questions now? [Y/n] ")).strip().lower()
- if choice.startswith("n"):
+ choice = _mock_input(ui.cyan("Review flagged questions now? [Y/n] ")).strip().lower()
+ if choice.startswith(("n", "q")):
break
for i, q in enumerate(questions, 1):
if q.id in flagged:
diff --git a/tests/test_quiz_cli.py b/tests/test_quiz_cli.py
index a8add3a..4f8dda0 100644
--- a/tests/test_quiz_cli.py
+++ b/tests/test_quiz_cli.py
@@ -321,9 +321,8 @@ def test_run_mock_returns_the_summary_when_the_review_is_interrupted(tmp_path, m
assert summary["type"] == "summary" and summary == _summaries(tmp_path)[0]
-@pytest.mark.parametrize("error", [EOFError, KeyboardInterrupt])
-def test_interrupt_during_the_exam_is_not_saved(tmp_path, monkeypatch, capsys, small_bank, error):
- feed(monkeypatch, "A", error)
+def test_eof_during_the_exam_is_not_saved(tmp_path, monkeypatch, capsys, small_bank):
+ feed(monkeypatch, "A", EOFError) # Ctrl+D; Ctrl+C now asks first, see test_mock_ctrl_c_*
assert cli.cmd_mock(tmp_path, [], None, _mock_args(4)) == 0
assert "Mock exam interrupted (not saved)." in capsys.readouterr().out
assert quiz_mod.read_history(tmp_path) == []
@@ -388,3 +387,25 @@ def test_stats_after_an_early_quit_mock(tmp_path, monkeypatch):
assert "Answers recorded: 1 ยท overall accuracy 100%" in text
assert "Bank coverage: 1/4 questions seen." in text
assert "incomplete: 1/4 answered" in text
+
+
+def test_mock_ctrl_c_then_no_keeps_going(tmp_path, monkeypatch):
+ qs = [_question("t-1"), _question("t-2")]
+ feed(monkeypatch, "A", KeyboardInterrupt, "n", "A")
+ summary = quiz_mod.run_mock(tmp_path, qs, timer=False)
+ assert summary["answered"] == 2 and summary["completed"] is True
+
+
+def test_mock_ctrl_c_then_yes_ends_and_saves_the_answers(tmp_path, monkeypatch):
+ qs = [_question(f"t-{i}") for i in range(1, 4)]
+ feed(monkeypatch, "A", "A", KeyboardInterrupt, "y")
+ summary = quiz_mod.run_mock(tmp_path, qs, timer=False)
+ assert [e["qid"] for e in _answers(tmp_path)] == ["t-1", "t-2"]
+ assert summary["answered"] == 2 and summary["completed"] is False
+
+
+def test_mock_double_ctrl_c_ends_and_saves(tmp_path, monkeypatch):
+ qs = [_question("t-1"), _question("t-2", answer=("B",))]
+ feed(monkeypatch, "A", "B f", KeyboardInterrupt, KeyboardInterrupt) # Ctrl+C at the flagged-review prompt
+ summary = quiz_mod.run_mock(tmp_path, qs, timer=False)
+ assert summary["answered"] == 2 and summary["completed"] is True
diff --git a/tests/test_repo.py b/tests/test_repo.py
index 760f09e..64a624c 100644
--- a/tests/test_repo.py
+++ b/tests/test_repo.py
@@ -9,6 +9,7 @@ from awslings.exercises import MARKER_RE, find_root, load_exercises
ROOT = find_root(Path(__file__).parent)
EXERCISES = load_exercises(ROOT)
+STATE = ex_mod.State(ROOT) # the learner's finished exercises legitimately have no marker
NAMES = {e.name for e in EXERCISES}
BOOK = sorted((ROOT / "book" / "src").glob("*.md"))
@@ -18,7 +19,7 @@ def test_exercises_and_solutions_are_consistent():
for e in EXERCISES:
assert e.path.is_file(), e.rel
assert e.solution.is_file(), e.name
- assert MARKER_RE.search(e.source()), f"{e.name}: missing marker"
+ assert MARKER_RE.search(e.source()) or STATE.is_done(e), f"{e.name}: missing marker"
assert not MARKER_RE.search(e.solution.read_text(encoding="utf-8")), f"{e.name}: solution has the marker"
assert ex_mod.tests_section(e.source()) == ex_mod.tests_section(e.solution.read_text(encoding="utf-8")), e.name
assert e.hint, f"{e.name}: missing hint"
--
2.54.0