add final-exam

This commit is contained in:
Meghdad committed 2026-09-27 05:49:59 +03:30
1 parent 524b443f3f
commit 056c7199b5
8 files changed
+460 -43

No files matched your search

+36 -2
View File
@@ -186,6 +186,38 @@ Use `--public PATH` for another library root, `--timeout SECONDS` for slow serve
## Exam questions and answers ## 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: Start the interactive import wizard:
```bash ```bash
@@ -199,7 +231,8 @@ The wizard:
3. Prompts for the UTF-8 Markdown questions-and-answers file. 3. Prompts for the UTF-8 Markdown questions-and-answers file.
4. Prompts for an optional original exam PDF. 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: 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 download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH]
ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE] ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE]
ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS] 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 recording [COURSE_ID] [ACTIVITY_ID] [VIDEO]
ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH] ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH]
ravin import URL [--timeout SECONDS] [--json] [--public PATH] ravin import URL [--timeout SECONDS] [--json] [--public PATH]
@@ -428,6 +461,7 @@ src/ravin/
├── transcribe.py # resilient manifest-driven Whisper batches ├── transcribe.py # resilient manifest-driven Whisper batches
├── summarize.py # resilient Codex CLI study-guide batches ├── summarize.py # resilient Codex CLI study-guide batches
├── questions.py # local exam-question and attachment imports ├── questions.py # local exam-question and attachment imports
├── assessments.py # durable course-level exam overlays
├── recordings.py # local live-class recording imports ├── recordings.py # local live-class recording imports
├── exporter.py # atomic course ZIP exports ├── exporter.py # atomic course ZIP exports
├── importer.py # safe URL restores and mirror updates ├── importer.py # safe URL restores and mirror updates
+15 -4
View File
@@ -255,6 +255,13 @@ function resourceMatches(item) {
} }
function resourceRow(item, index) { 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"); const row = document.createElement("article");
row.className = `resource-row${isComplete(item) ? " completed" : ""}`; row.className = `resource-row${isComplete(item) ? " completed" : ""}`;
const number = document.createElement("span"); const number = document.createElement("span");
@@ -272,7 +279,7 @@ function resourceRow(item, index) {
const filename = document.createElement("span"); const filename = document.createElement("span");
filename.className = "resource-file"; filename.className = "resource-file";
filename.dir = "auto"; 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); fileLine.append(filename);
if ((item.file_versions || []).some((version) => version.state === "current")) { if ((item.file_versions || []).some((version) => version.state === "current")) {
const currentBadge = document.createElement("span"); const currentBadge = document.createElement("span");
@@ -366,15 +373,19 @@ function resourceRow(item, index) {
const dot = document.createElement("span"); const dot = document.createElement("span");
dot.className = `status-dot${item.status === "missing" ? " missing" : item.status === "online" ? " online" : ""}`; dot.className = `status-dot${item.status === "missing" ? " missing" : item.status === "online" ? " online" : ""}`;
const size = document.createElement("span"); const size = document.createElement("span");
size.textContent = item.status === "partial" size.textContent = assessmentLabel || (item.status === "partial"
? `${formatBytes(item.local_bytes)} partial` ? `${formatBytes(item.local_bytes)} partial`
: item.status === "online" : item.status === "online"
? (item.lms_completed ? "LMS complete" : "Online") ? (item.lms_completed ? "LMS complete" : "Online")
: formatBytes(item.size); : formatBytes(item.size));
meta.append(type, dot, size); meta.append(type, dot, size);
let action; 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 = document.createElement("button");
action.type = "button"; action.type = "button";
action.textContent = "Play"; action.textContent = "Play";
+165
View File
@@ -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
+10 -1
View File
@@ -29,6 +29,10 @@ from .summarize import SummaryOptions, format_summary_result, summarize_courses
from .transcribe import TranscriptionOptions, format_transcription_result, transcribe_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: def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Scan and download your Ravin Academy Moodle courses.") parser = argparse.ArgumentParser(description="Scan and download your Ravin Academy Moodle courses.")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}") 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.", 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("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("questions", nargs="?", type=Path, help="UTF-8 Markdown questions and answers")
questions_parser.add_argument( questions_parser.add_argument(
"--file", "--file",
+44 -25
View File
@@ -10,15 +10,15 @@ from typing import Any, Callable, TextIO
from .local_files import atomic_copy from .local_files import atomic_copy
from .models import MoodleError from .models import MoodleError
from .paths import _activity_directory_name, _clean_name, _read_json_object from .paths import _clean_name, _read_json_object
from .scan import _atomic_json, _manifest_lock, scan_offline from .scan import _activity_directory, _atomic_json, _manifest_lock, scan_offline
from .wizard import prompt, prompt_path, select_number from .wizard import prompt, prompt_path, select_number
@dataclass(frozen=True) @dataclass(frozen=True)
class QuestionsImportResult: class QuestionsImportResult:
course_id: int course_id: int
activity_id: int activity_id: int | str
activity_key: str activity_key: str
activity_title: str activity_title: str
questions: str questions: str
@@ -46,8 +46,8 @@ def _course_choices(public: Path) -> list[tuple[int, str, dict[str, Any]]]:
return choices return choices
def _quiz_choices(course: dict[str, Any]) -> 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]] = [] choices: list[tuple[int | str, str, str, str]] = []
for section in course.get("sections", []): for section in course.get("sections", []):
if not isinstance(section, dict): if not isinstance(section, dict):
continue 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": if item.get("activity_type") != "quiz" and item.get("kind") != "assessment":
continue continue
activity_id = int(item.get("activity_id") or 0) 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 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") 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 return choices
def questions_wizard( def questions_wizard(
public: Path, public: Path,
course_id: int | None = None, course_id: int | None = None,
activity_id: int | None = None, activity_id: int | str | None = None,
questions_path: Path | None = None, questions_path: Path | None = None,
attachment_paths: tuple[Path, ...] = (), attachment_paths: tuple[Path, ...] = (),
*, *,
@@ -100,8 +101,10 @@ def questions_wizard(
if activity_id is None: if activity_id is None:
print("\nExams:", file=output) print("\nExams:", file=output)
for index, (candidate_id, title, section_title, status) in enumerate(quizzes, start=1): for index, (candidate_id, title, section_title, status) in enumerate(quizzes, start=1):
reference_label = "activity" if isinstance(candidate_id, int) else "assessment"
print( 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, file=output,
) )
activity_id = select_number(quizzes, "Select an exam: ", input_func, 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) 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]]] = [] 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", []): for section in course.get("sections", []):
if not isinstance(section, dict): if not isinstance(section, dict):
continue continue
for item in section.get("items", []): 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)) 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: 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: 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] section, item = matches[0]
if item.get("activity_type") != "quiz" and item.get("kind") != "assessment": 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 return section, item
def import_questions( def import_questions(
public: Path, public: Path,
course_id: int, course_id: int,
activity_id: int, activity_id: int | str,
questions_path: Path, questions_path: Path,
attachment_paths: tuple[Path, ...] = (), attachment_paths: tuple[Path, ...] = (),
) -> QuestionsImportResult: ) -> QuestionsImportResult:
@@ -199,12 +215,14 @@ def import_questions(
if not isinstance(course, dict): if not isinstance(course, dict):
raise MoodleError(f"course manifest not found: {manifest_path}; run `ravin scan {course_id}` first") raise MoodleError(f"course manifest not found: {manifest_path}; run `ravin scan {course_id}` first")
section, item = _find_activity(course, activity_id) section, item = _find_activity(course, activity_id)
key = str(item.get("key") or "") or _activity_directory_name( assessment_status = str(item.get("assessment_status") or "")
item.get("section_number", section.get("number")), if assessment_status in {"upcoming", "active", "unavailable"}:
item.get("activity_position"), raise MoodleError(
activity_id, f"assessment {activity_id} is {assessment_status}; publish questions only after it has ended"
) )
activity_directory = public / "courses" / str(course_id) / "content" / key 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" questions_destination = activity_directory / "artifacts" / "questions.fa.md"
atomic_copy(questions_source, questions_destination) 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 # and its primary attachment immediately. A later remote scan will merge the
# same bundle through its stable activity ID. # same bundle through its stable activity ID.
item["key"] = key item["key"] = key
item["bundle_path"] = f"content/{key}" item["bundle_path"] = bundle_path
item["kind"] = "assessment" item["kind"] = "assessment"
if copied_files: if copied_files:
primary = activity_directory / "files" / copied_files[0] primary = activity_directory / "files" / copied_files[0]
@@ -232,11 +250,12 @@ def import_questions(
current_course = current.get("course") current_course = current.get("course")
if not isinstance(current_course, dict): if not isinstance(current_course, dict):
raise MoodleError(f"course manifest changed while importing questions: {manifest_path}") 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( current_item.update(
{ {
"key": key, "key": key,
"bundle_path": f"content/{key}", "bundle_path": bundle_path,
"kind": "assessment", "kind": "assessment",
} }
) )
+30 -4
View File
@@ -10,6 +10,7 @@ from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import Any, Iterable from typing import Any, Iterable
from .assessments import assessment_directory, merge_assessments
from .catalog import _build_library_catalog from .catalog import _build_library_catalog
from .client import MoodleClient from .client import MoodleClient
from .constants import LIVE_CLASS_MODULES 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: 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( key = _activity_directory_name(
item.get("section_number", section.get("number")), item.get("section_number", section.get("number")),
item.get("activity_position"), item.get("activity_position"),
@@ -216,6 +223,7 @@ def _file_versions(
def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: 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) course_id = int(course.get("id") or 0)
downloaded_bytes = 0 downloaded_bytes = 0
type_counts: dict[str, int] = {} type_counts: dict[str, int] = {}
@@ -228,7 +236,12 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
"downloads": category_counts(), "downloads": category_counts(),
"transcripts": category_counts(), "transcripts": category_counts(),
"summaries": category_counts(), "summaries": category_counts(),
"assessments": category_counts(), "assessments": {
**category_counts(),
"upcoming": 0,
"active": 0,
"unavailable": 0,
},
"recordings": category_counts(), "recordings": category_counts(),
"partial": 0, "partial": 0,
"stale": 0, "stale": 0,
@@ -259,7 +272,13 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
and summary_state == "complete" and summary_state == "complete"
): ):
summary_state = "stale" 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): for value in (download_state, transcript_state, summary_state, questions_state):
if value not in STATE_VALUES: if value not in STATE_VALUES:
raise MoodleError(f"invalid manifest state {value!r}") 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 else download_state
) )
item["artifacts"] = _discover_artifacts(activity_directory, public) item["artifacts"] = _discover_artifacts(activity_directory, public)
if assessment_applicable and not questions_publishable:
item["artifacts"].pop("questions", None)
versioned_activity = ( versioned_activity = (
item.get("activity_type") == "resource" item.get("activity_type") == "resource"
or item.get("activity_type") in LIVE_CLASS_MODULES 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 state_counts["summaries"][summary_state] += 1
if assessment_applicable: if assessment_applicable:
state_counts["assessments"]["total"] += 1 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: if recording_applicable:
recording_state = download_state if download_state != "not_applicable" else "missing" recording_state = download_state if download_state != "not_applicable" else "missing"
state_counts["recordings"]["total"] += 1 state_counts["recordings"]["total"] += 1
@@ -472,7 +496,7 @@ def format_scan(catalog: dict[str, Any]) -> str:
total = int(state.get("total") or 0) total = int(state.get("total") or 0)
details = [ details = [
f"{int(state.get(value) or 0)} {value}" 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) if int(state.get(value) or 0)
] ]
suffix = f" · {', '.join(details)}" if details else "" suffix = f" · {', '.join(details)}" if details else ""
@@ -482,6 +506,8 @@ def format_scan(catalog: dict[str, Any]) -> str:
def pending(name: str) -> int: def pending(name: str) -> int:
state = course[name] 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) 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: def quantity(value: int, singular: str, plural: str | None = None) -> str:
+6 -7
View File
@@ -34,17 +34,16 @@ def select_number(
prompt_message: str, prompt_message: str,
input_func: Callable[[str], str], input_func: Callable[[str], str],
output: TextIO, output: TextIO,
) -> int: ) -> Any:
valid_ids = {int(choice[0]) for choice in choices} valid_ids = {str(choice[0]): choice[0] for choice in choices}
while True: while True:
value = prompt(input_func, prompt_message) value = prompt(input_func, prompt_message)
try: try:
selected = int(value) selected = int(value)
except ValueError: except ValueError:
print("Please enter a list number or ID.", file=output) selected = 0
continue
if 1 <= selected <= len(choices): if 1 <= selected <= len(choices):
return int(choices[selected - 1][0]) return choices[selected - 1][0]
if selected in valid_ids: if value in valid_ids:
return selected return valid_ids[value]
print("That selection is not in the list. Please try again.", file=output) print("That selection is not in the list. Please try again.", file=output)
+154
View File
@@ -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()