From 056c7199b5ca0dad289d76875f9f8b8e8dbb3337 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Sun, 27 Sep 2026 05:49:59 +0330 Subject: [PATCH] add final-exam --- README.md | 38 ++++++++- public/assets/app.js | 19 ++++- src/ravin/assessments.py | 165 ++++++++++++++++++++++++++++++++++++++ src/ravin/cli.py | 11 ++- src/ravin/questions.py | 69 ++++++++++------ src/ravin/scan.py | 34 +++++++- src/ravin/wizard.py | 13 ++- tests/test_assessments.py | 154 +++++++++++++++++++++++++++++++++++ 8 files changed, 460 insertions(+), 43 deletions(-) create mode 100644 src/ravin/assessments.py create mode 100644 tests/test_assessments.py diff --git a/README.md b/README.md index c9c591a..e2b1c43 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,38 @@ Use `--public PATH` for another library root, `--timeout SECONDS` for slow serve ## Exam questions and answers +Final exams can be declared independently of Moodle in +`public/courses/COURSE_ID/assessments.json`. This keeps exams visible when Moodle hides the +quiz activity and preserves them across later online scans. A local exam may optionally set +`activity_id` to link it to a Moodle quiz: + +```json +{ + "schema_version": 1, + "assessments": [ + { + "id": "final-exam", + "type": "final", + "title": "Final exam", + "status": "ended", + "activity_id": 6126 + } + ] +} +``` + +Supported statuses are `upcoming`, `active`, `ended`, and `unavailable`. Only ended exams +may receive published questions and answers. Do not place active exam material anywhere +under `public/`: hiding it in the interface would not prevent direct access to the file. + +Unlinked local exam material is stored in a stable course-level bundle: + +```text +public/courses/44/assessments/final-exam/ +├── files/ +└── artifacts/questions.fa.md +``` + Start the interactive import wizard: ```bash @@ -199,7 +231,8 @@ The wizard: 3. Prompts for the UTF-8 Markdown questions-and-answers file. 4. Prompts for an optional original exam PDF. -You can enter either a displayed list number or the actual course/activity ID. File paths can be pasted or dragged into the terminal. +You can enter either a displayed list number, a Moodle activity ID, or a local assessment ID +such as `final-exam`. File paths can be pasted or dragged into the terminal. For scripting, all values can still be passed directly: @@ -403,7 +436,7 @@ ravin scan [COURSE_ID ...] [--offline] [--json] [--public PATH] ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH] ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE] ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS] -ravin questions [COURSE_ID] [ACTIVITY_ID] [QUESTIONS.md] [--file ATTACHMENT ...] +ravin questions [COURSE_ID] [ACTIVITY_OR_ASSESSMENT_ID] [QUESTIONS.md] [--file ATTACHMENT ...] ravin recording [COURSE_ID] [ACTIVITY_ID] [VIDEO] ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH] ravin import URL [--timeout SECONDS] [--json] [--public PATH] @@ -428,6 +461,7 @@ src/ravin/ ├── transcribe.py # resilient manifest-driven Whisper batches ├── summarize.py # resilient Codex CLI study-guide batches ├── questions.py # local exam-question and attachment imports +├── assessments.py # durable course-level exam overlays ├── recordings.py # local live-class recording imports ├── exporter.py # atomic course ZIP exports ├── importer.py # safe URL restores and mirror updates diff --git a/public/assets/app.js b/public/assets/app.js index bb7b014..b1fe044 100644 --- a/public/assets/app.js +++ b/public/assets/app.js @@ -255,6 +255,13 @@ function resourceMatches(item) { } function resourceRow(item, index) { + const assessmentLabels = { + upcoming: "Upcoming", + active: "In progress", + ended: "Ended", + unavailable: "Not yet available", + }; + const assessmentLabel = assessmentLabels[item.assessment_status] || ""; const row = document.createElement("article"); row.className = `resource-row${isComplete(item) ? " completed" : ""}`; const number = document.createElement("span"); @@ -272,7 +279,7 @@ function resourceRow(item, index) { const filename = document.createElement("span"); filename.className = "resource-file"; filename.dir = "auto"; - filename.textContent = item.filename || item.badge || item.activity_type; + filename.textContent = item.filename || assessmentLabel || item.badge || item.activity_type; fileLine.append(filename); if ((item.file_versions || []).some((version) => version.state === "current")) { const currentBadge = document.createElement("span"); @@ -366,15 +373,19 @@ function resourceRow(item, index) { const dot = document.createElement("span"); dot.className = `status-dot${item.status === "missing" ? " missing" : item.status === "online" ? " online" : ""}`; const size = document.createElement("span"); - size.textContent = item.status === "partial" + size.textContent = assessmentLabel || (item.status === "partial" ? `${formatBytes(item.local_bytes)} partial` : item.status === "online" ? (item.lms_completed ? "LMS complete" : "Online") - : formatBytes(item.size); + : formatBytes(item.size)); meta.append(type, dot, size); let action; - if (item.status === "downloaded" && item.kind === "video") { + if (item.kind === "assessment" && ["upcoming", "active", "unavailable"].includes(item.assessment_status)) { + action = document.createElement("span"); + action.textContent = assessmentLabel; + action.setAttribute("aria-disabled", "true"); + } else if (item.status === "downloaded" && item.kind === "video") { action = document.createElement("button"); action.type = "button"; action.textContent = "Play"; diff --git a/src/ravin/assessments.py b/src/ravin/assessments.py new file mode 100644 index 0000000..8b11435 --- /dev/null +++ b/src/ravin/assessments.py @@ -0,0 +1,165 @@ +"""Course-level assessment overlays that survive LMS scans.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any + +from .models import MoodleError +from .paths import _read_json_object + + +ASSESSMENT_ID_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") +ASSESSMENT_STATUSES = {"upcoming", "active", "ended", "unavailable"} + + +def assessment_directory(public: Path, course_id: int, assessment_id: str) -> Path: + if not ASSESSMENT_ID_PATTERN.fullmatch(assessment_id): + raise MoodleError(f"invalid assessment ID: {assessment_id!r}") + return public / "courses" / str(course_id) / "assessments" / assessment_id + + +def load_assessments(public: Path, course_id: int) -> list[dict[str, Any]]: + path = public / "courses" / str(course_id) / "assessments.json" + if not path.exists(): + return [] + payload = _read_json_object(path) + raw_assessments = payload.get("assessments") + if not isinstance(raw_assessments, list): + raise MoodleError(f"invalid assessments file: {path}") + + assessments: list[dict[str, Any]] = [] + seen: set[str] = set() + for raw in raw_assessments: + if not isinstance(raw, dict): + raise MoodleError(f"invalid assessment entry in {path}") + assessment_id = str(raw.get("id") or "") + if not ASSESSMENT_ID_PATTERN.fullmatch(assessment_id): + raise MoodleError(f"invalid assessment ID in {path}: {assessment_id!r}") + if assessment_id in seen: + raise MoodleError(f"duplicate assessment ID in {path}: {assessment_id}") + seen.add(assessment_id) + status = str(raw.get("status") or "unavailable") + if status not in ASSESSMENT_STATUSES: + raise MoodleError(f"invalid status for assessment {assessment_id}: {status!r}") + title = str(raw.get("title") or "").strip() + if not title: + raise MoodleError(f"assessment {assessment_id} has no title in {path}") + assessment = dict(raw) + assessment.update({"id": assessment_id, "title": title, "status": status}) + assessments.append(assessment) + return assessments + + +def _remove_previous_overlay(course: dict[str, Any]) -> None: + retained_sections: list[dict[str, Any]] = [] + for section in course.get("sections", []): + if not isinstance(section, dict): + continue + if section.get("assessment_source") == "overlay": + continue + retained_items: list[dict[str, Any]] = [] + for item in section.get("items", []): + if not isinstance(item, dict): + continue + if item.get("assessment_source") == "overlay": + item = dict(item) + for key in ( + "assessment_id", "assessment_type", "assessment_status", "assessment_source", + ): + item.pop(key, None) + if item.get("activity_type") == "quiz": + item["kind"] = "quiz" + retained_items.append(item) + section["items"] = retained_items + retained_sections.append(section) + course["sections"] = retained_sections + + +def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]: + """Merge a course's durable local assessment metadata into its activity tree.""" + course_id = int(course.get("id") or 0) + if course_id <= 0: + return course + _remove_previous_overlay(course) + assessments = load_assessments(public, course_id) + if not assessments: + return course + + sections = course.setdefault("sections", []) + synthetic_items: list[dict[str, Any]] = [] + for position, assessment in enumerate(assessments, start=1): + linked: dict[str, Any] | None = None + activity_id = assessment.get("activity_id") + if activity_id is not None: + try: + resolved_activity_id = int(activity_id) + except (TypeError, ValueError) as exc: + raise MoodleError( + f"invalid activity ID for assessment {assessment['id']}: {activity_id!r}" + ) from exc + for section in sections: + for item in section.get("items", []): + if int(item.get("activity_id") or 0) == resolved_activity_id: + linked = item + break + if linked is not None: + break + if linked is None: + raise MoodleError( + f"assessment {assessment['id']} links to missing activity {resolved_activity_id} " + f"in course {course_id}" + ) + + common = { + "assessment_id": assessment["id"], + "assessment_type": str(assessment.get("type") or "exam"), + "assessment_status": assessment["status"], + "assessment_source": "overlay", + "kind": "assessment", + "badge": str(assessment.get("badge") or "Final exam"), + } + if linked is not None: + linked.update(common) + linked["title"] = assessment["title"] + if assessment.get("description") is not None: + linked["description"] = str(assessment["description"]) + continue + + synthetic_items.append( + { + "id": f"assessment-{assessment['id']}", + "section": "Exams", + "section_id": None, + "section_number": None, + "activity_id": None, + "activity_position": position, + "activity_type": "assessment", + "title": assessment["title"], + "description": str(assessment.get("description") or ""), + "filename": "", + "extension": "", + "mimetype": "", + "source_url": course.get("source_url"), + "lms_completed": None, + **common, + } + ) + + if synthetic_items: + sections.append( + { + "id": "local-assessments", + "number": None, + "position": len(sections) + 1, + "name": "Exams", + "summary": "", + "activity_count": len(synthetic_items), + "assessment_source": "overlay", + "items": synthetic_items, + } + ) + course["section_count"] = len(sections) + course["activity_count"] = sum(len(section.get("items", [])) for section in sections) + return course diff --git a/src/ravin/cli.py b/src/ravin/cli.py index 85767de..cef3c17 100644 --- a/src/ravin/cli.py +++ b/src/ravin/cli.py @@ -29,6 +29,10 @@ from .summarize import SummaryOptions, format_summary_result, summarize_courses from .transcribe import TranscriptionOptions, format_transcription_result, transcribe_courses +def _assessment_reference(value: str) -> int | str: + return int(value) if value.isdigit() else value + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Scan and download your Ravin Academy Moodle courses.") parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}") @@ -145,7 +149,12 @@ def build_parser() -> argparse.ArgumentParser: description="Import exam questions with a course-and-quiz wizard; all positional values are optional.", ) questions_parser.add_argument("course_id", nargs="?", type=int, help="course containing the quiz") - questions_parser.add_argument("activity_id", nargs="?", type=int, help="Moodle quiz activity ID") + questions_parser.add_argument( + "activity_id", + nargs="?", + type=_assessment_reference, + help="Moodle quiz activity ID or local assessment ID", + ) questions_parser.add_argument("questions", nargs="?", type=Path, help="UTF-8 Markdown questions and answers") questions_parser.add_argument( "--file", diff --git a/src/ravin/questions.py b/src/ravin/questions.py index 11420bb..72c4e3d 100644 --- a/src/ravin/questions.py +++ b/src/ravin/questions.py @@ -10,15 +10,15 @@ from typing import Any, Callable, TextIO from .local_files import atomic_copy from .models import MoodleError -from .paths import _activity_directory_name, _clean_name, _read_json_object -from .scan import _atomic_json, _manifest_lock, scan_offline +from .paths import _clean_name, _read_json_object +from .scan import _activity_directory, _atomic_json, _manifest_lock, scan_offline from .wizard import prompt, prompt_path, select_number @dataclass(frozen=True) class QuestionsImportResult: course_id: int - activity_id: int + activity_id: int | str activity_key: str activity_title: str questions: str @@ -46,8 +46,8 @@ def _course_choices(public: Path) -> list[tuple[int, str, dict[str, Any]]]: return choices -def _quiz_choices(course: dict[str, Any]) -> list[tuple[int, str, str, str]]: - choices: list[tuple[int, str, str, str]] = [] +def _quiz_choices(course: dict[str, Any]) -> list[tuple[int | str, str, str, str]]: + choices: list[tuple[int | str, str, str, str]] = [] for section in course.get("sections", []): if not isinstance(section, dict): continue @@ -58,18 +58,19 @@ def _quiz_choices(course: dict[str, Any]) -> list[tuple[int, str, str, str]]: if item.get("activity_type") != "quiz" and item.get("kind") != "assessment": continue activity_id = int(item.get("activity_id") or 0) - if not activity_id: + reference: int | str = str(item.get("assessment_id") or "") or activity_id + if not reference: continue - title = str(item.get("title") or f"Quiz {activity_id}") + title = str(item.get("title") or f"Quiz {reference}") status = str(item.get("state", {}).get("questions") or "missing") - choices.append((activity_id, title, section_title, status)) + choices.append((reference, title, section_title, status)) return choices def questions_wizard( public: Path, course_id: int | None = None, - activity_id: int | None = None, + activity_id: int | str | None = None, questions_path: Path | None = None, attachment_paths: tuple[Path, ...] = (), *, @@ -100,8 +101,10 @@ def questions_wizard( if activity_id is None: print("\nExams:", file=output) for index, (candidate_id, title, section_title, status) in enumerate(quizzes, start=1): + reference_label = "activity" if isinstance(candidate_id, int) else "assessment" print( - f" [{index}] {title} (activity {candidate_id}, section: {section_title}, questions: {status})", + f" [{index}] {title} ({reference_label} {candidate_id}, " + f"section: {section_title}, questions: {status})", file=output, ) activity_id = select_number(quizzes, "Select an exam: ", input_func, output) @@ -164,28 +167,41 @@ def _attachment_sources(paths: tuple[Path, ...]) -> tuple[Path, ...]: return tuple(sources) -def _find_activity(course: dict[str, Any], activity_id: int) -> tuple[dict[str, Any], dict[str, Any]]: +def _find_activity( + course: dict[str, Any], + activity_id: int | str, +) -> tuple[dict[str, Any], dict[str, Any]]: matches: list[tuple[dict[str, Any], dict[str, Any]]] = [] + local_reference = str(activity_id) if isinstance(activity_id, str) and not activity_id.isdigit() else "" + numeric_reference = int(activity_id) if not local_reference else 0 for section in course.get("sections", []): if not isinstance(section, dict): continue for item in section.get("items", []): - if isinstance(item, dict) and int(item.get("activity_id") or 0) == activity_id: + if not isinstance(item, dict): + continue + if local_reference and str(item.get("assessment_id") or "") == local_reference: matches.append((section, item)) + elif numeric_reference and int(item.get("activity_id") or 0) == numeric_reference: + matches.append((section, item)) + reference_label = "assessment" if local_reference else "activity" if not matches: - raise MoodleError(f"activity {activity_id} was not found in course {course.get('id')}; run `ravin scan` first") + raise MoodleError( + f"{reference_label} {activity_id} was not found in course {course.get('id')}; " + "run `ravin scan` first" + ) if len(matches) > 1: - raise MoodleError(f"activity {activity_id} appears more than once in the course manifest") + raise MoodleError(f"{reference_label} {activity_id} appears more than once in the course manifest") section, item = matches[0] if item.get("activity_type") != "quiz" and item.get("kind") != "assessment": - raise MoodleError(f"activity {activity_id} is not a quiz or assessment") + raise MoodleError(f"{reference_label} {activity_id} is not a quiz or assessment") return section, item def import_questions( public: Path, course_id: int, - activity_id: int, + activity_id: int | str, questions_path: Path, attachment_paths: tuple[Path, ...] = (), ) -> QuestionsImportResult: @@ -199,12 +215,14 @@ def import_questions( if not isinstance(course, dict): raise MoodleError(f"course manifest not found: {manifest_path}; run `ravin scan {course_id}` first") section, item = _find_activity(course, activity_id) - key = str(item.get("key") or "") or _activity_directory_name( - item.get("section_number", section.get("number")), - item.get("activity_position"), - activity_id, - ) - activity_directory = public / "courses" / str(course_id) / "content" / key + assessment_status = str(item.get("assessment_status") or "") + if assessment_status in {"upcoming", "active", "unavailable"}: + raise MoodleError( + f"assessment {activity_id} is {assessment_status}; publish questions only after it has ended" + ) + activity_directory = _activity_directory(public, course_id, section, item) + key = str(item["key"]) + bundle_path = str(item["bundle_path"]) questions_destination = activity_directory / "artifacts" / "questions.fa.md" atomic_copy(questions_source, questions_destination) @@ -218,7 +236,7 @@ def import_questions( # and its primary attachment immediately. A later remote scan will merge the # same bundle through its stable activity ID. item["key"] = key - item["bundle_path"] = f"content/{key}" + item["bundle_path"] = bundle_path item["kind"] = "assessment" if copied_files: primary = activity_directory / "files" / copied_files[0] @@ -232,11 +250,12 @@ def import_questions( current_course = current.get("course") if not isinstance(current_course, dict): raise MoodleError(f"course manifest changed while importing questions: {manifest_path}") - _current_section, current_item = _find_activity(current_course, activity_id) + current_section, current_item = _find_activity(current_course, activity_id) + _activity_directory(public, course_id, current_section, current_item) current_item.update( { "key": key, - "bundle_path": f"content/{key}", + "bundle_path": bundle_path, "kind": "assessment", } ) diff --git a/src/ravin/scan.py b/src/ravin/scan.py index bbf08a4..299d9ec 100644 --- a/src/ravin/scan.py +++ b/src/ravin/scan.py @@ -10,6 +10,7 @@ from datetime import datetime, timezone from pathlib import Path from typing import Any, Iterable +from .assessments import assessment_directory, merge_assessments from .catalog import _build_library_catalog from .client import MoodleClient from .constants import LIVE_CLASS_MODULES @@ -42,6 +43,12 @@ def _atomic_json(path: Path, value: dict[str, Any]) -> None: def _activity_directory(public: Path, course_id: int, section: dict[str, Any], item: dict[str, Any]) -> Path: + assessment_id = item.get("assessment_id") + if assessment_id: + directory = assessment_directory(public, course_id, str(assessment_id)) + item["key"] = f"assessment--{assessment_id}" + item["bundle_path"] = f"assessments/{assessment_id}" + return directory key = _activity_directory_name( item.get("section_number", section.get("number")), item.get("activity_position"), @@ -216,6 +223,7 @@ def _file_versions( def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: + course = merge_assessments(public, course) course_id = int(course.get("id") or 0) downloaded_bytes = 0 type_counts: dict[str, int] = {} @@ -228,7 +236,12 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: "downloads": category_counts(), "transcripts": category_counts(), "summaries": category_counts(), - "assessments": category_counts(), + "assessments": { + **category_counts(), + "upcoming": 0, + "active": 0, + "unavailable": 0, + }, "recordings": category_counts(), "partial": 0, "stale": 0, @@ -259,7 +272,13 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: and summary_state == "complete" ): summary_state = "stale" - questions_state = _artifact_state(activity_directory, "questions", assessment_applicable) + assessment_status = str(item.get("assessment_status") or "") + questions_publishable = assessment_status not in {"upcoming", "active", "unavailable"} + questions_state = _artifact_state( + activity_directory, + "questions", + assessment_applicable and questions_publishable, + ) for value in (download_state, transcript_state, summary_state, questions_state): if value not in STATE_VALUES: raise MoodleError(f"invalid manifest state {value!r}") @@ -278,6 +297,8 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: else download_state ) item["artifacts"] = _discover_artifacts(activity_directory, public) + if assessment_applicable and not questions_publishable: + item["artifacts"].pop("questions", None) versioned_activity = ( item.get("activity_type") == "resource" or item.get("activity_type") in LIVE_CLASS_MODULES @@ -305,7 +326,10 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: state_counts["summaries"][summary_state] += 1 if assessment_applicable: state_counts["assessments"]["total"] += 1 - state_counts["assessments"][questions_state] += 1 + if assessment_status in {"upcoming", "active", "unavailable"}: + state_counts["assessments"][assessment_status] += 1 + else: + state_counts["assessments"][questions_state] += 1 if recording_applicable: recording_state = download_state if download_state != "not_applicable" else "missing" state_counts["recordings"]["total"] += 1 @@ -472,7 +496,7 @@ def format_scan(catalog: dict[str, Any]) -> str: total = int(state.get("total") or 0) details = [ f"{int(state.get(value) or 0)} {value}" - for value in ("missing", "partial", "stale", "error") + for value in ("missing", "partial", "stale", "error", "upcoming", "active", "unavailable") if int(state.get(value) or 0) ] suffix = f" · {', '.join(details)}" if details else "" @@ -482,6 +506,8 @@ def format_scan(catalog: dict[str, Any]) -> str: def pending(name: str) -> int: state = course[name] + if name == "assessments": + return sum(int(state.get(value) or 0) for value in ("missing", "partial", "stale", "error")) return max(int(state.get("total") or 0) - int(state.get("complete") or 0), 0) def quantity(value: int, singular: str, plural: str | None = None) -> str: diff --git a/src/ravin/wizard.py b/src/ravin/wizard.py index 08e1cce..e105354 100644 --- a/src/ravin/wizard.py +++ b/src/ravin/wizard.py @@ -34,17 +34,16 @@ def select_number( prompt_message: str, input_func: Callable[[str], str], output: TextIO, -) -> int: - valid_ids = {int(choice[0]) for choice in choices} +) -> Any: + valid_ids = {str(choice[0]): choice[0] for choice in choices} while True: value = prompt(input_func, prompt_message) try: selected = int(value) except ValueError: - print("Please enter a list number or ID.", file=output) - continue + selected = 0 if 1 <= selected <= len(choices): - return int(choices[selected - 1][0]) - if selected in valid_ids: - return selected + return choices[selected - 1][0] + if value in valid_ids: + return valid_ids[value] print("That selection is not in the list. Please try again.", file=output) diff --git a/tests/test_assessments.py b/tests/test_assessments.py new file mode 100644 index 0000000..2b8423b --- /dev/null +++ b/tests/test_assessments.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from ravin.models import MoodleError +from ravin.questions import import_questions +from ravin.scan import scan_offline + + +class CourseAssessmentTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory() + self.public = Path(self.temporary_directory.name) / "public" + + def tearDown(self) -> None: + self.temporary_directory.cleanup() + + def write_course(self, course_id: int, items: list[dict] | None = None) -> Path: + course = self.public / "courses" / str(course_id) + course.mkdir(parents=True) + manifest = course / "manifest.json" + manifest.write_text( + json.dumps( + { + "course": { + "id": course_id, + "fullname": f"Course {course_id}", + "source_url": f"https://training.example/course/view.php?id={course_id}", + "sections": [ + { + "number": 1, + "name": "Course", + "items": items or [], + } + ], + } + } + ), + encoding="utf-8", + ) + return course + + def write_overlay(self, course: Path, **assessment: object) -> None: + (course / "assessments.json").write_text( + json.dumps( + { + "schema_version": 1, + "assessments": [ + { + "id": "final-exam", + "type": "final", + "title": "Final exam", + "status": "ended", + **assessment, + } + ], + } + ), + encoding="utf-8", + ) + + def test_local_exam_is_merged_and_survives_repeated_scans(self) -> None: + course = self.write_course(56) + self.write_overlay(course) + questions = course / "assessments" / "final-exam" / "artifacts" / "questions.fa.md" + questions.parent.mkdir(parents=True) + questions.write_text("# Final exam", encoding="utf-8") + + scan_offline(self.public, [56]) + scan_offline(self.public, [56]) + + manifest = json.loads((course / "manifest.json").read_text(encoding="utf-8")) + items = [item for section in manifest["course"]["sections"] for item in section["items"]] + exams = [item for item in items if item.get("assessment_id") == "final-exam"] + self.assertEqual(len(exams), 1) + self.assertEqual(exams[0]["state"]["questions"], "complete") + self.assertEqual(exams[0]["bundle_path"], "assessments/final-exam") + self.assertEqual(manifest["course"]["states"]["assessments"], {"complete": 1, "total": 1}) + + def test_overlay_can_link_to_a_moodle_quiz(self) -> None: + course = self.write_course( + 53, + [ + { + "id": "activity-6126", + "activity_id": 6126, + "activity_position": 1, + "activity_type": "quiz", + "title": "Moodle quiz", + "kind": "quiz", + "filename": "", + } + ], + ) + self.write_overlay(course, activity_id=6126) + + scan_offline(self.public, [53]) + + manifest = json.loads((course / "manifest.json").read_text(encoding="utf-8")) + item = manifest["course"]["sections"][0]["items"][0] + self.assertEqual(item["assessment_id"], "final-exam") + self.assertEqual(item["activity_id"], 6126) + self.assertEqual(item["kind"], "assessment") + self.assertEqual(item["bundle_path"], "assessments/final-exam") + + def test_question_import_uses_the_local_assessment_bundle(self) -> None: + course = self.write_course(51) + self.write_overlay(course) + scan_offline(self.public, [51]) + source = Path(self.temporary_directory.name) / "exam.md" + source.write_text("# Final exam", encoding="utf-8") + + result = import_questions(self.public, 51, "final-exam", source) + + questions = course / "assessments" / "final-exam" / "artifacts" / "questions.fa.md" + self.assertEqual(questions.read_text(encoding="utf-8"), "# Final exam") + self.assertEqual(result.activity_key, "assessment--final-exam") + self.assertEqual( + result.questions, + "courses/51/assessments/final-exam/artifacts/questions.fa.md", + ) + manifest = json.loads((course / "manifest.json").read_text(encoding="utf-8")) + item = manifest["course"]["sections"][-1]["items"][0] + self.assertEqual(item["bundle_path"], "assessments/final-exam") + self.assertEqual(item["state"]["questions"], "complete") + + def test_active_exam_is_visible_but_cannot_publish_answers(self) -> None: + course = self.write_course(56) + self.write_overlay(course, status="active") + misplaced = course / "assessments" / "final-exam" / "artifacts" / "questions.fa.md" + misplaced.parent.mkdir(parents=True) + misplaced.write_text("# Must remain hidden", encoding="utf-8") + scan_offline(self.public, [56]) + source = Path(self.temporary_directory.name) / "answers.md" + source.write_text("# Answers", encoding="utf-8") + + with self.assertRaisesRegex(MoodleError, "publish questions only after it has ended"): + import_questions(self.public, 56, "final-exam", source) + + manifest = json.loads((course / "manifest.json").read_text(encoding="utf-8")) + states = manifest["course"]["states"]["assessments"] + self.assertEqual(states, {"total": 1, "complete": 0, "active": 1}) + item = manifest["course"]["sections"][-1]["items"][0] + self.assertNotIn("questions", item["artifacts"]) + + +if __name__ == "__main__": + unittest.main()