feat: add interactive exam questions import wizard
This commit is contained in:
10 files changed
+605
-5
No files matched your search
@@ -44,3 +44,4 @@ jobs:
|
||||
ravin --version
|
||||
ravin transcribe --help
|
||||
ravin summarize --help
|
||||
ravin questions --help
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
All notable changes to this project will be documented here.
|
||||
|
||||
## 0.9.0 - 2026-08-13
|
||||
|
||||
- Add an interactive `ravin questions` wizard for importing or updating Markdown exam questions.
|
||||
- List local courses and their quiz activities, including current question status, for guided selection.
|
||||
- Resolve the ordered activity bundle from the course manifest instead of requiring manual directory naming.
|
||||
- Support repeatable `--file` options for original PDFs and other exam attachments.
|
||||
- Validate quiz activities and UTF-8 Markdown, write files atomically, and refresh manifests without LMS login.
|
||||
|
||||
## 0.8.0 - 2026-08-04
|
||||
|
||||
- Add a manifest-driven `ravin summarize` command that generates Persian Markdown study guides with Codex CLI.
|
||||
|
||||
@@ -40,6 +40,7 @@ ravin scan
|
||||
ravin download COURSE_ID
|
||||
ravin transcribe COURSE_ID
|
||||
ravin summarize COURSE_ID
|
||||
ravin questions
|
||||
ravin serve --open
|
||||
```
|
||||
|
||||
@@ -113,6 +114,46 @@ The scanner reports each applicable file, transcript, summary, and assessment as
|
||||
|
||||
The downloader updates the course manifest after every completed file. A final offline scan reconciles all totals, so an interrupted run still retains useful progress.
|
||||
|
||||
## Exam questions and answers
|
||||
|
||||
Start the interactive import wizard:
|
||||
|
||||
```bash
|
||||
ravin questions
|
||||
```
|
||||
|
||||
The wizard:
|
||||
|
||||
1. Lists local courses that contain exams.
|
||||
2. Lists the selected course's exams and their current question status.
|
||||
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.
|
||||
|
||||
For scripting, all values can still be passed directly:
|
||||
|
||||
```bash
|
||||
ravin questions 44 5679 ~/Downloads/questions.fa.md \
|
||||
--file ~/Downloads/5679.pdf
|
||||
```
|
||||
|
||||
The command finds the quiz in the course manifest and creates the correct ordered bundle automatically. For the example above, it writes:
|
||||
|
||||
```text
|
||||
public/courses/44/content/026--001--5679/
|
||||
├── files/5679.pdf
|
||||
└── artifacts/questions.fa.md
|
||||
```
|
||||
|
||||
Use `--file` more than once when an exam has multiple attachments. The attachment is optional when only updating questions or answers:
|
||||
|
||||
```bash
|
||||
ravin questions 44 5679 revised-questions.fa.md
|
||||
```
|
||||
|
||||
The import is local and requires no LMS login. Files are written atomically, the original attachment names are preserved, and the course manifest is refreshed immediately so the library exposes the exam under its **Questions** button.
|
||||
|
||||
## Whisper transcription
|
||||
|
||||
After downloading a course, transcribe its video and audio in LMS order:
|
||||
@@ -267,6 +308,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 serve [--host ADDRESS] [--port PORT] [--open] [--public PATH]
|
||||
```
|
||||
|
||||
@@ -287,6 +329,7 @@ src/ravin/
|
||||
├── scan.py # manifests and local state reconciliation
|
||||
├── transcribe.py # resilient manifest-driven Whisper batches
|
||||
├── summarize.py # resilient Codex CLI study-guide batches
|
||||
├── questions.py # local exam-question and attachment imports
|
||||
├── migration.py # previous-layout migration
|
||||
├── server.py # local range-aware HTTP server
|
||||
└── models.py # shared value objects and errors
|
||||
|
||||
Binary file not shown.
+2
-2
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "ravin-moodle-downloader"
|
||||
version = "0.8.0"
|
||||
description = "Scan, download, transcribe, summarize, and browse authorized Moodle course materials"
|
||||
version = "0.9.0"
|
||||
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
license = "MIT"
|
||||
|
||||
+49
-1
@@ -19,6 +19,7 @@ from .client import MoodleClient
|
||||
from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__
|
||||
from .migration import migrate_library_to_public
|
||||
from .models import MoodleError
|
||||
from .questions import format_questions_result, import_questions, questions_wizard
|
||||
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
|
||||
from .server import _serve_library
|
||||
from .summarize import SummaryOptions, format_summary_result, summarize_courses
|
||||
@@ -135,6 +136,25 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
summarize_parser.add_argument("--json", action="store_true", help="print the final result as JSON")
|
||||
|
||||
questions_parser = subparsers.add_parser(
|
||||
"questions",
|
||||
help="interactively import or update questions for a local quiz",
|
||||
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("questions", nargs="?", type=Path, help="UTF-8 Markdown questions and answers")
|
||||
questions_parser.add_argument(
|
||||
"--file",
|
||||
dest="files",
|
||||
type=Path,
|
||||
action="append",
|
||||
default=[],
|
||||
help="optional original exam attachment; repeat for multiple files",
|
||||
)
|
||||
questions_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
|
||||
questions_parser.add_argument("--json", action="store_true", help="print imported paths as JSON")
|
||||
|
||||
serve_parser = subparsers.add_parser("serve", help="serve the public learning library locally")
|
||||
serve_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
|
||||
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address")
|
||||
@@ -182,7 +202,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
return 0
|
||||
|
||||
public = getattr(args, "public", Path("public")).expanduser().resolve()
|
||||
if args.command in {"scan", "download", "transcribe", "summarize"}:
|
||||
if args.command in {"scan", "download", "transcribe", "summarize", "questions"}:
|
||||
_maybe_migrate(public)
|
||||
|
||||
if args.command == "scan" and args.offline:
|
||||
@@ -241,6 +261,34 @@ def main(argv: list[str] | None = None) -> int:
|
||||
)
|
||||
return result.exit_code
|
||||
|
||||
if args.command == "questions":
|
||||
interactive = args.course_id is None or args.activity_id is None or args.questions is None
|
||||
course_id, activity_id, questions_path, attachment_paths = questions_wizard(
|
||||
public,
|
||||
args.course_id,
|
||||
args.activity_id,
|
||||
args.questions,
|
||||
tuple(args.files),
|
||||
prompt_for_attachment=interactive,
|
||||
) if interactive else (
|
||||
args.course_id,
|
||||
args.activity_id,
|
||||
args.questions,
|
||||
tuple(args.files),
|
||||
)
|
||||
result = import_questions(
|
||||
public,
|
||||
course_id,
|
||||
activity_id,
|
||||
questions_path,
|
||||
attachment_paths,
|
||||
)
|
||||
print(
|
||||
json.dumps(result.to_dict(), ensure_ascii=False, indent=2)
|
||||
if args.json else format_questions_result(result)
|
||||
)
|
||||
return 0
|
||||
|
||||
args.env_values = _load_env_file(args.env_file)
|
||||
if args.command == "login":
|
||||
_client, mode = _authenticate_browser_session(args)
|
||||
|
||||
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
DEFAULT_SITE = "https://training.ravinacademy.com"
|
||||
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
|
||||
__version__ = "0.8.0"
|
||||
__version__ = "0.9.0"
|
||||
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
|
||||
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
|
||||
DEFAULT_ENV_FILE = Path.cwd() / ".env"
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
"""Import or update local exam questions and their attachments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, TextIO
|
||||
|
||||
from .models import MoodleError
|
||||
from .paths import _activity_directory_name, _clean_name, _read_json_object
|
||||
from .scan import _atomic_json, _manifest_lock, scan_offline
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class QuestionsImportResult:
|
||||
course_id: int
|
||||
activity_id: int
|
||||
activity_key: str
|
||||
activity_title: str
|
||||
questions: str
|
||||
files: tuple[str, ...]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
value = asdict(self)
|
||||
value["files"] = list(self.files)
|
||||
return value
|
||||
|
||||
|
||||
def _prompt(input_func: Callable[[str], str], message: str) -> str:
|
||||
try:
|
||||
return input_func(message).strip()
|
||||
except EOFError as exc:
|
||||
raise MoodleError("interactive input ended before the questions import was complete") from exc
|
||||
|
||||
|
||||
def _prompt_path_value(value: str) -> Path:
|
||||
try:
|
||||
parts = shlex.split(value)
|
||||
except ValueError as exc:
|
||||
raise MoodleError(f"invalid file path: {exc}") from exc
|
||||
if len(parts) != 1:
|
||||
raise MoodleError("enter exactly one file path")
|
||||
return Path(parts[0]).expanduser()
|
||||
|
||||
|
||||
def _course_choices(public: Path) -> list[tuple[int, str, dict[str, Any]]]:
|
||||
choices: list[tuple[int, str, dict[str, Any]]] = []
|
||||
for manifest_path in sorted((public / "courses").glob("*/manifest.json")):
|
||||
manifest = _read_json_object(manifest_path)
|
||||
course = manifest.get("course")
|
||||
if not isinstance(course, dict):
|
||||
continue
|
||||
course_id = int(course.get("id") or 0)
|
||||
quizzes = _quiz_choices(course)
|
||||
if course_id and quizzes:
|
||||
title = str(course.get("fullname") or course.get("shortname") or f"Course {course_id}")
|
||||
choices.append((course_id, title, course))
|
||||
choices.sort(key=lambda value: value[0])
|
||||
return choices
|
||||
|
||||
|
||||
def _quiz_choices(course: dict[str, Any]) -> list[tuple[int, str, str, str]]:
|
||||
choices: list[tuple[int, str, str, str]] = []
|
||||
for section in course.get("sections", []):
|
||||
if not isinstance(section, dict):
|
||||
continue
|
||||
section_title = str(section.get("name") or f"Section {section.get('number', '')}")
|
||||
for item in section.get("items", []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
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:
|
||||
continue
|
||||
title = str(item.get("title") or f"Quiz {activity_id}")
|
||||
status = str(item.get("state", {}).get("questions") or "missing")
|
||||
choices.append((activity_id, title, section_title, status))
|
||||
return choices
|
||||
|
||||
|
||||
def _select_number(
|
||||
choices: list[tuple[Any, ...]],
|
||||
prompt_message: str,
|
||||
input_func: Callable[[str], str],
|
||||
output: TextIO,
|
||||
) -> int:
|
||||
valid_ids = {int(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
|
||||
if 1 <= selected <= len(choices):
|
||||
return int(choices[selected - 1][0])
|
||||
if selected in valid_ids:
|
||||
return selected
|
||||
print("That selection is not in the list. Please try again.", file=output)
|
||||
|
||||
|
||||
def questions_wizard(
|
||||
public: Path,
|
||||
course_id: int | None = None,
|
||||
activity_id: int | None = None,
|
||||
questions_path: Path | None = None,
|
||||
attachment_paths: tuple[Path, ...] = (),
|
||||
*,
|
||||
prompt_for_attachment: bool = True,
|
||||
input_func: Callable[[str], str] = input,
|
||||
output: TextIO | None = None,
|
||||
) -> tuple[int, int, Path, tuple[Path, ...]]:
|
||||
"""Interactively fill omitted question-import arguments from local manifests."""
|
||||
public = public.expanduser().resolve()
|
||||
output = output or sys.stderr
|
||||
courses = _course_choices(public)
|
||||
if not courses:
|
||||
raise MoodleError(f"no local courses with quizzes found in {public / 'courses'}; run `ravin scan` first")
|
||||
|
||||
courses_by_id = {choice[0]: choice for choice in courses}
|
||||
if course_id is None:
|
||||
print("\nCourses with exams:", file=output)
|
||||
for index, (candidate_id, title, course) in enumerate(courses, start=1):
|
||||
quiz_count = len(_quiz_choices(course))
|
||||
print(f" [{index}] {title} (course {candidate_id}, {quiz_count} exam(s))", file=output)
|
||||
course_id = _select_number(courses, "Select a course: ", input_func, output)
|
||||
if course_id not in courses_by_id:
|
||||
raise MoodleError(f"course {course_id} has no local quiz activities; run `ravin scan {course_id}` first")
|
||||
|
||||
course = courses_by_id[course_id][2]
|
||||
quizzes = _quiz_choices(course)
|
||||
quiz_ids = {choice[0] for choice in quizzes}
|
||||
if activity_id is None:
|
||||
print("\nExams:", file=output)
|
||||
for index, (candidate_id, title, section_title, status) in enumerate(quizzes, start=1):
|
||||
print(
|
||||
f" [{index}] {title} (activity {candidate_id}, section: {section_title}, questions: {status})",
|
||||
file=output,
|
||||
)
|
||||
activity_id = _select_number(quizzes, "Select an exam: ", input_func, output)
|
||||
if activity_id not in quiz_ids:
|
||||
raise MoodleError(f"activity {activity_id} is not a quiz in course {course_id}")
|
||||
|
||||
while questions_path is None:
|
||||
value = _prompt(input_func, "Questions Markdown file: ")
|
||||
try:
|
||||
candidate = _prompt_path_value(value)
|
||||
questions_path = _questions_source(candidate)
|
||||
except MoodleError as exc:
|
||||
print(f"Invalid questions file: {exc}", file=output)
|
||||
questions_path = _questions_source(questions_path)
|
||||
|
||||
attachments = _attachment_sources(attachment_paths)
|
||||
if prompt_for_attachment and not attachments:
|
||||
while True:
|
||||
value = _prompt(input_func, "Exam PDF (optional; press Enter to skip): ")
|
||||
if not value:
|
||||
break
|
||||
try:
|
||||
candidate = _prompt_path_value(value)
|
||||
attachments = _attachment_sources((candidate,))
|
||||
break
|
||||
except MoodleError as exc:
|
||||
print(f"Invalid exam file: {exc}", file=output)
|
||||
|
||||
return course_id, activity_id, questions_path, attachments
|
||||
|
||||
|
||||
def _atomic_copy(source: Path, destination: Path) -> None:
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
if source.resolve() == destination.resolve():
|
||||
os.chmod(destination, 0o644)
|
||||
return
|
||||
temporary_path: Path | None = None
|
||||
try:
|
||||
with source.open("rb") as input_file, tempfile.NamedTemporaryFile(
|
||||
mode="wb",
|
||||
dir=destination.parent,
|
||||
prefix=f".{destination.name}.",
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as output_file:
|
||||
shutil.copyfileobj(input_file, output_file, length=1024 * 1024)
|
||||
output_file.flush()
|
||||
os.fsync(output_file.fileno())
|
||||
temporary_path = Path(output_file.name)
|
||||
os.chmod(temporary_path, 0o644)
|
||||
os.replace(temporary_path, destination)
|
||||
finally:
|
||||
if temporary_path is not None:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _questions_source(path: Path) -> Path:
|
||||
source = path.expanduser().resolve()
|
||||
if not source.is_file():
|
||||
raise MoodleError(f"questions file not found: {source}")
|
||||
if source.suffix.casefold() not in {".md", ".markdown"}:
|
||||
raise MoodleError("questions must be supplied as a Markdown file")
|
||||
try:
|
||||
content = source.read_text(encoding="utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise MoodleError("questions Markdown must be UTF-8 encoded") from exc
|
||||
if not content.strip():
|
||||
raise MoodleError("questions Markdown is empty")
|
||||
return source
|
||||
|
||||
|
||||
def _attachment_sources(paths: tuple[Path, ...]) -> tuple[Path, ...]:
|
||||
sources: list[Path] = []
|
||||
names: set[str] = set()
|
||||
for path in paths:
|
||||
source = path.expanduser().resolve()
|
||||
if not source.is_file():
|
||||
raise MoodleError(f"exam attachment not found: {source}")
|
||||
name = _clean_name(source.name, "exam-file")
|
||||
folded = name.casefold()
|
||||
if folded in names:
|
||||
raise MoodleError(f"multiple exam attachments resolve to the same filename: {name}")
|
||||
names.add(folded)
|
||||
sources.append(source)
|
||||
return tuple(sources)
|
||||
|
||||
|
||||
def _find_activity(course: dict[str, Any], activity_id: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
matches: list[tuple[dict[str, Any], dict[str, Any]]] = []
|
||||
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:
|
||||
matches.append((section, item))
|
||||
if not matches:
|
||||
raise MoodleError(f"activity {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")
|
||||
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")
|
||||
return section, item
|
||||
|
||||
|
||||
def import_questions(
|
||||
public: Path,
|
||||
course_id: int,
|
||||
activity_id: int,
|
||||
questions_path: Path,
|
||||
attachment_paths: tuple[Path, ...] = (),
|
||||
) -> QuestionsImportResult:
|
||||
"""Place questions in their manifest-resolved bundle and reconcile the library."""
|
||||
public = public.expanduser().resolve()
|
||||
questions_source = _questions_source(questions_path)
|
||||
attachment_sources = _attachment_sources(attachment_paths)
|
||||
manifest_path = public / "courses" / str(course_id) / "manifest.json"
|
||||
manifest = _read_json_object(manifest_path)
|
||||
course = manifest.get("course")
|
||||
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
|
||||
questions_destination = activity_directory / "artifacts" / "questions.fa.md"
|
||||
_atomic_copy(questions_source, questions_destination)
|
||||
|
||||
copied_files: list[str] = []
|
||||
for source in attachment_sources:
|
||||
filename = _clean_name(source.name, "exam-file")
|
||||
_atomic_copy(source, activity_directory / "files" / filename)
|
||||
copied_files.append(filename)
|
||||
|
||||
# Persist enough local information for an offline scan to expose the exam
|
||||
# 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["kind"] = "assessment"
|
||||
if copied_files:
|
||||
primary = activity_directory / "files" / copied_files[0]
|
||||
item["filename"] = primary.name
|
||||
item["extension"] = primary.suffix.removeprefix(".").casefold()
|
||||
item["mimetype"] = mimetypes.guess_type(primary.name)[0] or "application/octet-stream"
|
||||
item.pop("remote_size", None)
|
||||
|
||||
with _manifest_lock(public / "courses"):
|
||||
current = _read_json_object(manifest_path)
|
||||
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_item.update(
|
||||
{
|
||||
"key": key,
|
||||
"bundle_path": f"content/{key}",
|
||||
"kind": "assessment",
|
||||
}
|
||||
)
|
||||
if copied_files:
|
||||
primary = activity_directory / "files" / copied_files[0]
|
||||
current_item.update(
|
||||
{
|
||||
"filename": primary.name,
|
||||
"extension": primary.suffix.removeprefix(".").casefold(),
|
||||
"mimetype": mimetypes.guess_type(primary.name)[0] or "application/octet-stream",
|
||||
}
|
||||
)
|
||||
current_item.pop("remote_size", None)
|
||||
current["course"] = current_course
|
||||
_atomic_json(manifest_path, current)
|
||||
|
||||
scan_offline(public, [course_id])
|
||||
relative_questions = questions_destination.relative_to(public).as_posix()
|
||||
relative_files = tuple(
|
||||
(activity_directory / "files" / filename).relative_to(public).as_posix()
|
||||
for filename in copied_files
|
||||
)
|
||||
return QuestionsImportResult(
|
||||
course_id=course_id,
|
||||
activity_id=activity_id,
|
||||
activity_key=key,
|
||||
activity_title=str(item.get("title") or f"Activity {activity_id}"),
|
||||
questions=relative_questions,
|
||||
files=relative_files,
|
||||
)
|
||||
|
||||
|
||||
def format_questions_result(result: QuestionsImportResult) -> str:
|
||||
file_count = len(result.files)
|
||||
suffix = f" and {file_count} attachment(s)" if file_count else ""
|
||||
return (
|
||||
f"Updated questions for {result.activity_title} "
|
||||
f"(course {result.course_id}, activity {result.activity_id}){suffix}."
|
||||
)
|
||||
@@ -0,0 +1,146 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
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, questions_wizard
|
||||
|
||||
|
||||
class QuestionsImportTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary_directory = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temporary_directory.name)
|
||||
self.public = self.root / "public"
|
||||
self.manifest_path = self.public / "courses" / "44" / "manifest.json"
|
||||
self.manifest_path.parent.mkdir(parents=True)
|
||||
self.manifest_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schema_version": 1,
|
||||
"course": {
|
||||
"id": 44,
|
||||
"fullname": "Network +",
|
||||
"sections": [
|
||||
{
|
||||
"number": 26,
|
||||
"name": "Second exam",
|
||||
"items": [
|
||||
{
|
||||
"activity_id": 5679,
|
||||
"activity_position": 1,
|
||||
"activity_type": "quiz",
|
||||
"title": "Second exam",
|
||||
"kind": "quiz",
|
||||
"key": "026--001--5679",
|
||||
"bundle_path": "content/026--001--5679",
|
||||
"filename": "",
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
self.questions = self.root / "questions.fa.md"
|
||||
self.questions.write_text("# آزمون دوم\n\n## سؤال ۱\n\n**پاسخ صحیح: B**\n", encoding="utf-8")
|
||||
self.exam = self.root / "5679.pdf"
|
||||
self.exam.write_bytes(b"synthetic exam")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temporary_directory.cleanup()
|
||||
|
||||
def test_import_places_questions_and_attachment_and_refreshes_manifest(self) -> None:
|
||||
result = import_questions(self.public, 44, 5679, self.questions, (self.exam,))
|
||||
|
||||
bundle = self.public / "courses" / "44" / "content" / "026--001--5679"
|
||||
questions = bundle / "artifacts" / "questions.fa.md"
|
||||
attachment = bundle / "files" / "5679.pdf"
|
||||
self.assertEqual(questions.read_text(encoding="utf-8"), self.questions.read_text(encoding="utf-8"))
|
||||
self.assertEqual(attachment.read_bytes(), b"synthetic exam")
|
||||
self.assertEqual(os.stat(questions).st_mode & 0o777, 0o644)
|
||||
self.assertEqual(os.stat(attachment).st_mode & 0o777, 0o644)
|
||||
self.assertEqual(result.activity_key, "026--001--5679")
|
||||
self.assertEqual(result.files, ("courses/44/content/026--001--5679/files/5679.pdf",))
|
||||
|
||||
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
||||
item = manifest["course"]["sections"][0]["items"][0]
|
||||
self.assertEqual(item["kind"], "assessment")
|
||||
self.assertEqual(item["filename"], "5679.pdf")
|
||||
self.assertEqual(item["mimetype"], "application/pdf")
|
||||
self.assertEqual(item["state"]["download"], "complete")
|
||||
self.assertEqual(item["state"]["questions"], "complete")
|
||||
self.assertEqual(item["artifacts"]["questions"]["path"], "artifacts/questions.fa.md")
|
||||
self.assertEqual(manifest["course"]["states"]["assessments"], {"complete": 1, "total": 1})
|
||||
|
||||
def test_import_updates_existing_questions_without_requiring_attachment(self) -> None:
|
||||
import_questions(self.public, 44, 5679, self.questions, (self.exam,))
|
||||
self.questions.write_text("# نسخه جدید\n", encoding="utf-8")
|
||||
|
||||
result = import_questions(self.public, 44, 5679, self.questions)
|
||||
|
||||
bundle = self.public / "courses" / "44" / "content" / "026--001--5679"
|
||||
self.assertEqual((bundle / "artifacts" / "questions.fa.md").read_text(encoding="utf-8"), "# نسخه جدید\n")
|
||||
self.assertTrue((bundle / "files" / "5679.pdf").is_file())
|
||||
self.assertEqual(result.files, ())
|
||||
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
||||
item = manifest["course"]["sections"][0]["items"][0]
|
||||
self.assertEqual(item["state"]["questions"], "complete")
|
||||
self.assertEqual(item["state"]["download"], "complete")
|
||||
|
||||
def test_rejects_unknown_or_non_quiz_activity(self) -> None:
|
||||
with self.assertRaisesRegex(MoodleError, "activity 9999 was not found"):
|
||||
import_questions(self.public, 44, 9999, self.questions)
|
||||
|
||||
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
||||
item = manifest["course"]["sections"][0]["items"][0]
|
||||
item["activity_type"] = "resource"
|
||||
item["kind"] = "document"
|
||||
self.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
with self.assertRaisesRegex(MoodleError, "not a quiz or assessment"):
|
||||
import_questions(self.public, 44, 5679, self.questions)
|
||||
|
||||
def test_wizard_lists_courses_and_exams_then_collects_files(self) -> None:
|
||||
answers = iter(["1", "1", str(self.questions), str(self.exam)])
|
||||
output = io.StringIO()
|
||||
|
||||
values = questions_wizard(
|
||||
self.public,
|
||||
input_func=lambda _prompt: next(answers),
|
||||
output=output,
|
||||
)
|
||||
|
||||
course_id, activity_id, questions, attachments = values
|
||||
self.assertEqual(course_id, 44)
|
||||
self.assertEqual(activity_id, 5679)
|
||||
self.assertEqual(questions, self.questions.resolve())
|
||||
self.assertEqual(attachments, (self.exam.resolve(),))
|
||||
display = output.getvalue()
|
||||
self.assertIn("Courses with exams:", display)
|
||||
self.assertIn("Network + (course 44, 1 exam(s))", display)
|
||||
self.assertIn("Second exam (activity 5679", display)
|
||||
self.assertIn("questions: missing", display)
|
||||
|
||||
def test_wizard_accepts_ids_and_optional_empty_pdf(self) -> None:
|
||||
answers = iter(["44", "5679", str(self.questions), ""])
|
||||
|
||||
values = questions_wizard(
|
||||
self.public,
|
||||
input_func=lambda _prompt: next(answers),
|
||||
output=io.StringIO(),
|
||||
)
|
||||
|
||||
self.assertEqual(values, (44, 5679, self.questions.resolve(), ()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+12
-1
@@ -84,7 +84,7 @@ class ParserTests(unittest.TestCase):
|
||||
self.assertEqual(args.command, "login")
|
||||
self.assertFalse(args.manual_session)
|
||||
|
||||
def test_scan_download_transcribe_summarize_and_serve_commands_parse(self):
|
||||
def test_all_primary_commands_parse(self):
|
||||
scan = build_parser().parse_args(["scan", "44", "--public", "site", "--offline", "--json"])
|
||||
self.assertEqual(scan.course_ids, [44])
|
||||
self.assertEqual(scan.public, Path("site"))
|
||||
@@ -100,6 +100,17 @@ class ParserTests(unittest.TestCase):
|
||||
summarize = build_parser().parse_args(["summarize", "44", "--model", "gpt-test"])
|
||||
self.assertEqual(summarize.course_ids, [44])
|
||||
self.assertEqual(summarize.model, "gpt-test")
|
||||
questions = build_parser().parse_args(
|
||||
["questions", "44", "5679", "questions.fa.md", "--file", "5679.pdf"]
|
||||
)
|
||||
self.assertEqual(questions.course_id, 44)
|
||||
self.assertEqual(questions.activity_id, 5679)
|
||||
self.assertEqual(questions.questions, Path("questions.fa.md"))
|
||||
self.assertEqual(questions.files, [Path("5679.pdf")])
|
||||
questions_wizard = build_parser().parse_args(["questions"])
|
||||
self.assertIsNone(questions_wizard.course_id)
|
||||
self.assertIsNone(questions_wizard.activity_id)
|
||||
self.assertIsNone(questions_wizard.questions)
|
||||
serve = build_parser().parse_args(["serve", "--port", "9000"])
|
||||
self.assertEqual(serve.port, 9000)
|
||||
|
||||
|
||||
Reference in new issue
Block a user