diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..efa43a3 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,2 @@ +reports/ +.coverage diff --git a/backend/alembic/versions/0007_timetable.py b/backend/alembic/versions/0007_timetable.py index 0491c13..097b971 100644 --- a/backend/alembic/versions/0007_timetable.py +++ b/backend/alembic/versions/0007_timetable.py @@ -1,4 +1,4 @@ -"""Create annual timetables, kholle bounds, audiences and revocable ICS subscriptions.""" +"""Create annual timetables, availability patterns, audiences and revocable ICS subscriptions.""" from uuid import uuid4 @@ -13,7 +13,7 @@ def upgrade() -> None: - """Create timetable storage, availability bounds, archive policy and personal calendar links.""" + """Create timetables, availability patterns, archive policy and personal calendar links.""" op.create_table( "timetable_calendars", sa.Column("id", sa.BigInteger(), sa.Identity(), primary_key=True), @@ -61,15 +61,6 @@ def upgrade() -> None: sa.Column("user_id", sa.BigInteger(), nullable=False), sa.Column("school_year", sa.Integer(), nullable=False), sa.Column("ranges", postgresql.JSONB(), nullable=True), - sa.Column("kholle_min_hours", sa.Integer(), nullable=False, server_default="0"), - sa.Column("kholle_max_hours", sa.Integer(), nullable=False, server_default="0"), - sa.CheckConstraint( - "kholle_min_hours >= 0", name=op.f("ck_teacher_availability_kholle_min_hours") - ), - sa.CheckConstraint( - "kholle_max_hours >= kholle_min_hours", - name=op.f("ck_teacher_availability_kholle_max_hours"), - ), sa.Column("revision", sa.String(32), nullable=False), sa.PrimaryKeyConstraint("user_id", "school_year"), sa.ForeignKeyConstraint(["user_id"], ["sophikron.users.id"], ondelete="CASCADE"), diff --git a/backend/alembic/versions/0008_kholloscope.py b/backend/alembic/versions/0008_kholloscope.py index 51f5e08..dd72e14 100644 --- a/backend/alembic/versions/0008_kholloscope.py +++ b/backend/alembic/versions/0008_kholloscope.py @@ -1,7 +1,7 @@ """Consolidated kholloscope preparation, durable drafts and administrator capabilities. This unreleased baseline replaces the former 0008 through 0014 revisions. -Apply it to a fresh database or one still at 0007; never stamp an old schema to match it. +Apply it to a fresh database or the cleaned 0007 baseline; never stamp an old schema to match it. """ import sqlalchemy as sa @@ -52,15 +52,6 @@ def upgrade() -> None: sa.ForeignKeyConstraint(["subject_id"], ["sophikron.subjects.id"], ondelete="RESTRICT"), schema="sophikron", ) - for name in ("kholle_max_hours", "kholle_min_hours"): - op.drop_constraint( - op.f(f"ck_teacher_availability_{name}"), - "teacher_availability", - type_="check", - schema="sophikron", - ) - for name in ("kholle_min_hours", "kholle_max_hours"): - op.drop_column("teacher_availability", name, schema="sophikron") op.create_table( "kholloscope_workflows", sa.Column("school_year", sa.Integer(), primary_key=True), @@ -149,24 +140,6 @@ def downgrade() -> None: ) op.drop_column("timetable_rooms", "kholle_capacity", schema="sophikron") op.drop_table("kholloscope_workflows", schema="sophikron") - for name in ("kholle_min_hours", "kholle_max_hours"): - op.add_column( - "teacher_availability", - sa.Column(name, sa.Integer(), nullable=False, server_default="0"), - schema="sophikron", - ) - op.create_check_constraint( - op.f("ck_teacher_availability_kholle_min_hours"), - "teacher_availability", - "kholle_min_hours >= 0", - schema="sophikron", - ) - op.create_check_constraint( - op.f("ck_teacher_availability_kholle_max_hours"), - "teacher_availability", - "kholle_max_hours >= kholle_min_hours", - schema="sophikron", - ) op.drop_table("kholle_wishes", schema="sophikron") op.drop_column("timetable_school_years", "created_at", schema="sophikron") op.drop_column("timetable_calendars", "kholle_settings", schema="sophikron") diff --git a/backend/alembic/versions/0009_curricula.py b/backend/alembic/versions/0009_curricula.py new file mode 100644 index 0000000..d40cee7 --- /dev/null +++ b/backend/alembic/versions/0009_curricula.py @@ -0,0 +1,167 @@ +"""Release baseline for curricula, competency DAGs, optional promotions and bounded undo.""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision = "0009_curricula" +down_revision = "0008_kholloscope" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Add programme storage without changing calendars or existing promotions.""" + op.create_table( + "curricula", + sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True), + sa.Column("title", sa.String(160), nullable=False), + sa.Column("description", sa.Text()), + sa.Column("source_url", sa.String(2000)), + sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"), + sa.Column("version", sa.BigInteger(), nullable=False, server_default="0"), + sa.CheckConstraint("length(btrim(title)) > 0", name="title"), + schema="sophikron", + ) + op.create_table( + "curriculum_subjects", + sa.Column("curriculum_id", sa.BigInteger(), primary_key=True), + sa.Column("subject_id", sa.BigInteger(), primary_key=True), + sa.ForeignKeyConstraint(["curriculum_id"], ["sophikron.curricula.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["subject_id"], ["sophikron.subjects.id"], ondelete="RESTRICT"), + schema="sophikron", + ) + op.create_table( + "competencies", + sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True), + sa.Column("curriculum_id", sa.BigInteger(), nullable=False), + sa.Column("subject_id", sa.BigInteger(), nullable=False), + sa.Column("name", sa.String(300), nullable=False), + sa.Column("semester", sa.Integer()), + sa.Column("knowledge", sa.Text()), + sa.Column("comment", sa.Text()), + sa.Column("color", sa.String(7)), + sa.Column("position", sa.Integer(), nullable=False, server_default="0"), + sa.ForeignKeyConstraint( + ["curriculum_id", "subject_id"], + [ + "sophikron.curriculum_subjects.curriculum_id", + "sophikron.curriculum_subjects.subject_id", + ], + ondelete="CASCADE", + ), + sa.UniqueConstraint("curriculum_id", "subject_id", "id", name="uq_competency_scope"), + sa.CheckConstraint("length(btrim(name)) > 0", name="name"), + sa.CheckConstraint("semester BETWEEN 1 AND 4", name="semester"), + sa.CheckConstraint("color ~ '^#[0-9A-Fa-f]{6}$'", name="color"), + sa.CheckConstraint("position >= 0", name="position"), + schema="sophikron", + ) + op.create_index( + "ix_competencies_curriculum_id", "competencies", ["curriculum_id"], schema="sophikron" + ) + op.create_table( + "competency_links", + sa.Column("curriculum_id", sa.BigInteger(), nullable=False), + sa.Column("subject_id", sa.BigInteger(), nullable=False), + sa.Column("parent_id", sa.BigInteger(), primary_key=True), + sa.Column("child_id", sa.BigInteger(), primary_key=True), + *( + sa.ForeignKeyConstraint( + ["curriculum_id", "subject_id", endpoint], + [ + "sophikron.competencies.curriculum_id", + "sophikron.competencies.subject_id", + "sophikron.competencies.id", + ], + ondelete="CASCADE", + name=f"fk_competency_links_{endpoint}", + ) + for endpoint in ("parent_id", "child_id") + ), + sa.CheckConstraint("parent_id <> child_id", name="different_nodes"), + schema="sophikron", + ) + op.create_index( + "ix_competency_links_child_id", "competency_links", ["child_id"], schema="sophikron" + ) + op.add_column("promotions", sa.Column("curriculum_id", sa.BigInteger()), schema="sophikron") + op.create_foreign_key( + "fk_promotions_curriculum_id_curricula", + "promotions", + "curricula", + ["curriculum_id"], + ["id"], + source_schema="sophikron", + referent_schema="sophikron", + ondelete="RESTRICT", + ) + op.create_index( + "ix_promotions_curriculum_id", "promotions", ["curriculum_id"], schema="sophikron" + ) + op.create_table( + "curriculum_undo", + sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True), + sa.Column( + "actor_id", + sa.BigInteger(), + sa.ForeignKey("sophikron.users.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column( + "curriculum_id", + sa.BigInteger(), + sa.ForeignKey("sophikron.curricula.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column( + "subject_id", + sa.BigInteger(), + sa.ForeignKey("sophikron.subjects.id", ondelete="RESTRICT"), + nullable=False, + ), + sa.Column("node_id", sa.BigInteger(), nullable=False), + sa.Column("after_version", sa.BigInteger(), nullable=False), + sa.Column("payload", postgresql.JSONB(), nullable=False), + schema="sophikron", + ) + + for code, roles in ( + ("curricula.read", ("admin", "teacher", "kholleur")), + ("curricula.edit", ("teacher",)), + ("curricula.manage", ("admin",)), + ): + op.execute( + sa.text( + "INSERT INTO sophikron.permissions (code, description) VALUES (:c, :c)" + ).bindparams(c=code) + ) + for role in roles: + op.execute( + sa.text( + "INSERT INTO sophikron.role_permissions (role_id, permission_id) " + "SELECT r.id, p.id FROM sophikron.roles r CROSS JOIN sophikron.permissions p " + "WHERE r.code = :r AND p.code = :c" + ).bindparams(r=role, c=code) + ) + + +def downgrade() -> None: + """Remove only programme storage and the optional promotion association.""" + op.execute("DELETE FROM sophikron.permissions WHERE code LIKE 'curricula.%'") + op.drop_index("ix_promotions_curriculum_id", table_name="promotions", schema="sophikron") + op.drop_constraint( + "fk_promotions_curriculum_id_curricula", + "promotions", + schema="sophikron", + type_="foreignkey", + ) + op.drop_column("promotions", "curriculum_id", schema="sophikron") + for table in ( + "curriculum_undo", + "competency_links", + "competencies", + "curriculum_subjects", + "curricula", + ): + op.drop_table(table, schema="sophikron") diff --git a/backend/app/api/router.py b/backend/app/api/router.py index e4cf473..5a1dc06 100644 --- a/backend/app/api/router.py +++ b/backend/app/api/router.py @@ -5,6 +5,7 @@ from app.api.v1 import ( admin, auth, + curricula, dashboard, groups, kholloscope, @@ -20,6 +21,7 @@ router = APIRouter() v1 = APIRouter(prefix="/api/v1") v1.include_router(auth.router) +v1.include_router(curricula.router) v1.include_router(admin.router) v1.include_router(dashboard.router) v1.include_router(groups.router) diff --git a/backend/app/api/v1/curricula.py b/backend/app/api/v1/curricula.py new file mode 100644 index 0000000..2a500d7 --- /dev/null +++ b/backend/app/api/v1/curricula.py @@ -0,0 +1,135 @@ +"""Authenticated programme catalogues, administration and subject-scoped graph routes.""" + +from typing import Annotated + +from fastapi import APIRouter, Depends, Path, Request +from pydantic import ValidationError + +from app.dependencies.auth import AuthenticatedUser, AuthServiceDependency +from app.schemas.curricula import ( + CompetencyFields, + CurriculumFields, + CurriculumUpdate, + Revision, +) +from app.services.curricula import CurriculaService +from app.services.curriculum_files import parse_import +from app.services.errors import AuthError + +router = APIRouter(prefix="/curricula", tags=["Curricula"]) +Identifier = Annotated[int, Path(gt=0)] + + +def get_service(auth: AuthServiceDependency) -> CurriculaService: + """Construct the programme service using request-owned resources.""" + return CurriculaService(auth) + + +Service = Annotated[CurriculaService, Depends(get_service)] + + +@router.get("/catalog") +async def catalog(actor: AuthenticatedUser, service: Service) -> dict[str, object]: + """List programme metadata without loading competency graphs.""" + return await service.catalog(actor) + + +@router.post("", status_code=201) +async def curriculum_create( + data: CurriculumFields, actor: AuthenticatedUser, service: Service +) -> dict[str, object]: + """Create a programme with multiple existing subjects.""" + return await service.curriculum_save(actor, data) + + +@router.put("/{curriculum_id}") +async def curriculum_update( + curriculum_id: Identifier, data: CurriculumUpdate, actor: AuthenticatedUser, service: Service +) -> dict[str, object]: + """Update administrator-owned programme metadata.""" + return await service.curriculum_save(actor, data, curriculum_id, data.expected_version) + + +@router.get("/{curriculum_id}/subjects/{subject_id}") +async def graph( + curriculum_id: Identifier, subject_id: Identifier, actor: AuthenticatedUser, service: Service +) -> dict[str, object]: + """Read one selected subject's competency graph.""" + return await service.graph(actor, curriculum_id, subject_id) + + +@router.post("/{curriculum_id}/undo") +async def undo( + curriculum_id: Identifier, data: Revision, actor: AuthenticatedUser, service: Service +) -> dict[str, object]: + """Undo this actor's latest edit without overwriting intervening changes.""" + return await service.undo(actor, curriculum_id, data.expected_version) + + +@router.get("/{curriculum_id}/subjects/{subject_id}/export") +async def export_file( + curriculum_id: Identifier, subject_id: Identifier, actor: AuthenticatedUser, service: Service +) -> dict: + """Return the versioned portable subject graph to authorized readers.""" + try: + return await service.export_file(actor, curriculum_id, subject_id) + except ValidationError: + raise AuthError( + 422, "Ce graphe dépasse les limites du format d’échange (128 niveaux, 20 000 liens)." + ) from None + + +@router.post("/{curriculum_id}/subjects/{subject_id}/import") +async def import_file( + curriculum_id: Identifier, + subject_id: Identifier, + request: Request, + actor: AuthenticatedUser, + service: Service, +) -> dict: + """Validate strict bounded JSON before invoking the subject-authorized transaction.""" + if request.headers.get("content-type", "").split(";")[0] != "application/json": + raise AuthError(415, "Un fichier JSON est requis.") + return await service.import_file( + actor, curriculum_id, subject_id, parse_import(await request.body()) + ) + + +@router.post("/{curriculum_id}/subjects/{subject_id}/nodes", status_code=201) +async def node_create( + curriculum_id: Identifier, + subject_id: Identifier, + data: CompetencyFields, + actor: AuthenticatedUser, + service: Service, +) -> dict[str, object]: + """Add a competency with zero or more parents.""" + return await service.node_save(actor, curriculum_id, subject_id, data) + + +@router.put("/{curriculum_id}/subjects/{subject_id}/nodes/{node_id}") +async def node_update( + curriculum_id: Identifier, + subject_id: Identifier, + node_id: Identifier, + data: CompetencyFields, + actor: AuthenticatedUser, + service: Service, +) -> dict[str, object]: + """Replace one shared competency and its parent links.""" + return await service.node_save(actor, curriculum_id, subject_id, data, node_id) + + +@router.delete("/{curriculum_id}/subjects/{subject_id}/nodes/{node_id}") +async def node_delete( + curriculum_id: Identifier, + subject_id: Identifier, + node_id: Identifier, + data: Revision, + actor: AuthenticatedUser, + service: Service, +) -> dict[str, object]: + """Remove a node from every branch while retaining its children.""" + return await service.node_delete( + actor, curriculum_id, subject_id, node_id, data.expected_version + ) diff --git a/backend/app/core/http.py b/backend/app/core/http.py index 6391983..60ee8ca 100644 --- a/backend/app/core/http.py +++ b/backend/app/core/http.py @@ -1,6 +1,7 @@ """Early bounded API bodies and application-scoped browser CORS policy.""" import logging +import re import anyio from starlette.middleware.cors import CORSMiddleware @@ -53,6 +54,10 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: return settings = scope["app"].state.auth_settings limit = settings.request_max_bytes + if scope.get("method") == "POST" and re.fullmatch( + r"/api/v1/curricula/[1-9]\d*/subjects/[1-9]\d*/import", scope["path"] + ): + limit = 8 * 1024 * 1024 + 4096 binary = is_document_upload(scope["path"], scope.get("method", "")) if binary: limit = scope["app"].state.document_settings.max_bytes diff --git a/backend/app/main.py b/backend/app/main.py index 962016f..4a3e8f3 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -127,7 +127,7 @@ async def lifespan(application: FastAPI) -> AsyncIterator[None]: application = FastAPI( title="Sophikron API", description="API for the Sophikron educational platform.", - version="0.2.0", + version="0.3.0", lifespan=lifespan, ) application.include_router(router) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index f763abd..1f657bc 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -11,6 +11,8 @@ User, UserRole, ) +from app.models.curricula import Competency, CompetencyLink, Curriculum, CurriculumSubject +from app.models.curriculum_undo import CurriculumUndo from app.models.groups import ( PromotionCustomGroup, PromotionCustomGroupMember, @@ -51,6 +53,11 @@ ) __all__ = [ + "CurriculumUndo", + "Competency", + "CompetencyLink", + "Curriculum", + "CurriculumSubject", "KholloscopeRun", "KholloscopeWorkflow", "KholleWish", diff --git a/backend/app/models/curricula.py b/backend/app/models/curricula.py new file mode 100644 index 0000000..cbfe475 --- /dev/null +++ b/backend/app/models/curricula.py @@ -0,0 +1,98 @@ +"""Shared two-year curricula and subject-scoped directed acyclic competency graphs.""" + +from sqlalchemy import ( + BigInteger, + Boolean, + CheckConstraint, + ForeignKey, + ForeignKeyConstraint, + Identity, + Integer, + String, + Text, + UniqueConstraint, +) +from sqlalchemy.orm import Mapped, mapped_column + +from app.core.database import Base + + +class Curriculum(Base): + """Represent one complete pathway and its current multi-subject programme.""" + + __tablename__ = "curricula" + __table_args__ = (CheckConstraint("length(btrim(title)) > 0", name="title"),) + id: Mapped[int] = mapped_column(BigInteger, Identity(always=True), primary_key=True) + title: Mapped[str] = mapped_column(String(160)) + description: Mapped[str | None] = mapped_column(Text) + source_url: Mapped[str | None] = mapped_column(String(2000)) + is_active: Mapped[bool] = mapped_column(Boolean, server_default="true") + version: Mapped[int] = mapped_column(BigInteger, server_default="0") + + +class CurriculumSubject(Base): + """Allow only administrator-selected existing subjects in a curriculum.""" + + __tablename__ = "curriculum_subjects" + curriculum_id: Mapped[int] = mapped_column( + ForeignKey("sophikron.curricula.id", ondelete="CASCADE"), primary_key=True + ) + subject_id: Mapped[int] = mapped_column( + ForeignKey("sophikron.subjects.id", ondelete="RESTRICT"), primary_key=True + ) + + +class Competency(Base): + """Store one editable identity regardless of its number of parents.""" + + __tablename__ = "competencies" + __table_args__ = ( + ForeignKeyConstraint( + ["curriculum_id", "subject_id"], + [ + "sophikron.curriculum_subjects.curriculum_id", + "sophikron.curriculum_subjects.subject_id", + ], + ondelete="CASCADE", + ), + UniqueConstraint("curriculum_id", "subject_id", "id", name="uq_competency_scope"), + CheckConstraint("length(btrim(name)) > 0", name="name"), + CheckConstraint("semester BETWEEN 1 AND 4", name="semester"), + CheckConstraint("color ~ '^#[0-9A-Fa-f]{6}$'", name="color"), + CheckConstraint("position >= 0", name="position"), + ) + id: Mapped[int] = mapped_column(BigInteger, Identity(always=True), primary_key=True) + curriculum_id: Mapped[int] = mapped_column(BigInteger, index=True) + subject_id: Mapped[int] = mapped_column(BigInteger) + name: Mapped[str] = mapped_column(String(300)) + semester: Mapped[int | None] = mapped_column(Integer) + knowledge: Mapped[str | None] = mapped_column(Text) + comment: Mapped[str | None] = mapped_column(Text) + color: Mapped[str | None] = mapped_column(String(7)) + position: Mapped[int] = mapped_column(Integer, server_default="0") + + +class CompetencyLink(Base): + """Constrain both ends of an edge to the same curriculum and subject.""" + + __tablename__ = "competency_links" + __table_args__ = ( + *( + ForeignKeyConstraint( + ["curriculum_id", "subject_id", endpoint], + [ + "sophikron.competencies.curriculum_id", + "sophikron.competencies.subject_id", + "sophikron.competencies.id", + ], + ondelete="CASCADE", + name=f"fk_competency_links_{endpoint}", + ) + for endpoint in ("parent_id", "child_id") + ), + CheckConstraint("parent_id <> child_id", name="different_nodes"), + ) + curriculum_id: Mapped[int] = mapped_column(BigInteger) + subject_id: Mapped[int] = mapped_column(BigInteger) + parent_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + child_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, index=True) diff --git a/backend/app/models/curriculum_undo.py b/backend/app/models/curriculum_undo.py new file mode 100644 index 0000000..d1abf17 --- /dev/null +++ b/backend/app/models/curriculum_undo.py @@ -0,0 +1,24 @@ +"""Bounded inverse operations for collaborative programme editing.""" + +from sqlalchemy import BigInteger, ForeignKey, Identity +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column + +from app.core.database import Base + + +class CurriculumUndo(Base): + """Retain inverse data with the exact revision it can safely undo.""" + + __tablename__ = "curriculum_undo" + id: Mapped[int] = mapped_column(BigInteger, Identity(always=True), primary_key=True) + actor_id: Mapped[int] = mapped_column(ForeignKey("sophikron.users.id", ondelete="CASCADE")) + curriculum_id: Mapped[int] = mapped_column( + ForeignKey("sophikron.curricula.id", ondelete="CASCADE") + ) + subject_id: Mapped[int] = mapped_column( + ForeignKey("sophikron.subjects.id", ondelete="RESTRICT") + ) + node_id: Mapped[int] = mapped_column(BigInteger) + after_version: Mapped[int] = mapped_column(BigInteger) + payload: Mapped[dict] = mapped_column(JSONB) diff --git a/backend/app/models/promotions.py b/backend/app/models/promotions.py index d64692a..d310667 100644 --- a/backend/app/models/promotions.py +++ b/backend/app/models/promotions.py @@ -34,6 +34,9 @@ class Promotion(Base): ) id: Mapped[int] = mapped_column(BigInteger, Identity(always=True), primary_key=True) + curriculum_id: Mapped[int | None] = mapped_column( + ForeignKey("sophikron.curricula.id", ondelete="RESTRICT"), index=True + ) year: Mapped[int] = mapped_column(Integer, index=True) identifier: Mapped[str] = mapped_column(String(64)) color: Mapped[str] = mapped_column(String(7)) diff --git a/backend/app/repositories/curricula.py b/backend/app/repositories/curricula.py new file mode 100644 index 0000000..133fbf1 --- /dev/null +++ b/backend/app/repositories/curricula.py @@ -0,0 +1,45 @@ +"""Database reads for programme catalogues and subject-scoped graphs.""" + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models.curricula import Competency, CompetencyLink, Curriculum + + +class CurriculaRepository: + """Keep graph queries separate from permissions and transaction ownership.""" + + def __init__(self, db: AsyncSession) -> None: + """Bind the request's database session.""" + self.db = db + + async def curriculum(self, identifier: int, *, lock: bool = False) -> Curriculum | None: + """Read a programme, optionally serializing its graph edits.""" + statement = select(Curriculum).where(Curriculum.id == identifier) + return await self.db.scalar(statement.with_for_update() if lock else statement) + + async def nodes(self, curriculum_id: int, subject_id: int) -> list[Competency]: + """Read one subject's graph in stable sibling order.""" + return list( + await self.db.scalars( + select(Competency) + .where( + Competency.curriculum_id == curriculum_id, Competency.subject_id == subject_id + ) + .order_by(Competency.position, Competency.id) + ) + ) + + async def edges(self, curriculum_id: int, subject_id: int) -> list[tuple[int, int]]: + """Read parent-child pairs without expanding shared nodes into copies.""" + return [ + (parent, child) + for parent, child in await self.db.execute( + select(CompetencyLink.parent_id, CompetencyLink.child_id) + .where( + CompetencyLink.curriculum_id == curriculum_id, + CompetencyLink.subject_id == subject_id, + ) + .order_by(CompetencyLink.parent_id, CompetencyLink.child_id) + ) + ] diff --git a/backend/app/schemas/administration.py b/backend/app/schemas/administration.py index 4be7944..a5bc5c2 100644 --- a/backend/app/schemas/administration.py +++ b/backend/app/schemas/administration.py @@ -13,6 +13,7 @@ class PromotionCreate(InputModel): """Create an active promotion using a year, identifier and hexadecimal CSS color.""" year: int = Field(ge=1, le=9999) + curriculum_id: int | None = Field(default=None, gt=0) identifier: str = Field(min_length=1, max_length=64) color: str = Field(pattern=r"^#[0-9A-Fa-f]{6}$") @@ -32,10 +33,17 @@ def normalize_color(cls, value: str) -> str: return value.upper() +class PromotionSnapshot(PromotionCreate): + """Read legacy pathway references only in historical event snapshots.""" + + track_id: int | None = Field(default=None, gt=0) + + class PromotionUpdate(InputModel): """Update supplied fields, including reversible archive state; null is never a value.""" year: int | None = Field(default=None, ge=1, le=9999) + curriculum_id: int | None = Field(default=None, gt=0) identifier: str | None = Field(default=None, min_length=1, max_length=64) color: str | None = Field(default=None, pattern=r"^#[0-9A-Fa-f]{6}$") is_active: bool | None = None @@ -105,6 +113,7 @@ class PromotionResponse(BaseModel): """Expose promotion metadata and the current number of linked permanent accounts.""" id: int + curriculum_id: int | None = None year: int identifier: str color: str @@ -177,7 +186,7 @@ class EventResponse(BaseModel): subject_user_id: int | None actor_role: Literal["admin", "teacher", "kholleur", "user"] | None subject_role: Literal["admin", "teacher", "kholleur", "user"] | None - promotion_snapshot: PromotionCreate | None + promotion_snapshot: PromotionSnapshot | None resource_type: str | None resource_id: int | None data: dict[str, object] diff --git a/backend/app/schemas/curricula.py b/backend/app/schemas/curricula.py new file mode 100644 index 0000000..fb59ff6 --- /dev/null +++ b/backend/app/schemas/curricula.py @@ -0,0 +1,142 @@ +"""Bounded contracts for programme metadata and modular competency editing.""" + +from typing import Annotated, Literal + +from pydantic import Field, HttpUrl, field_validator, model_validator + +from app.schemas.auth import InputModel + +Identifier = Annotated[int, Field(gt=0)] + + +class Revision(InputModel): + """Reject stale edits using a programme-wide revision.""" + + expected_version: int = Field(ge=0) + + +def trim_name(value: str) -> str: + """Return a nonempty normalized display name.""" + value = " ".join(value.split()) + if not value: + raise ValueError("Un nom est requis.") + return value + + +class CurriculumFields(InputModel): + """Create a self-contained programme using existing subjects and an official PDF link.""" + + title: str = Field(min_length=1, max_length=160) + description: str | None = Field(default=None, max_length=3000) + source_url: HttpUrl | None = None + subject_ids: list[Identifier] = Field(min_length=1, max_length=100) + is_active: bool = True + + @field_validator("title") + @classmethod + def trim_title(cls, value: str) -> str: + """Reject blank programme titles.""" + return trim_name(value) + + @field_validator("source_url") + @classmethod + def public_link(cls, value: HttpUrl | None) -> HttpUrl | None: + """Reject credentials and unbounded source URLs; no server-side fetch occurs.""" + if value and (value.username or value.password or len(str(value)) > 2000): + raise ValueError("Lien invalide.") + return value + + @field_validator("subject_ids") + @classmethod + def unique_subjects(cls, value: list[int]) -> list[int]: + """Require each subject once.""" + if len(set(value)) != len(value): + raise ValueError("Matière dupliquée.") + return value + + +class CurriculumUpdate(CurriculumFields, Revision): + """Edit programme settings using optimistic concurrency.""" + + +class CompetencyFields(Revision): + """Replace one competency and all its parent links in a single transaction.""" + + name: str = Field(min_length=1, max_length=300) + semester: int | None = Field(default=None, ge=1, le=4) + knowledge: str | None = Field(default=None, max_length=12000) + comment: str | None = Field(default=None, max_length=12000) + color: str | None = Field(default=None, pattern=r"^#[0-9A-Fa-f]{6}$") + position: int = Field(default=0, ge=0, le=10000) + parent_ids: list[Identifier] = Field(default_factory=list, max_length=100) + + @field_validator("name") + @classmethod + def nonempty_name(cls, value: str) -> str: + """Normalize names while retaining punctuation and accents.""" + return trim_name(value) + + @field_validator("knowledge", "comment") + @classmethod + def empty_to_null(cls, value: str | None) -> str | None: + """Store empty optional text as null for portable future exports.""" + return value.strip() or None if value is not None else None + + @field_validator("parent_ids") + @classmethod + def unique_parents(cls, value: list[int]) -> list[int]: + """Reject duplicate edges.""" + if len(set(value)) != len(value): + raise ValueError("Parent dupliqué.") + return value + + +class PortableCompetency(CompetencyFields): + """Use file-local identities; codes are recalculated after import.""" + + id: Identifier + expected_version: Literal[0] = 0 + + +class CompetencyFile(InputModel): + """Validate a bounded flat DAG without recursive traversal or executable content.""" + + format: Literal["sophikron.competencies"] + version: Literal[1] + subject_name: str = Field(max_length=100) + nodes: list[PortableCompetency] = Field(max_length=2000) + + @model_validator(mode="after") + def validate_graph(self) -> "CompetencyFile": + """Reject duplicate identities, dangling edges, cycles and depth above 128.""" + by_id = {node.id: node for node in self.nodes} + if len(by_id) != len(self.nodes): + raise ValueError("Identifiants dupliqués.") + incoming = {node.id: len(node.parent_ids) for node in self.nodes} + children: dict[int, list[int]] = {} + if sum(incoming.values()) > 20000: + raise ValueError("Trop de relations.") + for node in self.nodes: + for parent in node.parent_ids: + if parent not in by_id: + raise ValueError("Parent introuvable.") + children.setdefault(parent, []).append(node.id) + queue = [identifier for identifier, count in incoming.items() if not count] + depth = dict.fromkeys(queue, 1) + for identifier in queue: + for child in children.get(identifier, []): + depth[child] = max(depth.get(child, 0), depth[identifier] + 1) + if depth[child] > 128: + raise ValueError("Profondeur maximale dépassée.") + incoming[child] -= 1 + if not incoming[child]: + queue.append(child) + if len(queue) != len(self.nodes): + raise ValueError("Cycle entre compétences.") + return self + + +class CompetencyImport(Revision): + """Apply a validated portable graph to a revision-matching subject.""" + + document: CompetencyFile diff --git a/backend/app/schemas/lessons.py b/backend/app/schemas/lessons.py index de12851..92c57bb 100644 --- a/backend/app/schemas/lessons.py +++ b/backend/app/schemas/lessons.py @@ -11,10 +11,28 @@ from app.schemas.auth import InputModel LessonIcon = Literal[ - "book", "science", "calculator", "language", "history", "code", "school", - "physics", "biology", "geology", "engineering", "astronomy", "statistics", - "economics", "finance", "sociology", "geography", "philosophy", "literature", - "ancient", "art", "music", + "book", + "science", + "calculator", + "language", + "history", + "code", + "school", + "physics", + "biology", + "geology", + "engineering", + "astronomy", + "statistics", + "economics", + "finance", + "sociology", + "geography", + "philosophy", + "literature", + "ancient", + "art", + "music", ] ElementKind = Literal["section", "subsection", "text", "youtube", "file", "table"] ScheduleMode = Literal["inherit", "from", "range"] diff --git a/backend/app/services/activity.py b/backend/app/services/activity.py index 9717709..b95da69 100644 --- a/backend/app/services/activity.py +++ b/backend/app/services/activity.py @@ -12,11 +12,24 @@ from app.models import ActivityEvent, Promotion, Role, UserRole from app.models.site import Subject -from app.schemas.administration import PromotionCreate +from app.schemas.administration import PromotionCreate, PromotionSnapshot from app.schemas.auth import InputModel, RoleCodes from app.schemas.site import SubjectFields +class CurriculumActivity(InputModel): + """Describe programme changes without retaining long teaching text in the journal.""" + + action: str = Field(max_length=40) + curriculum_title: str = Field(max_length=160) + subject_name: str | None = Field(default=None, max_length=100) + competency_name: str | None = Field(default=None, max_length=300) + changed_fields: list[str] = Field(default_factory=list, max_length=20) + parent_count: int = Field(default=0, ge=0) + child_count: int = Field(default=0, ge=0) + imported_count: int = Field(default=0, ge=0, le=2000) + + class EmptyData(InputModel): """Reject arbitrary metadata, particularly credentials and copied personal identities.""" @@ -24,16 +37,18 @@ class EmptyData(InputModel): class PromotionChanges(InputModel): """Describe changed promotion fields without storing arbitrary request bodies.""" - changed_fields: list[Literal["year", "identifier", "color"]] = Field(max_length=3) - previous: PromotionCreate - current: PromotionCreate + changed_fields: list[Literal["year", "identifier", "color", "track_id", "curriculum_id"]] = ( + Field(max_length=5) + ) + previous: PromotionSnapshot + current: PromotionSnapshot class AccountArchiveCause(InputModel): """Identify an automatic promotion action without copying pupil identities.""" promotion_id: int | None = Field(default=None, gt=0) - promotion: PromotionCreate | None = None + promotion: PromotionSnapshot | None = None class PromotionArchiveCounts(InputModel): @@ -208,7 +223,7 @@ class LessonActivity(InputModel): removed_count: int | None = Field(default=None, ge=1, le=500) direction: Literal["up", "down"] | None = None promotion_id: int | None = Field(default=None, gt=0) - promotion: PromotionCreate | None = None + promotion: PromotionSnapshot | None = None previous_period: LessonPeriod | None = None period: LessonPeriod | None = None @@ -559,6 +574,24 @@ def __init__( ) +for _resource, _label in (("track", "Filière"), ("curriculum", "Référentiel")): + EVENTS[f"{_resource}.saved"] = EventDefinition( + resource=_resource, + label=f"{_label} enregistré", + icon="book", + message=f"{{actor}} a modifié un élément du catalogue : {_label.lower()}.", + ) + + +EVENTS["curriculum.changed"] = EventDefinition( + resource="curriculum", + payload=CurriculumActivity, + label="Modification du programme", + icon="book", + message="{actor} a modifié le programme pédagogique.", +) + + def event_family(code: str) -> str: """Return the journal family for a registered event code. diff --git a/backend/app/services/administration.py b/backend/app/services/administration.py index 71cdf7c..955e0ea 100644 --- a/backend/app/services/administration.py +++ b/backend/app/services/administration.py @@ -25,6 +25,7 @@ UserPromotion, UserRole, ) +from app.models.curricula import Curriculum from app.models.site import Subject, TeacherSubject from app.repositories.administration import AdministrationRepository from app.repositories.groups import GroupsRepository @@ -121,6 +122,7 @@ async def _promotion_profiles( return [ PromotionResponse( id=item.id, + curriculum_id=item.curriculum_id, year=item.year, identifier=item.identifier, color=item.color, @@ -214,6 +216,7 @@ async def create_promotion( try: async with self.db.begin(): await self.auth._actor(actor, permission="promotions.manage") + await self._validate_curriculum(data.curriculum_id) promotion = Promotion(**data.model_dump(), is_active=True) self.db.add(promotion) await self.db.flush() @@ -237,8 +240,14 @@ async def update_promotion( await self.auth._lifecycle_lock() await self.auth._actor(actor, permission="promotions.manage") promotion = await self._promotion(promotion_id, lock=True) + if ( + "curriculum_id" in data.model_fields_set + and data.curriculum_id != promotion.curriculum_id + ): + await self._validate_curriculum(data.curriculum_id) previous = { - field: getattr(promotion, field) for field in ("identifier", "year", "color") + field: getattr(promotion, field) + for field in ("identifier", "year", "color", "curriculum_id") } changes = { key: value @@ -292,6 +301,13 @@ async def update_promotion( except IntegrityError: raise AuthError(409, "Cette promotion existe déjà.") from None + async def _validate_curriculum(self, curriculum_id: int | None) -> None: + """Permit unassigned promotions and require an active explicitly selected pathway.""" + if curriculum_id is not None: + curriculum = await self.db.get(Curriculum, curriculum_id) + if curriculum is None or not curriculum.is_active: + raise AuthError(422, "Choisissez un référentiel actif.") + async def promotion_archive_impact( self, actor: UserContext, promotion_id: int ) -> PromotionArchiveImpact: diff --git a/backend/app/services/competency_codes.py b/backend/app/services/competency_codes.py new file mode 100644 index 0000000..e1d73c1 --- /dev/null +++ b/backend/app/services/competency_codes.py @@ -0,0 +1,57 @@ +"""Deterministic single-identity numbering for shared competency graphs.""" + +from collections import deque +from collections.abc import Sequence + +from app.models.curricula import Competency + + +def alphabetic(index: int, *, uppercase: bool = False) -> str: + """Return a one-based alphabetic index, continuing after Z with AA.""" + result = "" + while index: + index, remainder = divmod(index - 1, 26) + result = chr(ord("a") + remainder) + result + return result.upper() if uppercase else result + + +def competency_codes( + nodes: Sequence[Competency], edges: Sequence[tuple[int, int]] +) -> tuple[dict[int, str], list[int]]: + """Assign one code per node using the first shortest path in stable sibling order. + + Parameters + ---------- + nodes + Subject-scoped competencies, ordered by position and identity. + edges + Existing acyclic parent-child relationships. + + Returns + ------- + tuple[dict[int, str], list[int]] + Derived codes and node identities in natural hierarchical code order. + """ + order = {node.id: (node.position, node.id) for node in nodes} + children: dict[int, list[int]] = {} + parented = set() + for parent, child in edges: + children.setdefault(parent, []).append(child) + parented.add(child) + roots = sorted((node.id for node in nodes if node.id not in parented), key=order.__getitem__) + codes = {identifier: alphabetic(i, uppercase=True) for i, identifier in enumerate(roots, 1)} + paths = {identifier: (i,) for i, identifier in enumerate(roots, 1)} + queue = deque(roots) + while queue: + parent = queue.popleft() + index = 0 + for child in sorted(children.get(parent, []), key=order.__getitem__): + if child in codes: + continue + index += 1 + depth = len(paths[parent]) + segment = str(index) if depth % 2 else alphabetic(index) + codes[child] = f"{codes[parent]}.{segment}" + paths[child] = (*paths[parent], index) + queue.append(child) + return codes, sorted(codes, key=paths.__getitem__) diff --git a/backend/app/services/curricula.py b/backend/app/services/curricula.py new file mode 100644 index 0000000..640681d --- /dev/null +++ b/backend/app/services/curricula.py @@ -0,0 +1,590 @@ +"""Transactional programme administration and collaborative competency graph editing.""" + +from sqlalchemy import delete, or_, select, text +from sqlalchemy.exc import IntegrityError + +from app.models.curricula import Competency, CompetencyLink, Curriculum, CurriculumSubject +from app.models.curriculum_undo import CurriculumUndo +from app.models.site import Subject, TeacherSubject +from app.repositories.curricula import CurriculaRepository +from app.schemas.curricula import ( + CompetencyFields, + CompetencyFile, + CompetencyImport, + CurriculumFields, +) +from app.services.activity import record_event +from app.services.auth import AuthService, UserContext +from app.services.competency_codes import competency_codes +from app.services.errors import AuthError + + +def validate_parents(node_id: int, parent_ids: list[int], edges: list[tuple[int, int]]) -> None: + """Reject new incoming edges that would make the graph cyclic. + + Parameters + ---------- + node_id + Competency whose incoming edges are replaced. + parent_ids + Proposed parents, already scoped to the same subject. + edges + Existing parent-child pairs. + + Returns + ------- + None + Raise a validation error if a parent is the node or one of its descendants. + """ + children: dict[int, list[int]] = {} + for parent, child in edges: + children.setdefault(parent, []).append(child) + descendants, pending = set(), [node_id] + while pending: + current = pending.pop() + if current in descendants: + continue + descendants.add(current) + pending.extend(children.get(current, [])) + if descendants.intersection(parent_ids): + raise AuthError(422, "Ce rattachement créerait un cycle entre les compétences.") + + +def fields(row: Curriculum | Competency) -> dict[str, object]: + """Serialize mapped programme fields without ORM internals.""" + return { + column.key: getattr(row, column.key) + for column in row.__table__.columns + if column.key != "name_key" + } + + +class CurriculaService: + """Recheck live permissions and serialize edits against staff assignment changes.""" + + def __init__(self, auth: AuthService) -> None: + """Reuse authentication resources and the request-owned transaction.""" + self.auth, self.db = auth, auth.db + self.repo = CurriculaRepository(self.db) + + async def _access(self, actor: UserContext, *, write: bool = False) -> set[str]: + """Revalidate the session and return fresh explicitly granted capabilities.""" + if write: + await self.auth._lifecycle_lock() + await self.auth._actor(actor, permission="curricula.read") + return set(await self.auth.repo.permissions(actor.id)) + + async def _event( + self, + actor: UserContext, + resource: str, + identifier: int, + action: str = "referential_saved", + node: Competency | None = None, + changed: list[str] | None = None, + ) -> None: + """Journal human-readable identities and the exact type of successful change.""" + row = await self.repo.curriculum(identifier) + subject = await self.db.get(Subject, node.subject_id) if node else None + edges = await self.repo.edges(identifier, node.subject_id) if node else [] + await record_event( + self.db, + "curriculum.changed", + actor.id, + resource_type="curriculum", + resource_id=identifier, + data={ + "action": action, + "curriculum_title": row.title, + "subject_name": subject.name if subject else None, + "competency_name": node.name if node else None, + "changed_fields": changed or [], + "parent_count": sum(child == node.id for _, child in edges) if node else 0, + "child_count": sum(parent == node.id for parent, _ in edges) if node else 0, + }, + ) + + async def _remember( + self, + actor: UserContext, + row: Curriculum, + subject_id: int, + node_id: int, + before: dict | None, + edges: list[tuple[int, int]], + ) -> None: + """Retain at most twenty inverse operations per actor and programme.""" + self.db.add( + CurriculumUndo( + actor_id=actor.id, + curriculum_id=row.id, + subject_id=subject_id, + node_id=node_id, + after_version=row.version, + payload={ + "before_version": row.version - 1, + "node": before, + "edges": [list(edge) for edge in edges if node_id in edge], + }, + ) + ) + await self.db.flush() + old = ( + select(CurriculumUndo.id) + .where(CurriculumUndo.actor_id == actor.id, CurriculumUndo.curriculum_id == row.id) + .order_by(CurriculumUndo.id.desc()) + .offset(20) + ) + await self.db.execute(delete(CurriculumUndo).where(CurriculumUndo.id.in_(old))) + + async def catalog(self, actor: UserContext) -> dict[str, object]: + """List metadata only; graph data is fetched for one selected subject.""" + async with self.db.begin(): + permissions = await self._access(actor) + admin = "curricula.manage" in permissions + subjects = list(await self.db.scalars(select(Subject).order_by(Subject.name_key))) + assignments = set( + await self.db.scalars( + select(TeacherSubject.subject_id).where(TeacherSubject.user_id == actor.id) + ) + ) + curricula = list(await self.db.scalars(select(Curriculum).order_by(Curriculum.title))) + links = (await self.db.execute(select(CurriculumSubject))).scalars().all() + return { + "can_manage": admin, + "subjects": [ + { + "id": s.id, + "name": s.name, + "color": s.color, + "icon": s.icon, + "is_active": s.is_active, + "can_edit": admin + or ( + "curricula.edit" in permissions and s.id in assignments and s.is_active + ), + } + for s in subjects + ], + "curricula": [ + { + **fields(c), + "subject_ids": [s.subject_id for s in links if s.curriculum_id == c.id], + } + for c in curricula + ], + } + + async def curriculum_save( + self, + actor: UserContext, + data: CurriculumFields, + identifier: int | None = None, + version: int | None = None, + ) -> dict[str, object]: + """Save admin-owned metadata; refuse removing subjects that still contain nodes.""" + async with self.db.begin(): + permissions = await self._access(actor, write=True) + if "curricula.manage" not in permissions: + raise AuthError(403, "Seul un administrateur peut gérer les référentiels.") + row = await self.repo.curriculum(identifier, lock=True) if identifier else Curriculum() + if row is None: + raise AuthError(404, "Référentiel introuvable.") + if identifier and row.version != version: + raise AuthError(409, "Ce référentiel a changé. Actualisez la page.") + available = set( + await self.db.scalars( + select(Subject.id).where(Subject.id.in_(data.subject_ids), Subject.is_active) + ) + ) + previous = ( + set( + await self.db.scalars( + select(CurriculumSubject.subject_id).where( + CurriculumSubject.curriculum_id == identifier + ) + ) + ) + if identifier + else set() + ) + if not set(data.subject_ids) <= available | previous: + raise AuthError(422, "Choisissez des matières existantes et actives.") + removed = previous - set(data.subject_ids) + if removed and await self.db.scalar( + select(Competency.id) + .where(Competency.curriculum_id == identifier, Competency.subject_id.in_(removed)) + .limit(1) + ): + raise AuthError( + 409, "Une matière contenant des compétences ne peut pas être retirée." + ) + row.title = data.title + row.description = data.description.strip() or None if data.description else None + row.source_url = str(data.source_url) if data.source_url else None + row.is_active, row.version = data.is_active, row.version + 1 if identifier else 0 + self.db.add(row) + await self.db.flush() + if removed: + await self.db.execute( + delete(CurriculumSubject).where( + CurriculumSubject.curriculum_id == row.id, + CurriculumSubject.subject_id.in_(removed), + ) + ) + self.db.add_all( + CurriculumSubject(curriculum_id=row.id, subject_id=s) + for s in set(data.subject_ids) - previous + ) + await self.db.flush() + await self._event( + actor, + "curriculum", + row.id, + "referential_archived" + if not data.is_active + else "referential_updated" + if identifier + else "referential_created", + changed=sorted(data.model_fields_set - {"expected_version"}), + ) + return {**fields(row), "subject_ids": data.subject_ids} + + async def _graph_access( + self, + actor: UserContext, + curriculum_id: int, + subject_id: int, + *, + write: bool = False, + version: int | None = None, + ) -> Curriculum: + """Scope both graph endpoints and authorize live subject assignments.""" + permissions = await self._access(actor, write=write) + row = await self.repo.curriculum(curriculum_id, lock=write) + if row is None or await self.db.get(CurriculumSubject, (curriculum_id, subject_id)) is None: + raise AuthError(404, "Référentiel ou matière introuvable.") + if write: + subject = await self.db.get(Subject, subject_id) + admin = "curricula.manage" in permissions + assigned = await self.db.get(TeacherSubject, (actor.id, subject_id)) + if not admin and ("curricula.edit" not in permissions or assigned is None): + raise AuthError(403, "Vous ne pouvez modifier que vos matières.") + if not row.is_active or not subject.is_active: + raise AuthError(409, "Ce référentiel ou cette matière est archivé.") + if row.version != version: + raise AuthError(409, "Le référentiel a changé. Actualisez avant de réessayer.") + return row + + async def _graph(self, row: Curriculum, subject_id: int) -> dict[str, object]: + """Return a compact portable representation of one subject's graph.""" + nodes = await self.repo.nodes(row.id, subject_id) + edges = await self.repo.edges(row.id, subject_id) + codes, ordered = competency_codes(nodes, edges) + by_id = {node.id: node for node in nodes} + return { + "curriculum_id": row.id, + "subject_id": subject_id, + "version": row.version, + "nodes": [ + {**fields(by_id[identifier]), "code": codes[identifier]} for identifier in ordered + ], + "edges": [{"parent_id": p, "child_id": c} for p, c in edges], + } + + async def graph( + self, actor: UserContext, curriculum_id: int, subject_id: int + ) -> dict[str, object]: + """Read one graph for any authorized staff member.""" + async with self.db.begin(): + row = await self._graph_access(actor, curriculum_id, subject_id) + return await self._graph(row, subject_id) + + async def export_file(self, actor: UserContext, curriculum_id: int, subject_id: int) -> dict: + """Export the complete subject DAG, preserving shared identities and all content.""" + import json + + from app.services.curriculum_files import FILE_LIMIT + + async with self.db.begin(): + row = await self._graph_access(actor, curriculum_id, subject_id) + graph = await self._graph(row, subject_id) + subject = await self.db.get(Subject, subject_id) + document = CompetencyFile.model_validate( + { + "format": "sophikron.competencies", + "version": 1, + "subject_name": subject.name, + "nodes": [ + { + **{ + key: value + for key, value in node.items() + if key not in {"curriculum_id", "subject_id", "code"} + }, + "parent_ids": [ + edge["parent_id"] + for edge in graph["edges"] + if edge["child_id"] == node["id"] + ], + } + for node in graph["nodes"] + ], + } + ).model_dump(exclude={"nodes": {"__all__": {"expected_version"}}}) + if len(json.dumps(document, ensure_ascii=False).encode()) > FILE_LIMIT: + raise AuthError(413, "Export supérieur à la limite de 4 Mo.") + return document + + async def import_file( + self, actor: UserContext, curriculum_id: int, subject_id: int, data: CompetencyImport + ) -> dict: + """Append an entire validated graph atomically using fresh database identities.""" + async with self.db.begin(): + row = await self._graph_access( + actor, curriculum_id, subject_id, write=True, version=data.expected_version + ) + existing = await self.repo.nodes(curriculum_id, subject_id) + if len(existing) + len(data.document.nodes) > 2000: + raise AuthError(422, "Limite de 2 000 compétences par matière atteinte.") + if not data.document.nodes: + raise AuthError(422, "Le fichier ne contient aucune compétence.") + mapped: dict[int, Competency] = {} + for item in data.document.nodes: + node = Competency( + curriculum_id=curriculum_id, + subject_id=subject_id, + **item.model_dump(exclude={"id", "expected_version", "parent_ids"}), + ) + self.db.add(node) + mapped[item.id] = node + await self.db.flush() + self.db.add_all( + CompetencyLink( + curriculum_id=curriculum_id, + subject_id=subject_id, + parent_id=mapped[parent].id, + child_id=mapped[item.id].id, + ) + for item in data.document.nodes + for parent in item.parent_ids + ) + row.version += 1 + await self.db.flush() + await self._remember(actor, row, subject_id, 0, None, []) + history = await self.db.scalar( + select(CurriculumUndo) + .where( + CurriculumUndo.actor_id == actor.id, + CurriculumUndo.curriculum_id == curriculum_id, + ) + .order_by(CurriculumUndo.id.desc()) + .limit(1) + ) + history.payload = { + **history.payload, + "created_ids": [node.id for node in mapped.values()], + } + subject = await self.db.get(Subject, subject_id) + await record_event( + self.db, + "curriculum.changed", + actor.id, + resource_type="curriculum", + resource_id=curriculum_id, + data={ + "action": "competencies_imported", + "curriculum_title": row.title, + "subject_name": subject.name, + "imported_count": len(mapped), + }, + ) + return {**await self._graph(row, subject_id), "can_undo": True} + + async def node_save( + self, + actor: UserContext, + curriculum_id: int, + subject_id: int, + data: CompetencyFields, + node_id: int | None = None, + ) -> dict[str, object]: + """Create or replace a competency and incoming edges with cycle prevention.""" + try: + async with self.db.begin(): + row = await self._graph_access( + actor, curriculum_id, subject_id, write=True, version=data.expected_version + ) + nodes = {n.id: n for n in await self.repo.nodes(curriculum_id, subject_id)} + if node_id is not None and node_id not in nodes: + raise AuthError(404, "Compétence introuvable.") + if not set(data.parent_ids) <= nodes.keys(): + raise AuthError( + 422, "Les parents doivent appartenir à cette matière du référentiel." + ) + if node_id is None and len(nodes) >= 2000: + raise AuthError(422, "Limite de 2 000 compétences par matière atteinte.") + validate_parents( + node_id or -1, data.parent_ids, await self.repo.edges(curriculum_id, subject_id) + ) + node = ( + nodes[node_id] + if node_id + else Competency(curriculum_id=curriculum_id, subject_id=subject_id) + ) + before = fields(node) if node_id else None + previous_edges = await self.repo.edges(curriculum_id, subject_id) + changed = [ + key + for key, value in data.model_dump( + exclude={"expected_version", "parent_ids"} + ).items() + if before is None or before.get(key) != value + ] + if set(data.parent_ids) != {p for p, c in previous_edges if c == node.id}: + changed.append("parent_ids") + for key, value in data.model_dump( + exclude={"expected_version", "parent_ids"} + ).items(): + setattr(node, key, value) + self.db.add(node) + await self.db.flush() + await self.db.execute( + delete(CompetencyLink).where(CompetencyLink.child_id == node.id) + ) + self.db.add_all( + CompetencyLink( + curriculum_id=curriculum_id, + subject_id=subject_id, + parent_id=p, + child_id=node.id, + ) + for p in data.parent_ids + ) + row.version += 1 + await self.db.flush() + await self._remember(actor, row, subject_id, node.id, before, previous_edges) + await self._event( + actor, + "curriculum", + row.id, + "competency_updated" if node_id else "competency_created", + node, + changed, + ) + return {**await self._graph(row, subject_id), "can_undo": True} + except IntegrityError: + raise AuthError(409, "Le référentiel a changé. Actualisez la page.") from None + + async def node_delete( + self, actor: UserContext, curriculum_id: int, subject_id: int, node_id: int, version: int + ) -> dict[str, object]: + """Delete only the selected node; cascading edges leave all children intact.""" + async with self.db.begin(): + row = await self._graph_access( + actor, curriculum_id, subject_id, write=True, version=version + ) + nodes = {n.id: n for n in await self.repo.nodes(curriculum_id, subject_id)} + if node_id not in nodes: + raise AuthError(404, "Compétence introuvable.") + before = fields(nodes[node_id]) + previous_edges = await self.repo.edges(curriculum_id, subject_id) + await self._event(actor, "curriculum", row.id, "competency_deleted", nodes[node_id]) + await self.db.delete(nodes[node_id]) + row.version += 1 + await self.db.flush() + await self._remember(actor, row, subject_id, node_id, before, previous_edges) + return {**await self._graph(row, subject_id), "can_undo": True} + + async def undo(self, actor: UserContext, curriculum_id: int, version: int) -> dict[str, object]: + """Apply only a revision-matching inverse after rechecking subject authorization.""" + async with self.db.begin(): + await self._access(actor, write=True) + entry = await self.db.scalar( + select(CurriculumUndo) + .where( + CurriculumUndo.actor_id == actor.id, + CurriculumUndo.curriculum_id == curriculum_id, + ) + .order_by(CurriculumUndo.id.desc()) + .limit(1) + ) + if entry is None: + raise AuthError(409, "Aucune action à annuler.") + row = await self._graph_access( + actor, curriculum_id, entry.subject_id, write=True, version=version + ) + if entry.after_version != row.version: + raise AuthError( + 409, "Le programme a changé depuis cette action. Annulation refusée." + ) + before = entry.payload["node"] + node = await self.db.get(Competency, entry.node_id) + await self.db.execute( + delete(CompetencyLink).where( + or_( + CompetencyLink.parent_id == entry.node_id, + CompetencyLink.child_id == entry.node_id, + ) + ) + ) + if before is None: + if entry.payload.get("created_ids"): + await self.db.execute( + delete(Competency).where( + Competency.curriculum_id == curriculum_id, + Competency.subject_id == entry.subject_id, + Competency.id.in_(entry.payload["created_ids"]), + ) + ) + if node: + await self.db.delete(node) + else: + if node is None: + columns = list(before) + statement = ( + "INSERT INTO sophikron.competencies (" + + ", ".join(columns) + + ") OVERRIDING SYSTEM VALUE VALUES (" + + ", ".join(":" + key for key in columns) + + ")" + ) + await self.db.execute(text(statement), before) + else: + for key, value in before.items(): + setattr(node, key, value) + await self.db.flush() + self.db.add_all( + CompetencyLink( + curriculum_id=curriculum_id, + subject_id=entry.subject_id, + parent_id=p, + child_id=c, + ) + for p, c in entry.payload["edges"] + ) + row.version += 1 + await self.db.delete(entry) + await self.db.flush() + previous = await self.db.scalar( + select(CurriculumUndo) + .where( + CurriculumUndo.actor_id == actor.id, + CurriculumUndo.curriculum_id == curriculum_id, + ) + .order_by(CurriculumUndo.id.desc()) + .limit(1) + ) + available = ( + previous is not None and previous.after_version == entry.payload["before_version"] + ) + if available: + previous.after_version = row.version + await self._event( + actor, + "curriculum", + row.id, + "action_undone", + node if node is not None else Competency(**before) if before else None, + ) + return {**await self._graph(row, entry.subject_id), "can_undo": available} diff --git a/backend/app/services/curriculum_files.py b/backend/app/services/curriculum_files.py new file mode 100644 index 0000000..3369ea7 --- /dev/null +++ b/backend/app/services/curriculum_files.py @@ -0,0 +1,44 @@ +"""Parse portable JSON strictly; uploaded text is data and is never executed.""" + +import json + +from pydantic import ValidationError + +from app.schemas.curricula import CompetencyImport +from app.services.errors import AuthError + +FILE_LIMIT = 4 * 1024 * 1024 +REQUEST_LIMIT = FILE_LIMIT * 2 + 4096 + + +def unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + """Reject duplicate and prototype-related keys before constructing dictionaries.""" + result: dict[str, object] = {} + for key, value in pairs: + if key in result or key in {"__proto__", "constructor", "prototype"}: + raise ValueError("Clé JSON interdite ou dupliquée.") + result[key] = value + return result + + +def parse_import(body: bytes) -> CompetencyImport: + """Return a validated bounded import or a safe error without echoing file contents.""" + if len(body) > REQUEST_LIMIT: + raise AuthError(413, "Fichier trop volumineux (4 Mo maximum).") + try: + value = json.loads(body, object_pairs_hook=unique_object) + if isinstance(value, dict) and isinstance(value.get("document"), str): + if len(value["document"].encode("utf-8")) > FILE_LIMIT: + raise ValueError("Fichier trop volumineux.") + value["document"] = json.loads(value["document"], object_pairs_hook=unique_object) + if ( + isinstance(value, dict) + and len(json.dumps(value.get("document"), ensure_ascii=False, allow_nan=False).encode()) + > FILE_LIMIT + ): + raise ValueError("Fichier trop volumineux.") + return CompetencyImport.model_validate(value) + except (ValueError, ValidationError, RecursionError, UnicodeError): + raise AuthError( + 422, "JSON invalide : vérifiez le format, les champs et les relations." + ) from None diff --git a/backend/app/services/kholloscope_solver.py b/backend/app/services/kholloscope_solver.py index a158511..5bd5d66 100644 --- a/backend/app/services/kholloscope_solver.py +++ b/backend/app/services/kholloscope_solver.py @@ -491,8 +491,12 @@ def watch_cancel() -> None: status = cp_model.UNKNOWN selected = None all_optimal = True - weights = rules.time_distribution() if template and rules.optimize else ( - (sum(rules.time_distribution()[:3]), rules.time_annual_percent) if template else (100,) + weights = ( + rules.time_distribution() + if template and rules.optimize + else ( + (sum(rules.time_distribution()[:3]), rules.time_annual_percent) if template else (100,) + ) ) try: for stage, objective in enumerate(objectives): diff --git a/backend/app/services/releases.py b/backend/app/services/releases.py index 1a7023f..be2c7d9 100644 --- a/backend/app/services/releases.py +++ b/backend/app/services/releases.py @@ -28,11 +28,14 @@ def stable_version(value: str) -> tuple[int, int, int] | None: def fetch_release() -> tuple[str, str] | None: """Fetch one stable public release with a timeout and a bounded response body.""" - request = Request(API_URL, headers={ - "Accept": "application/vnd.github+json", - "User-Agent": "Sophikron-update-check", - "X-GitHub-Api-Version": "2022-11-28", - }) + request = Request( + API_URL, + headers={ + "Accept": "application/vnd.github+json", + "User-Agent": "Sophikron-update-check", + "X-GitHub-Api-Version": "2022-11-28", + }, + ) try: with urlopen(request, timeout=4) as response: body = response.read(262145) @@ -45,8 +48,11 @@ def fetch_release() -> tuple[str, str] | None: data = json.loads(body) tag = data.get("tag_name") if ( - not isinstance(tag, str) or len(tag) > 100 or stable_version(tag) is None - or data.get("draft") is not False or data.get("prerelease") is not False + not isinstance(tag, str) + or len(tag) > 100 + or stable_version(tag) is None + or data.get("draft") is not False + or data.get("prerelease") is not False ): raise ValueError("Unsupported stable release") return tag.removeprefix("v"), f"{REPOSITORY}/releases/tag/{quote(tag, safe='')}" diff --git a/backend/app/services/timetable.py b/backend/app/services/timetable.py index c0f8c81..56a50ef 100644 --- a/backend/app/services/timetable.py +++ b/backend/app/services/timetable.py @@ -679,7 +679,8 @@ async def edit_occurrence( document = await self.repo.document(year) source = next((item for item in document.series if item.id == series_id), None) if ( - data.block is not None and data.block.kind == "kholle" + data.block is not None + and data.block.kind == "kholle" or source is not None and any( block is not None and block.kind == "kholle" diff --git a/backend/pyproject.toml b/backend/pyproject.toml index dcef0c9..fffd832 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "sophikron-api" -version = "0.2.0" +version = "0.3.0" description = "Backend API for the Sophikron educational platform" requires-python = ">=3.12" dependencies = [ @@ -33,6 +33,7 @@ dev = [ "pytest", "pytest-asyncio>=1.4,<2.0", "ruff", + "coverage>=7.10,<8", ] [tool.setuptools.packages.find] @@ -43,7 +44,29 @@ include = ["app*"] testpaths = ["tests"] asyncio_mode = "strict" asyncio_default_fixture_loop_scope = "function" -markers = ["integration: requires the full services and a dedicated PostgreSQL test database"] +junit_family = "xunit1" +markers = [ + "unit: isolated business logic and boundary tests", + "integration: requires the full services and a dedicated PostgreSQL test database", + "e2e: complete journeys against the running disposable API", + "perf: repeatable performance regression checks", +] + +[tool.coverage.run] +branch = true +source = ["app", "run_tests"] +data_file = "reports/.coverage" + +[tool.coverage.report] +show_missing = true +precision = 2 + +[tool.coverage.html] +directory = "reports/html" + +[tool.coverage.json] +output = "reports/coverage.json" +show_contexts = true [tool.ruff] line-length = 100 diff --git a/backend/tests/TESTING.md b/backend/tests/TESTING.md new file mode 100644 index 0000000..cdfa9f8 --- /dev/null +++ b/backend/tests/TESTING.md @@ -0,0 +1,61 @@ +# Backend verification + +Run commands from `backend/` using the project's configured Python interpreter. +Install development dependencies with `python -m pip install -e ".[dev]"`. + +## Suites + +- `unit/`: isolated business rules, validation and mocked boundary adapters. +- `integration/`: real PostgreSQL repositories, migrations and ASGI routes. +- `e2e/`: real TCP journeys against the disposable running API, without frontend changes. +- `perf/`: measured regression budgets with correctness assertions. +- `support/`: reusable fixtures and synthetic data helpers; never imported from test modules. + +Fast feedback: `python -m pytest tests/unit -q`. + +Full isolated verification: `python run_tests.py`. This reuses the project's existing +Compose configuration and removes only its uniquely named disposable resources. +It includes integration, E2E and performance tests; no persistent installation is accepted. + +Select suites through the runner, for example `python run_tests.py -m integration` +or `python run_tests.py -m perf`. E2E bootstrap journeys must run before integration +fixtures remove the startup account; run them on a fresh runner installation. + +## Coverage and CI commands + +The workflow outside `backend/` is deliberately unchanged. Its existing test commands +still discover the nested suites. Proposed additional CI steps are: + +```sh +python -m tests.verify +python -m tests.function_inventory --strict +ruff check . +``` + +Reports live in `backend/reports/`, ignored locally. `functions.json` enumerates every +module function and class method authored in `app/` and `run_tests.py`, including private +methods. Protocol declarations containing only `...` have no implementation to exercise +and are not counted. It lists test execution contexts in the first body statement. Nested helpers +remain visible in line/branch coverage. This is execution evidence, not proof that an +assertion verifies every behavior. Review test assertions and uncovered branches too. +An unobserved method remains a gap; do not hide it with exclusions or fabricate a test +that merely calls it. The strict audit fails until every enumerated callable is observed. +The verification wrapper collects coverage in memory before exporting HTML and compressed +JSON (`reports/coverage.json.gz`), +avoiding SQLite corruption when the workspace is on a network drive. +For independently executed additional tests, the inventory accepts +`--supplement reports/coverage-additional.json` to union their test contexts with the +main report. This does not change the main report's line/branch coverage percentage. + +Performance tests record measurements in JUnit output (`--junitxml=reports/perf.xml`). +The report uses xUnit 1, which supports the per-case custom measurement properties. +Budgets are broad regression ceilings, not production latency commitments. Search covers +2,000 and 10,000 identities, including an encrypted PostgreSQL benchmark with three callers. +Pure ranking, annual occurrence expansion and timezone windows have separate budgets. +Real small-model CP-SAT generation verifies exact quotas within its runtime budget. +Document reception measures digest correctness, elapsed time and Python allocation peaks +for 1 MiB and 16 MiB uploads; this is not a measurement of total process RSS. +Run heavier measurements separately on a stable worker before tightening thresholds. + +When a behavior test exposes an application defect, retain the failure and report it. +Do not change application code, mark the test xfail, or weaken its expectations to pass. diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index a40388e..5ebe446 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -6,19 +6,45 @@ import os import secrets import sys -from collections.abc import Callable +from collections.abc import Callable, Generator from pathlib import Path from unittest.mock import AsyncMock import pytest +from coverage import Coverage from sqlalchemy import delete, select from app.core.config import DatabaseSettings from app.core.database import Database from app.models import AccountInvitation, User -from tests.postgres import run_alembic -from tests.test_auth_postgres import auth_case # noqa: F401 -from tests.test_lessons_postgres import course # noqa: F401 +from tests.support.authentication import auth_case # noqa: F401 +from tests.support.cleanup import clear_test_events +from tests.support.lessons import course # noqa: F401 +from tests.support.postgres import run_alembic + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_protocol(item: pytest.Item) -> Generator[None, object, object]: + """Associate setup, asynchronous tasks and teardown with the exact pytest case.""" + coverage = Coverage.current() + if coverage is not None: + coverage.switch_context(item.nodeid) + try: + return (yield) + finally: + if coverage is not None: + coverage.switch_context("") + + +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + """Keep marker selection consistent with the suite directories, including future tests.""" + for item in items: + relative = Path(item.path).relative_to(Path(__file__).parent) + category = relative.parts[0] + if category in {"unit", "integration", "e2e", "perf"}: + item.add_marker(getattr(pytest.mark, category)) + if category == "e2e": + item.add_marker(pytest.mark.integration) @pytest.fixture(scope="session") @@ -33,6 +59,10 @@ async def remove_startup_fixture() -> None: database = Database(DatabaseSettings()) try: async with database.sessions.begin() as session: + bootstrap_ids = list( + await session.scalars(select(User.id).where(User.is_bootstrap)) + ) + await clear_test_events(bootstrap_ids) ids = select(User.id).where(User.is_bootstrap) await session.execute( delete(AccountInvitation).where( diff --git a/backend/tests/e2e/__init__.py b/backend/tests/e2e/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/e2e/auth/__init__.py b/backend/tests/e2e/auth/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/e2e/auth/test_authentication.py b/backend/tests/e2e/auth/test_authentication.py new file mode 100644 index 0000000..7ffb052 --- /dev/null +++ b/backend/tests/e2e/auth/test_authentication.py @@ -0,0 +1,47 @@ +"""Real TCP authentication journey against the runner's disposable installation.""" + +import os +from pathlib import Path + +import httpx2 as httpx +import pytest + +pytestmark = [pytest.mark.e2e, pytest.mark.integration] + + +@pytest.fixture(scope="session") +def live_installation() -> tuple[str, str, Path]: + """Capture runner settings before function-scoped synthetic AUTH settings replace them.""" + if os.environ.get("DB_INTEGRATION") != "1" or os.environ.get("DB_NAME") != "sophikron_test": + pytest.skip("Run through backend/run_tests.py with its disposable API") + url = os.environ.get("DB_TEST_API_URL") + directory = os.environ.get("SOPHIKRON_SECRETS_DIRECTORY") + username = os.environ.get("AUTH_BOOTSTRAP_USERNAME") + if not url or not directory or not username: + pytest.skip("Disposable live API bootstrap configuration required") + return url, username, Path(directory) / "bootstrap_password" + + +def test_login_profile_logout_and_revoked_session( + live_installation: tuple[str, str, Path], +) -> None: + """Authenticate over TCP, read own identity, log out and reject reuse of the session.""" + url, username, secret = live_installation + headers = {"Origin": "http://localhost:3000", "X-CSRF-Protection": "1"} + with httpx.Client(base_url=url, headers=headers, timeout=15) as client: + assert client.get("/health").status_code == 200 + assert client.get("/api/v1/auth/me").status_code == 401 + response = client.post( + "/api/v1/auth/login", + json={"identifier": username, "password": secret.read_text().strip()}, + ) + assert response.status_code == 200 + assert response.json()["is_bootstrap"] is True + saved_cookies = dict(client.cookies) + try: + assert client.get("/api/v1/auth/me").status_code == 200 + assert client.get("/api/v1/admin/users").status_code == 403 + finally: + assert client.post("/api/v1/auth/logout").status_code == 204 + client.cookies.update(saved_cookies) + assert client.get("/api/v1/auth/me").status_code == 401 diff --git a/backend/tests/function_inventory.py b/backend/tests/function_inventory.py new file mode 100644 index 0000000..99701f5 --- /dev/null +++ b/backend/tests/function_inventory.py @@ -0,0 +1,104 @@ +"""Report authored callables without observed test execution using coverage contexts.""" + +import argparse +import ast +import gzip +import json +from pathlib import Path + +BACKEND = Path(__file__).resolve().parents[1] + + +def callables(tree: ast.AST, prefix: str = "") -> list[tuple[str, int, int]]: + """Enumerate module functions and class methods using their first body statement. + + Parameters + ---------- + tree + Parsed module or class. + prefix + Enclosing class qualification. + + Returns + ------- + list + Qualified names and executable body lines; generated methods are excluded. + """ + result = [] + for node in getattr(tree, "body", []): + if isinstance(node, ast.ClassDef): + result.extend(callables(node, prefix + node.name + ".")) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + body = node.body + if isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant): + body = body[1:] + if body and not ( + len(body) == 1 + and isinstance(body[0], ast.Expr) + and isinstance(body[0].value, ast.Constant) + and body[0].value.value is Ellipsis + ): + result.append((prefix + node.name, body[0].lineno, body[0].end_lineno)) + return result + + +def main(arguments: list[str] | None = None) -> int: + """Write the callable inventory and optionally fail when any callable lacks test context. + + Parameters + ---------- + arguments + Optional CLI arguments; otherwise use the process arguments. + + Returns + ------- + int + Nonzero for a strict audit with unobserved callables. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--strict", action="store_true") + parser.add_argument("--supplement", action="append", default=[]) + options = parser.parse_args(arguments) + with gzip.open(BACKEND / "reports" / "coverage.json.gz", "rt", encoding="utf-8") as source: + report = json.load(source) + files = {name.replace("\\", "/"): facts for name, facts in report["files"].items()} + for supplement in options.supplement: + extra = json.loads(Path(supplement).read_text(encoding="utf-8")) + for name, facts in extra["files"].items(): + contexts = files.setdefault(name.replace("\\", "/"), {}).setdefault("contexts", {}) + for line, values in facts.get("contexts", {}).items(): + contexts[line] = sorted(set(contexts.get(line, [])) | set(values)) + rows = [] + for path in sorted([*(BACKEND / "app").rglob("*.py"), BACKEND / "run_tests.py"]): + facts = files.get(path.relative_to(BACKEND).as_posix(), {}) + contexts = {int(line): values for line, values in facts.get("contexts", {}).items()} + for name, line, end_line in callables(ast.parse(path.read_text(encoding="utf-8"))): + tests = sorted( + { + c + for number in range(line, end_line + 1) + for c in contexts.get(number, []) + if "test_" in c + } + ) + rows.append( + { + "file": str(path.relative_to(BACKEND)), + "name": name, + "line": line, + "test_contexts": tests, + } + ) + missing = [row for row in rows if not row["test_contexts"]] + output = BACKEND / "reports" / "functions.json" + output.parent.mkdir(exist_ok=True) + output.write_text( + json.dumps({"total": len(rows), "unobserved": len(missing), "functions": rows}, indent=2), + encoding="utf-8", + ) + print(f"{len(rows)} authored callables; {len(missing)} without observed test context: {output}") + return int(options.strict and bool(missing)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/tests/integration/__init__.py b/backend/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/integration/administration/__init__.py b/backend/tests/integration/administration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_activity_journal.py b/backend/tests/integration/administration/test_activity_journal.py similarity index 97% rename from backend/tests/test_activity_journal.py rename to backend/tests/integration/administration/test_activity_journal.py index 259414e..b446f3e 100644 --- a/backend/tests/test_activity_journal.py +++ b/backend/tests/integration/administration/test_activity_journal.py @@ -9,8 +9,8 @@ from app.models import ActivityEvent from app.services.activity import EVENTS, DownloadFacts, EventDefinition, event_family, highest_role -from tests.test_auth_postgres import PASSWORD, Harness -from tests.test_dashboard_postgres import clear_promotions, make_promotion +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import PASSWORD, Harness integration = pytest.mark.skipif( os.environ.get("DB_INTEGRATION") != "1", reason="PostgreSQL required" @@ -215,7 +215,7 @@ async def test_historical_roles_survive_later_changes(auth_case: Harness) -> Non ).status_code == 200 assert ( await case.client.patch( - path, json={"expected_version": 1, "roles": ["admin"], "first_name": "Marie"} + path, json={"expected_version": 1, "roles": ["admin"], "first_name": "Modele"} ) ).status_code == 200 result = await case.client.get( @@ -225,7 +225,7 @@ async def test_historical_roles_survive_later_changes(auth_case: Harness) -> Non entry = result.json()["items"][0] assert entry["actor_user_id"] == staff_id and entry["actor_role"] == "admin" assert entry["subject_user_id"] == user_id and entry["subject_role"] == "user" - assert entry["subject_label"] == "Marie Burgaud" + assert entry["subject_label"] == "Modele Fictif" assert entry["data"] == {"previous_roles": ["user"], "roles": ["teacher"]} assert entry["actor_profile_available"] and entry["subject_profile_available"] @@ -253,7 +253,9 @@ async def test_promotion_snapshot_and_explicit_changes(auth_case: Harness) -> No created = next(item for item in result if item["event_type"] == "promotion.created") updated = next(item for item in result if item["event_type"] == "promotion.updated") assert created["promotion_snapshot"] == { - field: before[field] for field in ("identifier", "year", "color") + **{field: before[field] for field in ("identifier", "year", "color")}, + "curriculum_id": None, + "track_id": None, } assert updated["promotion_snapshot"]["identifier"] == "RENAMED" assert updated["data"]["previous"]["identifier"] == before["identifier"] diff --git a/backend/tests/integration/administration/test_curricula_postgres.py b/backend/tests/integration/administration/test_curricula_postgres.py new file mode 100644 index 0000000..f762b33 --- /dev/null +++ b/backend/tests/integration/administration/test_curricula_postgres.py @@ -0,0 +1,489 @@ +"""Real PostgreSQL programme rights, shared nodes, constraints and atomic edits.""" + +import json +import os +from pathlib import Path + +import pytest +from sqlalchemy import delete, text +from sqlalchemy.exc import IntegrityError + +from app.core.config import DatabaseSettings +from app.core.database import Database +from app.models.curricula import CompetencyLink, Curriculum +from tests.support.authentication import Harness +from tests.support.lessons import CourseHarness +from tests.support.postgres import run_alembic + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("DB_INTEGRATION") != "1", reason="Dedicated PostgreSQL required" + ), +] + + +@pytest.mark.asyncio +async def test_curriculum_json_roundtrip_rights_and_undo(course: CourseHarness) -> None: + """Append complete shared graphs atomically, preserve existing nodes and undo one batch.""" + case = course.case + identifier = await create_programme(case, course.state["subject_id"]) + path = f"/api/v1/curricula/{identifier}/subjects/{course.state['subject_id']}" + try: + await course.login(course.owner) + ids = [] + for version, name in enumerate(("A", "B", "Shared")): + response = await case.client.post( + path + "/nodes", + json={ + "name": name, + "expected_version": version, + "parent_ids": ids if version == 2 else [], + "knowledge": "", + "comment": "Note", + "color": "#123456", + "semester": 2, + }, + ) + assert response.status_code == 201, response.text + ids.append( + next(node["id"] for node in response.json()["nodes"] if node["name"] == name) + ) + exported = await case.client.get(path + "/export") + assert exported.status_code == 200, exported.text + document = exported.json() + assert len(document["nodes"]) == 3 + assert ( + next(node for node in document["nodes"] if node["name"] == "Shared")["parent_ids"] + == ids[:2] + ) + assert document["nodes"][0]["knowledge"] == "" + imported = await case.client.post( + path + "/import", json={"expected_version": 3, "document": json.dumps(document)} + ) + assert imported.status_code == 200, imported.text + assert len(imported.json()["nodes"]) == 6 and len(imported.json()["edges"]) == 4 + assert {node["id"] for node in imported.json()["nodes"]} >= set(ids) + assert len({node["id"] for node in imported.json()["nodes"]}) == 6 + undone = await case.client.post( + f"/api/v1/curricula/{identifier}/undo", json={"expected_version": 4} + ) + assert undone.status_code == 200 and len(undone.json()["nodes"]) == 3 + assert ( + await case.client.post( + path + "/import", json={"expected_version": 0, "document": document} + ) + ).status_code == 409 + document["nodes"][0]["parent_ids"] = [document["nodes"][0]["id"]] + assert ( + await case.client.post( + path + "/import", json={"expected_version": 5, "document": document} + ) + ).status_code == 422 + assert (await case.client.get(path)).json()["version"] == 5 + _, reader = await case.create("kholleur") + await course.login(reader) + assert (await case.client.get(path + "/export")).status_code == 200 + valid = (await case.client.get(path + "/export")).json() + assert ( + await case.client.post( + path + "/import", json={"expected_version": 5, "document": valid} + ) + ).status_code == 403 + finally: + async with case.database.sessions.begin() as session: + await session.execute(delete(Curriculum).where(Curriculum.id == identifier)) + + +def test_curriculum_migration_matches_metadata(migrated_database: None) -> None: + """Compare the migrated disposable database to every registered SQLAlchemy model.""" + run_alembic("check") + + +@pytest.mark.asyncio +async def test_curriculum_baseline_upgrade_and_downgrade(migrated_database: None) -> None: + """Round-trip the consolidated migration while preserving older promotions and calendars.""" + run_alembic("downgrade", "0008_kholloscope") + database = Database( + DatabaseSettings( + user="sophikron_migrator", + password_file=Path(os.environ["DB_TEST_MIGRATION_PASSWORD_FILE"]), + ) + ) + async with database.sessions.begin() as session: + subject = await session.scalar( + text( + "INSERT INTO sophikron.subjects (name, name_key, icon, color) VALUES ('Baseline " + "SII', 'baseline-sii', 'book', '#4361EE') RETURNING id" + ) + ) + promotion = await session.scalar( + text( + "INSERT INTO sophikron.promotions (year, identifier, color) VALUES (2026, " + "'Baseline preservation', '#4361EE') RETURNING id" + ) + ) + calendar = await session.scalar( + text( + "INSERT INTO sophikron.timetable_calendars (name, name_key, promotion_id, " + "revision) VALUES ('Baseline calendar', 'baseline-calendar', :promotion, " + "'unchanged') RETURNING id" + ).bindparams(promotion=promotion) + ) + try: + for _ in range(2): + run_alembic("upgrade", "head") + run_alembic("check") + async with database.sessions.begin() as session: + assert ( + await session.scalar(text("SELECT version_num FROM sophikron.alembic_version")) + == "0009_curricula" + ) + assert await session.scalar(text("SELECT to_regclass('sophikron.tracks')")) is None + assert ( + await session.scalar( + text( + "SELECT count(*) FROM information_schema.columns WHERE " + "table_schema='sophikron' AND table_name='competencies' AND " + "column_name='code'" + ) + ) + == 0 + ) + grants = ( + await session.execute( + text( + "SELECT p.code, r.code FROM sophikron.permissions p JOIN " + "sophikron.role_permissions rp ON rp.permission_id=p.id JOIN " + "sophikron.roles r ON r.id=rp.role_id WHERE p.code LIKE 'curricula.%'" + ) + ) + ).all() + assert set(grants) == { + ("curricula.read", "admin"), + ("curricula.read", "teacher"), + ("curricula.read", "kholleur"), + ("curricula.edit", "teacher"), + ("curricula.manage", "admin"), + } + programme = await session.scalar( + text( + "INSERT INTO sophikron.curricula (title, description) VALUES ('Baseline " + "programme', 'Current official programme') RETURNING id" + ) + ) + await session.execute( + text( + "INSERT INTO sophikron.curriculum_subjects VALUES (:programme, :subject)" + ).bindparams(programme=programme, subject=subject) + ) + await session.execute( + text( + "INSERT INTO sophikron.competencies (curriculum_id, subject_id, name) " + "VALUES (:programme, :subject, 'Analyser')" + ).bindparams(programme=programme, subject=subject) + ) + await session.execute( + text( + "UPDATE sophikron.promotions SET curriculum_id=:programme WHERE id=:id" + ).bindparams(programme=programme, id=promotion) + ) + run_alembic("downgrade", "0008_kholloscope") + async with database.sessions.begin() as session: + assert ( + await session.scalar( + text("SELECT identifier FROM sophikron.promotions WHERE id=:id").bindparams( + id=promotion + ) + ) + == "Baseline preservation" + ) + assert ( + await session.scalar( + text("SELECT name FROM sophikron.subjects WHERE id=:id").bindparams( + id=subject + ) + ) + == "Baseline SII" + ) + assert ( + await session.execute( + text( + "SELECT promotion_id, revision FROM sophikron.timetable_calendars " + "WHERE id=:id" + ).bindparams(id=calendar) + ) + ).one() == (promotion, "unchanged") + assert ( + await session.scalar( + text( + "SELECT count(*) FROM sophikron.permissions WHERE code LIKE " + "'curricula.%'" + ) + ) + == 0 + ) + assert ( + await session.scalar(text("SELECT to_regclass('sophikron.curriculum_undo')")) + is None + ) + assert ( + await session.scalar(text("SELECT to_regclass('sophikron.curricula')")) is None + ) + run_alembic("upgrade", "head") + run_alembic("check") + finally: + run_alembic("upgrade", "head") + async with database.sessions.begin() as session: + await session.execute( + text("DELETE FROM sophikron.timetable_calendars WHERE id=:id").bindparams( + id=calendar + ) + ) + await session.execute( + text("DELETE FROM sophikron.promotions WHERE id=:id").bindparams(id=promotion) + ) + await session.execute( + text("DELETE FROM sophikron.subjects WHERE id=:id").bindparams(id=subject) + ) + await database.close() + + +async def create_programme(case: Harness, subject_id: int) -> int: + """Create programme metadata using an administrator with no teacher role.""" + case.as_admin() + response = await case.client.post( + "/api/v1/curricula", + json={ + "title": "Programme des deux années", + "description": "Description du programme officiel", + "subject_ids": [subject_id], + "source_url": "https://education.gouv.fr/programme.pdf", + }, + ) + assert response.status_code == 201, response.text + assert response.json()["description"] == "Description du programme officiel" + assert "track_id" not in response.json() + return response.json()["id"] + + +@pytest.mark.asyncio +async def test_curriculum_undo_preserves_identity_and_rejects_other_writers( + course: CourseHarness, +) -> None: + """Restore deleted identities, unwind several edits, and deny stale inverse operations.""" + case = course.case + identifier = await create_programme(case, course.state["subject_id"]) + base = f"/api/v1/curricula/{identifier}" + path = base + f"/subjects/{course.state['subject_id']}" + try: + await course.login(course.owner) + created = await case.client.post( + path + "/nodes", json={"name": "Original", "expected_version": 0} + ) + assert created.status_code == 201, created.text + node_id = created.json()["nodes"][0]["id"] + edited = await case.client.put( + path + f"/nodes/{node_id}", json={"name": "Edited", "expected_version": 1} + ) + assert edited.status_code == 200, edited.text + removed = await case.client.request( + "DELETE", path + f"/nodes/{node_id}", json={"expected_version": 2} + ) + assert removed.status_code == 200, removed.text + for version, expected in ((3, "Edited"), (4, "Original"), (5, None)): + response = await case.client.post(base + "/undo", json={"expected_version": version}) + assert response.status_code == 200, response.text + if expected: + assert response.json()["nodes"][0]["id"] == node_id + assert response.json()["nodes"][0]["name"] == expected + else: + assert response.json()["nodes"] == [] + parent = await case.client.post( + path + "/nodes", json={"name": "Parent", "expected_version": 6} + ) + parent_id = parent.json()["nodes"][0]["id"] + child = await case.client.post( + path + "/nodes", + json={"name": "Child", "parent_ids": [parent_id], "expected_version": 7}, + ) + expected_edges = child.json()["edges"] + removed = await case.client.request( + "DELETE", path + f"/nodes/{parent_id}", json={"expected_version": 8} + ) + assert removed.status_code == 200 and removed.json()["edges"] == [] + restored = await case.client.post(base + "/undo", json={"expected_version": 9}) + assert restored.status_code == 200, restored.text + assert restored.json()["edges"] == expected_edges + await case.client.post(path + "/nodes", json={"name": "Owner edit", "expected_version": 10}) + await course.login(course.collaborator) + await case.client.post( + path + "/nodes", json={"name": "Other writer", "expected_version": 11} + ) + await course.login(course.owner) + assert ( + await case.client.post(base + "/undo", json={"expected_version": 12}) + ).status_code == 409 + finally: + async with case.database.sessions.begin() as session: + await session.execute(delete(Curriculum).where(Curriculum.id == identifier)) + + +@pytest.mark.asyncio +async def test_curriculum_collaboration_and_integrity(course: CourseHarness) -> None: + """Enforce subject rights, sharing, cycles, stale edits and child-preserving deletion.""" + case = course.case + curriculum_id = await create_programme(case, course.state["subject_id"]) + path = f"/api/v1/curricula/{curriculum_id}/subjects/{course.state['subject_id']}" + try: + await course.login(course.student) + assert (await case.client.get("/api/v1/curricula/catalog")).status_code == 403 + await course.login(course.owner) + assert ( + await case.client.post( + "/api/v1/curricula", + json={ + "title": "Denied", + "subject_ids": [course.state["subject_id"]], + }, + ) + ).status_code == 403 + version = 0 + ids = [] + for name in ("Analyser", "Modéliser", "Compétence partagée"): + response = await case.client.post( + path + "/nodes", + json={ + "name": name, + "expected_version": version, + "parent_ids": ids if len(ids) == 2 else [], + }, + ) + assert response.status_code == 201, response.text + state = response.json() + ids.append(next(node["id"] for node in state["nodes"] if node["name"] == name)) + version = state["version"] + assert len(state["edges"]) == 2 + assert {n["id"]: n["code"] for n in state["nodes"]} == { + ids[0]: "A", + ids[1]: "B", + ids[2]: "A.1", + } + assert ( + await case.client.put( + path + f"/nodes/{ids[2]}", + json={ + "name": "Code manuel", + "code": "Z", + "expected_version": version, + }, + ) + ).status_code == 422 + rejected = await case.client.put( + path + f"/nodes/{ids[0]}", + json={ + "name": "Cycle", + "expected_version": version, + "parent_ids": [ids[2]], + }, + ) + assert rejected.status_code == 422 + assert (await case.client.get(path)).json()["version"] == version + await course.login(course.collaborator) + assert ( + await case.client.put( + path + f"/nodes/{ids[2]}", + json={ + "name": "Stale", + "expected_version": 0, + }, + ) + ).status_code == 409 + response = await case.client.put( + path + f"/nodes/{ids[2]}", + json={ + "name": "Actualisée partout", + "expected_version": version, + "parent_ids": ids[:2], + }, + ) + assert response.status_code == 200, response.text + version = response.json()["version"] + # Composite foreign keys reject a spoofed subject independently of service checks. + with pytest.raises(IntegrityError): + async with case.database.sessions.begin() as session: + session.add( + CompetencyLink( + curriculum_id=curriculum_id, + subject_id=999999, + parent_id=ids[0], + child_id=ids[1], + ) + ) + response = await case.client.request( + "DELETE", path + f"/nodes/{ids[0]}", json={"expected_version": version} + ) + assert response.status_code == 200, response.text + state = response.json() + assert {n["id"] for n in state["nodes"]} == set(ids[1:]) + assert state["edges"] == [{"parent_id": ids[1], "child_id": ids[2]}] + assert {n["id"]: n["code"] for n in state["nodes"]} == {ids[1]: "A", ids[2]: "A.1"} + response = await case.client.put( + path + f"/nodes/{ids[2]}", + json={ + "name": "Racine détachée", + "expected_version": state["version"], + "parent_ids": [], + }, + ) + assert response.status_code == 200 and response.json()["edges"] == [] + assert {n["id"]: n["code"] for n in response.json()["nodes"]} == {ids[1]: "A", ids[2]: "B"} + finally: + async with case.database.sessions.begin() as session: + await session.execute(delete(Curriculum).where(Curriculum.id == curriculum_id)) + + +@pytest.mark.asyncio +async def test_curriculum_reader_and_unassigned_teacher(course: CourseHarness) -> None: + """Kholleurs can read; unassigned teachers cannot mutate; promotion links stay optional.""" + case = course.case + curriculum_id = await create_programme(case, course.state["subject_id"]) + path = f"/api/v1/curricula/{curriculum_id}/subjects/{course.state['subject_id']}" + try: + _, kholleur = await case.create("kholleur") + _, stranger = await case.create("teacher") + for username in (kholleur, stranger): + await course.login(username) + assert (await case.client.get(path)).status_code == 200 + assert ( + await case.client.post( + path + "/nodes", + json={ + "name": "Denied", + "expected_version": 0, + }, + ) + ).status_code == 403 + case.as_admin() + response = await case.client.post( + "/api/v1/admin/promotions", + json={ + "year": 2026, + "identifier": case.prefix, + "color": "#123456", + }, + ) + assert response.status_code == 201 and response.json()["curriculum_id"] is None + promotion_id = response.json()["id"] + course.promotion_ids.append(promotion_id) + response = await case.client.patch( + f"/api/v1/admin/promotions/{promotion_id}", json={"curriculum_id": curriculum_id} + ) + assert response.status_code == 200 and response.json()["curriculum_id"] == curriculum_id + response = await case.client.patch( + f"/api/v1/admin/promotions/{promotion_id}", json={"curriculum_id": None} + ) + assert response.status_code == 200 and response.json()["curriculum_id"] is None + finally: + async with case.database.sessions.begin() as session: + await session.execute(delete(Curriculum).where(Curriculum.id == curriculum_id)) diff --git a/backend/tests/test_dashboard_postgres.py b/backend/tests/integration/administration/test_dashboard_postgres.py similarity index 83% rename from backend/tests/test_dashboard_postgres.py rename to backend/tests/integration/administration/test_dashboard_postgres.py index 217b2db..59780df 100644 --- a/backend/tests/test_dashboard_postgres.py +++ b/backend/tests/integration/administration/test_dashboard_postgres.py @@ -2,17 +2,12 @@ import asyncio import os -from math import ceil -from pathlib import Path -from time import perf_counter from unittest.mock import patch import pytest -from sqlalchemy import delete, func, insert, select, text +from sqlalchemy import func, select, text from sqlalchemy.exc import DBAPIError, IntegrityError -from app.core.config import DatabaseSettings -from app.core.database import Database from app.models import ( ActivityEvent, Promotion, @@ -22,7 +17,8 @@ UserPromotion, UserRole, ) -from tests.test_auth_postgres import PASSWORD, Harness +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import PASSWORD, Harness pytestmark = [ pytest.mark.integration, @@ -32,40 +28,6 @@ ] -async def make_promotion(case: Harness, identifier: str = "PTSI") -> int: - """Create a synthetic promotion and return its generated integer identity.""" - case.as_admin() - response = await case.client.post( - "/api/v1/admin/promotions", - json={ - "year": 2019, - "identifier": identifier, - "color": "#123abc", - }, - ) - assert response.status_code == 201, response.text - return response.json()["id"] - - -async def clear_promotions(ids: list[int]) -> None: - """Remove synthetic catalogue rows through the migration role after memberships are gone.""" - database = Database( - DatabaseSettings( - user="sophikron_migrator", - password_file=Path(os.environ["DB_TEST_MIGRATION_PASSWORD_FILE"]), - ) - ) - try: - async with database.sessions.begin() as session: - await session.execute( - delete(PromotionAccountBlock).where(PromotionAccountBlock.promotion_id.in_(ids)) - ) - await session.execute(delete(UserPromotion).where(UserPromotion.promotion_id.in_(ids))) - await session.execute(delete(Promotion).where(Promotion.id.in_(ids))) - finally: - await database.close() - - @pytest.mark.asyncio async def test_promotion_memberships_and_archive(auth_case: Harness) -> None: """Archive/reactivate without deleting users or memberships; journal only actual changes.""" @@ -144,8 +106,8 @@ async def test_promotion_role_eligibility_and_teaching_filter(auth_case: Harness response = await case.client.post( "/api/v1/admin/users", json={ - "first_name": "Camille", - "last_name": "Martin", + "first_name": "Compte", + "last_name": "Specimen", "email": f"{case.prefix}-eligible-{index}@example.org", "roles": roles, "promotion_ids": [promotion_id], @@ -183,7 +145,7 @@ async def test_promotion_role_eligibility_and_teaching_filter(auth_case: Harness searched = await case.client.get( "/api/v1/admin/users/search", params={ - "q": "Camille", + "q": "Compte", "role": "teaching", "promotion_id": promotion_id, }, @@ -211,8 +173,8 @@ async def test_promotion_role_eligibility_and_teaching_filter(auth_case: Harness rejected = await case.client.post( "/api/v1/admin/users", json={ - "first_name": "Camille", - "last_name": "Martin", + "first_name": "Compte", + "last_name": "Specimen", "email": f"{case.prefix}-rejected@example.org", "roles": ["admin"], "promotion_ids": [promotion_id], @@ -223,8 +185,8 @@ async def test_promotion_role_eligibility_and_teaching_filter(auth_case: Harness accepted = await case.client.post( "/api/v1/admin/users", json={ - "first_name": "Camille", - "last_name": "Martin", + "first_name": "Compte", + "last_name": "Specimen", "email": f"{case.prefix}-rejected@example.org", "roles": ["admin"], }, @@ -269,7 +231,7 @@ async def test_promotion_candidates_exclude_members(auth_case: Harness, roles: l response = await case.client.post( "/api/v1/admin/users", json={ - "first_name": "Camille", + "first_name": "Compte", "last_name": "Exclusion", "email": f"{case.prefix}-exclude-{index}@example.org", "roles": roles, @@ -555,8 +517,8 @@ async def test_atomic_creation_and_immutable_username(auth_case: Harness) -> Non promotion_id = await make_promotion(case) try: body = dict( - first_name="Valentin", - last_name="Rémi", + first_name="Exemple", + last_name="Démo", email="atomic@example.org", roles=["teacher", "admin"], promotion_ids=[promotion_id], @@ -566,7 +528,7 @@ async def test_atomic_creation_and_immutable_username(auth_case: Harness) -> Non user = response.json() case.ids.append(user["id"]) assert isinstance(user["id"], int) and user["id"] > 0 - assert user["username"].startswith("vremi") and 100 <= int(user["username"][-3:]) <= 999 + assert user["username"].startswith("edemo") and 100 <= int(user["username"][-3:]) <= 999 assert {"teacher.access", "users.manage"} <= set(user["permissions"]) before = (await case.client.get("/api/v1/admin/users")).json()["total"] for changes, expected in ( @@ -653,11 +615,11 @@ async def test_search_filters_and_permissions(auth_case: Harness) -> None: assert (await case.client.get("/api/v1/test/teacher")).status_code == 403 user_id, username = await case.create("teacher") assert ( - await case.client.get("/api/v1/admin/users/search?q=valentin%20burgo&role=teacher") + await case.client.get("/api/v1/admin/users/search?q=exemple%20ficto&role=teacher") ).json()[0]["id"] == user_id assert (await case.client.get("/api/v1/admin/users/search?q=v")).status_code == 422 assert (await case.client.get("/api/v1/admin/users/search?q=zzzzzzzz")).json() == [] - assert (await case.client.get("/api/v1/admin/users/search?q=val&limit=21")).status_code == 422 + assert (await case.client.get("/api/v1/admin/users/search?q=exe&limit=21")).status_code == 422 assert (await case.client.get("/api/v1/admin/users?role=teacher")).json()["total"] == 1 assert (await case.client.get("/api/v1/admin/users/9223372036854775807")).status_code == 404 assert ( @@ -666,10 +628,10 @@ async def test_search_filters_and_permissions(auth_case: Harness) -> None: await case.client.post( "/api/v1/auth/login", json={"identifier": username, "password": PASSWORD} ) - for path in ("users", "users/search?q=val", "promotions", "events"): + for path in ("users", "users/search?q=exe", "promotions", "events"): assert (await case.client.get("/api/v1/admin/" + path)).status_code == 403 case.client.cookies.clear() - assert (await case.client.get("/api/v1/admin/users/search?q=val")).status_code == 401 + assert (await case.client.get("/api/v1/admin/users/search?q=exe")).status_code == 401 @pytest.mark.asyncio @@ -758,86 +720,6 @@ async def test_parallel_membership_is_idempotent(auth_case: Harness) -> None: await clear_promotions([promotion_id]) -@pytest.mark.asyncio -async def test_interactive_search_representative_volumes(auth_case: Harness) -> None: - """Measure complete ASGI searches over encrypted PostgreSQL identities with three callers.""" - case = auth_case - promotion_id = await make_promotion(case, "SEARCH-BENCHMARK") - cipher = case.app.state.identity_cipher - try: - for count in (2000, 8000): - async with case.database.sessions.begin() as session: - ids = list( - ( - await session.scalars( - text( - "SELECT nextval(pg_get_serial_sequence('sophikron.users', 'id')) " - "FROM generate_series(1, :count)" - ), - {"count": count}, - ) - ).all() - ) - records = [] - for index, user_id in enumerate(ids): - username = f"benchmark{user_id}" - email = f"{username}@example.org" - first, last = ( - ("Valentin", "Burgaud") if index % 10 == 0 else ("Alice", "Martin") - ) - records.append( - dict( - id=user_id, - first_name_encrypted=cipher.encrypt(user_id, "first_name", first), - last_name_encrypted=cipher.encrypt(user_id, "last_name", last), - username_encrypted=cipher.encrypt(user_id, "username", username), - email_encrypted=cipher.encrypt(user_id, "email", email), - username_lookup=cipher.lookup("username", username), - email_lookup=cipher.lookup("email", email), - ) - ) - await session.execute(insert(User), records) - role_id = await session.scalar(select(Role.id).where(Role.code == "user")) - await session.execute( - insert(UserRole), [dict(user_id=item, role_id=role_id) for item in ids] - ) - await session.execute( - insert(UserPromotion), - [dict(user_id=item, promotion_id=promotion_id) for item in ids], - ) - case.ids.extend(ids) - - async def timed_search() -> float: - """Measure full authenticated query, database loading, decryption and ranking.""" - start = perf_counter() - response = await case.client.get( - "/api/v1/admin/users/search", - params={ - "q": "valentin burgo", - "promotion_id": promotion_id, - }, - ) - elapsed = perf_counter() - start - assert response.status_code == 200 and len(response.json()) == 20 - assert all(item["last_name"] == "Burgaud" for item in response.json()) - return elapsed - - await timed_search() - samples = [] - for _ in range(4): - samples.extend(await asyncio.gather(*(timed_search() for _ in range(3)))) - p95 = sorted(samples)[ceil(len(samples) * 0.95) - 1] - volume = 2000 if count == 2000 else 10000 - print( - f"Search benchmark: {volume} accounts, 3 concurrent callers, " - f"p95={p95 * 1000:.1f} ms" - ) - # A broad regression ceiling avoids turning a hardware-specific target into flaky CI. - assert p95 < 2, "Interactive search exceeded the two-second regression ceiling" - finally: - await clear_promotions([promotion_id]) - - @pytest.mark.asyncio async def test_parallel_username_generation(auth_case: Harness) -> None: """Create distinct usernames for identical names through concurrent requests.""" @@ -847,8 +729,8 @@ async def test_parallel_username_generation(auth_case: Harness) -> None: case.client.post( "/api/v1/admin/users", json={ - "first_name": "Dionis", - "last_name": "DU SEJOUR", + "first_name": "Compte", + "last_name": "DU TEST", "email": f"collision{index}@example.org", "roles": ["user"], }, @@ -860,7 +742,7 @@ async def test_parallel_username_generation(auth_case: Harness) -> None: assert response.status_code == 201, response.text case.ids.append(response.json()["id"]) names = [response.json()["username"] for response in responses] - assert len(set(names)) == 3 and all(name.startswith("dduse") for name in names) + assert len(set(names)) == 3 and all(name.startswith("cdute") for name in names) @pytest.mark.asyncio @@ -872,20 +754,20 @@ async def test_cached_search_observes_current_identity_and_filters(auth_case: Ha user_id, _ = await case.create(activate=False) membership = f"/api/v1/admin/users/{user_id}/promotions/{promotion_id}" await case.client.put(membership) - params = {"q": "burgaud", "promotion_id": promotion_id} + params = {"q": "fictif", "promotion_id": promotion_id} assert (await case.client.get("/api/v1/admin/users/search", params=params)).json()[0][ "id" ] == user_id async with case.database.sessions.begin() as session: user = await session.get(User, user_id) user.last_name_encrypted = case.app.state.identity_cipher.encrypt( - user_id, "last_name", "Martin" + user_id, "last_name", "Specimen" ) assert (await case.client.get("/api/v1/admin/users/search", params=params)).json() == [] - params["q"] = "martin" + params["q"] = "specimen" assert (await case.client.get("/api/v1/admin/users/search", params=params)).json()[0][ "last_name" - ] == "Martin" + ] == "Specimen" await case.client.delete(membership) assert (await case.client.get("/api/v1/admin/users/search", params=params)).json() == [] finally: diff --git a/backend/tests/test_groups_postgres.py b/backend/tests/integration/administration/test_groups_postgres.py similarity index 98% rename from backend/tests/test_groups_postgres.py rename to backend/tests/integration/administration/test_groups_postgres.py index 9721422..927281f 100644 --- a/backend/tests/test_groups_postgres.py +++ b/backend/tests/integration/administration/test_groups_postgres.py @@ -11,8 +11,8 @@ from sqlalchemy.exc import IntegrityError from app.models import Promotion, PromotionGroupMember -from tests.test_auth_postgres import PASSWORD, Harness -from tests.test_dashboard_postgres import clear_promotions, make_promotion +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import PASSWORD, Harness pytestmark = [ pytest.mark.integration, @@ -131,7 +131,7 @@ async def test_attendance_export_respects_directory_scope_and_current_roster( pdf = PdfReader(BytesIO(response.content)) assert pdf.metadata.title.endswith(" - 2019") # Three pupil rows, plus the fixture administrator's name in the footer. - assert pdf.pages[0].extract_text().count("Valentin") == (4) + assert pdf.pages[0].extract_text().count("Exemple") == (4) for role in ("teacher", "kholleur", "user"): identifier, username = await case.create(role) response = await case.client.put( @@ -145,7 +145,7 @@ async def test_attendance_export_respects_directory_scope_and_current_roster( exported = await case.client.get(path) assert exported.status_code == (200 if role == "teacher" else 403) if role == "teacher": - assert PdfReader(BytesIO(exported.content)).metadata.author == "BURGAUD Valentin" + assert PdfReader(BytesIO(exported.content)).metadata.author == "FICTIF Exemple" case.as_admin() assert ( await case.client.delete( @@ -164,7 +164,7 @@ async def test_attendance_export_respects_directory_scope_and_current_roster( ).status_code == 204 response = await case.client.get(path) # Includes the remaining two pupils plus the newly attached student account. - assert PdfReader(BytesIO(response.content)).pages[0].extract_text().count("Valentin") == ( + assert PdfReader(BytesIO(response.content)).pages[0].extract_text().count("Exemple") == ( 4 if variant in {"roster", "global", "halves", "thirds", "kholles"} else 3 ) case.client.cookies.clear() @@ -411,7 +411,7 @@ def tags(response: dict) -> set[tuple[int, str, int]]: assert tags(response.json()) == all_tags for path in ( f"/api/v1/admin/users?promotion_id={shared}", - f"/api/v1/admin/users/search?q=Valentin&promotion_id={shared}", + f"/api/v1/admin/users/search?q=Exemple&promotion_id={shared}", ): response = (await case.client.get(path)).json() items = response if isinstance(response, list) else response["items"] @@ -436,8 +436,8 @@ def tags(response: dict) -> set[tuple[int, str, int]]: for path in ( "/api/v1/teaching/users", f"/api/v1/teaching/users?promotion_id={shared}", - "/api/v1/teaching/users/search?q=Valentin", - f"/api/v1/teaching/users/search?q=Valentin&promotion_id={shared}", + "/api/v1/teaching/users/search?q=Exemple", + f"/api/v1/teaching/users/search?q=Exemple&promotion_id={shared}", ): response = (await case.client.get(path)).json() items = response if isinstance(response, list) else response["items"] diff --git a/backend/tests/test_management_flows.py b/backend/tests/integration/administration/test_management_flows.py similarity index 98% rename from backend/tests/test_management_flows.py rename to backend/tests/integration/administration/test_management_flows.py index b4db68a..29fedb4 100644 --- a/backend/tests/test_management_flows.py +++ b/backend/tests/integration/administration/test_management_flows.py @@ -8,8 +8,8 @@ from app.models import AccountInvitation, ActivityEvent from app.services.mail import DisabledMailer -from tests.test_auth_postgres import PASSWORD, SECOND_PASSWORD, Harness -from tests.test_dashboard_postgres import clear_promotions, make_promotion +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import PASSWORD, SECOND_PASSWORD, Harness pytestmark = [ pytest.mark.integration, @@ -239,7 +239,7 @@ async def test_teacher_scope_includes_archived_students(auth_case: Harness) -> N assert ( await case.client.get(f"/api/v1/teaching/users?promotion_id={other}") ).status_code == 404 - matches = await case.client.get("/api/v1/teaching/users/search?q=valentin") + matches = await case.client.get("/api/v1/teaching/users/search?q=exemple") assert [item["id"] for item in matches.json()] == [student_id] for path in ("/api/v1/admin/users", "/api/v1/admin/summary", "/api/v1/admin/events"): assert (await case.client.get(path)).status_code == 403 @@ -272,7 +272,7 @@ async def test_event_date_order_and_expired_invitation(auth_case: Harness) -> No page = await case.client.get("/api/v1/admin/events?limit=1") assert page.status_code == 200 assert datetime.fromisoformat(page.json()["items"][0]["occurred_at"]) == future - assert page.json()["items"][0]["subject_label"] == "Valentin Burgaud" + assert page.json()["items"][0]["subject_label"] == "Exemple Fictif" cursor = page.json()["next_cursor"] next_page = await case.client.get("/api/v1/admin/events", params={"cursor": cursor, "limit": 1}) assert next_page.json()["items"][0]["id"] != page.json()["items"][0]["id"] diff --git a/backend/tests/test_releases_postgres.py b/backend/tests/integration/administration/test_releases_postgres.py similarity index 76% rename from backend/tests/test_releases_postgres.py rename to backend/tests/integration/administration/test_releases_postgres.py index a328ae4..027afe6 100644 --- a/backend/tests/test_releases_postgres.py +++ b/backend/tests/integration/administration/test_releases_postgres.py @@ -9,11 +9,14 @@ from app.models.releases import ReleaseCheck from app.services import releases -from tests.test_auth_postgres import PASSWORD, Harness +from tests.support.authentication import PASSWORD, Harness -pytestmark = [pytest.mark.integration, pytest.mark.skipif( - os.environ.get("DB_INTEGRATION") != "1", reason="Dedicated PostgreSQL required" -)] +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("DB_INTEGRATION") != "1", reason="Dedicated PostgreSQL required" + ), +] @pytest.mark.asyncio @@ -29,9 +32,11 @@ def fetch() -> tuple[str, str]: monkeypatch.setattr(releases, "fetch_release", fetch) async with case.database.sessions.begin() as db: - await db.execute(update(ReleaseCheck).values( - attempted_at=None, checked_at=None, version=None, release_url=None, error=None - )) + await db.execute( + update(ReleaseCheck).values( + attempted_at=None, checked_at=None, version=None, release_url=None, error=None + ) + ) try: result = await case.client.get("/api/v1/admin/versions") assert result.status_code == 200, result.text @@ -39,9 +44,9 @@ def fetch() -> tuple[str, str]: assert (await case.client.get("/api/v1/admin/versions")).status_code == 200 assert len(calls) == 1 async with case.database.sessions.begin() as db: - await db.execute(update(ReleaseCheck).values( - attempted_at=datetime.now(UTC) - timedelta(days=2) - )) + await db.execute( + update(ReleaseCheck).values(attempted_at=datetime.now(UTC) - timedelta(days=2)) + ) async with case.database.sessions.begin() as locked: await locked.execute(text("SELECT pg_advisory_xact_lock(73482916)")) assert (await case.client.get("/api/v1/admin/versions")).status_code == 200 @@ -60,9 +65,11 @@ def failed() -> None: assert len(calls) == 2 finally: async with case.database.sessions.begin() as db: - await db.execute(update(ReleaseCheck).values( - attempted_at=None, checked_at=None, version=None, release_url=None, error=None - )) + await db.execute( + update(ReleaseCheck).values( + attempted_at=None, checked_at=None, version=None, release_url=None, error=None + ) + ) @pytest.mark.asyncio @@ -73,7 +80,11 @@ async def test_versions_admin_only(auth_case: Harness, role: str) -> None: case.client.cookies.clear() assert (await case.client.get("/api/v1/admin/versions")).status_code == 401 _, username = await case.create(role) - await case.client.post("/api/v1/auth/login", json={ - "identifier": username, "password": PASSWORD, - }) + await case.client.post( + "/api/v1/auth/login", + json={ + "identifier": username, + "password": PASSWORD, + }, + ) assert (await case.client.get("/api/v1/admin/versions")).status_code == 403 diff --git a/backend/tests/test_school_profiles.py b/backend/tests/integration/administration/test_school_profiles.py similarity index 94% rename from backend/tests/test_school_profiles.py rename to backend/tests/integration/administration/test_school_profiles.py index 1dd438a..44ce080 100644 --- a/backend/tests/test_school_profiles.py +++ b/backend/tests/integration/administration/test_school_profiles.py @@ -12,8 +12,8 @@ from app.models import AccountInvitation, ActivityEvent, User from app.schemas.profile import AdminProfileUpdate, Baccalaureate, SchoolProfile from app.services.profiles import calculate_age -from tests.test_auth_postgres import PASSWORD, Harness -from tests.test_dashboard_postgres import clear_promotions, make_promotion +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import PASSWORD, Harness integration = pytest.mark.skipif( os.environ.get("DB_INTEGRATION") != "1", reason="PostgreSQL required" @@ -42,7 +42,7 @@ def test_age_birthday_boundaries(birth: date | None, today: date, expected: int {"phone": "hello"}, {"postal_code": "7500"}, {"orientation_project": "x" * 201}, - {"reference_adult": {"first_name": "Paul", "last_name": "Roy"}}, + {"reference_adult": {"first_name": "Profil", "last_name": "Test"}}, {"baccalaureate": {"overall_grade": 20.01}}, {"baccalaureate": {"subjects": [{"name": "Maths", "grade": -1}]}}, {"baccalaureate": {"subjects": [{"name": "Maths"}, {"name": "maths"}]}}, @@ -111,8 +111,8 @@ async def commune(code: str, postcode: str) -> str: path = f"/api/v1/admin/users/{user_id}/profile" patch = { "expected_version": 0, - "first_name": "Élodie", - "last_name": "Roy", + "first_name": "Échantillon", + "last_name": "Test", "email": "updated-profile@example.org", "birth_date": "2006-05-17", "city": "untrusted label", @@ -127,7 +127,7 @@ async def commune(code: str, postcode: str) -> str: "subjects": [{"name": "Mathématiques", "grade": 0}, {"name": "SI", "grade": 18}], }, "orientation_project": "École d’ingénieurs", - "reference_adult": {"first_name": "Marie", "last_name": "Roy", "phone": "01 23 45 67 89"}, + "reference_adult": {"first_name": "Modele", "last_name": "Test", "phone": "01 23 45 67 89"}, } response = await case.client.patch(path, json=patch) assert response.status_code == 200, response.text @@ -163,10 +163,10 @@ async def commune(code: str, postcode: str) -> str: ) ).all() assert journal and all("changed_fields" in event.data for event in journal) - assert "Roy" not in json.dumps([event.data for event in journal]) + assert "Test" not in json.dumps([event.data for event in journal]) user = (await case.client.get(f"/api/v1/admin/users/{user_id}")).json() assert "birth_date" not in user and "profile" not in user - matches = await case.client.get("/api/v1/admin/users/search?q=elodie%20roy") + matches = await case.client.get("/api/v1/admin/users/search", params={"q": "Échantillon Test"}) assert matches.json()[0]["id"] == user_id login = await case.client.post( "/api/v1/auth/login", @@ -248,8 +248,13 @@ async def test_profile_teacher_scope_and_field_permissions(auth_case: Harness) - case.as_admin() admin_detail = await case.client.get(f"/api/v1/admin/users/{student_id}/profile") assert set(admin_detail.json()["activity"]) == { - "created_at", "login_count", "last_login_at", "updated_at", - "password_changed_at", "email_verified_at", "email_verified", + "created_at", + "login_count", + "last_login_at", + "updated_at", + "password_changed_at", + "email_verified_at", + "email_verified", } finally: await clear_promotions([promotion_id]) @@ -265,11 +270,11 @@ async def test_profile_duplicate_email_rolls_back(auth_case: Harness) -> None: path = f"/api/v1/admin/users/{user_id}/profile" email = (await case.client.get(f"/api/v1/admin/users/{case.administrator}")).json()["email"] response = await case.client.patch( - path, json={"expected_version": 0, "first_name": "Paul", "email": email} + path, json={"expected_version": 0, "first_name": "Profil", "email": email} ) assert response.status_code == 409 detail = (await case.client.get(path)).json() - assert detail["first_name"] == "Valentin" and detail["profile_version"] == 0 + assert detail["first_name"] == "Exemple" and detail["profile_version"] == 0 @pytest.mark.integration @@ -345,12 +350,12 @@ async def test_role_changes_noop_validation_and_atomicity(auth_case: Harness) -> email = (await case.client.get(f"/api/v1/admin/users/{case.administrator}")).json()["email"] response = await case.client.patch( path, - json={"expected_version": 1, "email": email, "roles": ["user"], "first_name": "Paul"}, + json={"expected_version": 1, "email": email, "roles": ["user"], "first_name": "Profil"}, ) assert response.status_code == 409 detail = (await case.client.get(path)).json() assert detail["roles"] == ["admin", "teacher"] and detail["profile_version"] == 1 - assert detail["first_name"] == "Valentin" + assert detail["first_name"] == "Exemple" async with case.database.sessions() as session: events = list( await session.scalars( @@ -418,11 +423,11 @@ async def test_administrator_cannot_remove_own_admin_role(auth_case: Harness) -> path = f"/api/v1/admin/users/{case.administrator}/profile" for roles in [["user"], ["teacher"]]: response = await case.client.patch( - path, json={"expected_version": 0, "roles": roles, "first_name": "Paul"} + path, json={"expected_version": 0, "roles": roles, "first_name": "Profil"} ) assert response.status_code == 409 detail = (await case.client.get(path)).json() - assert detail["roles"] == ["admin"] and detail["first_name"] == "Valentin" + assert detail["roles"] == ["admin"] and detail["first_name"] == "Exemple" assert detail["profile_version"] == 0 for version, roles in enumerate([["teacher", "admin"], ["admin"]]): response = await case.client.patch(path, json={"expected_version": version, "roles": roles}) diff --git a/backend/tests/test_site_postgres.py b/backend/tests/integration/administration/test_site_postgres.py similarity index 99% rename from backend/tests/test_site_postgres.py rename to backend/tests/integration/administration/test_site_postgres.py index 4cb06e4..d80b36e 100644 --- a/backend/tests/test_site_postgres.py +++ b/backend/tests/integration/administration/test_site_postgres.py @@ -11,9 +11,9 @@ from app.models.lessons import LessonCollaborator from app.models.site import Subject, TeacherSubject -from tests.test_auth_postgres import HEADERS, Harness -from tests.test_lessons_postgres import CourseHarness -from tests.test_lessons_postgres import course as course_fixture +from tests.support.authentication import HEADERS, Harness +from tests.support.lessons import CourseHarness +from tests.support.lessons import course as course_fixture course = course_fixture @@ -654,7 +654,7 @@ async def test_combined_roles_preserve_remaining_course_permissions( assert response.status_code == 200, response.text await course.login(course.owner) await course.mutation(f"/collaborators/{course.collaborator_id}", {}, "put") - candidates = await case.client.get(course.path + "/teacher-options", params={"q": "Valentin"}) + candidates = await case.client.get(course.path + "/teacher-options", params={"q": "Exemple"}) assert candidates.status_code == 200, candidates.text assert all(item["id"] != course.collaborator_id for item in candidates.json()) current = await profile(case, course.collaborator_id) diff --git a/backend/tests/integration/auth/__init__.py b/backend/tests/integration/auth/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_auth_postgres.py b/backend/tests/integration/auth/test_auth_postgres.py similarity index 85% rename from backend/tests/test_auth_postgres.py rename to backend/tests/integration/auth/test_auth_postgres.py index f663825..9a1fc12 100644 --- a/backend/tests/test_auth_postgres.py +++ b/backend/tests/integration/auth/test_auth_postgres.py @@ -3,16 +3,12 @@ import argparse import asyncio import os -from collections.abc import AsyncIterator -from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta from pathlib import Path from uuid import uuid4 import httpx2 as httpx import pytest -import pytest_asyncio -from fastapi import FastAPI from sqlalchemy import delete, func, select, update from sqlalchemy.exc import IntegrityError @@ -21,7 +17,6 @@ from app.core.config import DatabaseSettings from app.core.database import Database from app.core.security import IdentityCipher, PasswordSecurity, token_digest -from app.dependencies.auth import AuthenticatedUser, TeacherUser, UserAccount from app.main import create_app from app.models import ( AccountInvitation, @@ -35,8 +30,8 @@ ) from app.services.auth import AuthService from app.services.errors import AuthError -from app.services.mail import MailDeliveryError -from tests.cleanup import clear_test_events +from tests.support.authentication import Harness, MemoryMailer, login_status +from tests.support.cleanup import clear_test_events pytestmark = [ pytest.mark.integration, @@ -49,184 +44,6 @@ HEADERS = {"Origin": "https://testserver", "X-CSRF-Protection": "1"} -class MemoryMailer: - """Capture invitation delivery only inside isolated test memory.""" - - available = True - - def __init__(self) -> None: - """Initialize captured deliveries and an explicit transport failure switch.""" - self.messages: list[tuple[str, str]] = [] - self.fail = False - - async def send_invitation(self, recipient: str, token: str) -> None: - """Capture successful sends or simulate a sanitized transport failure.""" - if self.fail: - raise MailDeliveryError("synthetic transport failure") - self.messages.append((recipient, token)) - - -@dataclass -class Harness: - """Own HTTP clients and only the account records created by this test.""" - - app: FastAPI - database: Database - client: httpx.AsyncClient - mailer: MemoryMailer - prefix: str - ids: list[int] = field(default_factory=list) - administrator: int | None = None - admin_token: str = "" - admin_username: str = "" - emails: dict[str, str] = field(default_factory=dict) - - def as_admin(self) -> None: - """Restore the fixture administrator's browser cookie after a role-specific login.""" - self.client.cookies.clear() - self.client.cookies.set( - self.app.state.auth_settings.cookie_name, - self.admin_token, - domain="testserver.local", - path="/", - ) - - async def create(self, role: str = "user", *, activate: bool = True) -> tuple[int, str]: - """Create and optionally activate a uniquely named account through the real HTTP API.""" - self.as_admin() - username = f"{self.prefix}_{len(self.ids)}" - response = await self.client.post( - "/api/v1/admin/users", - json={ - "first_name": "Valentin", - "last_name": "Burgaud", - "email": f"{username}@example.org", - "roles": [role], - }, - ) - assert response.status_code == 201, response.text - email = f"{username}@example.org" - username = response.json()["username"] - self.emails[username] = email - user_id = int(response.json()["id"]) - self.ids.append(user_id) - if activate: - response = await self.client.post(f"/api/v1/admin/users/{user_id}/invite") - assert response.status_code == 204 - token = self.mailer.messages[-1][1] - response = await self.client.post( - "/api/v1/auth/activate", - json={ - "token": token, - "password": PASSWORD, - }, - ) - assert response.status_code == 204 - return user_id, username - - -@pytest_asyncio.fixture -async def auth_case(migrated_database: None, tmp_path: Path) -> AsyncIterator[Harness]: - """Exercise the initial administrator handover before yielding a normal installation.""" - database = Database(DatabaseSettings()) - mailer = MemoryMailer() - prefix = "u" + uuid4().hex[:12] - secret = tmp_path / "bootstrap-password" - secret.write_text(PASSWORD) - settings = AuthSettings(bootstrap_username=prefix + "_setup", bootstrap_password_file=secret) - app = create_app(mailer=mailer, auth_settings=settings) - async with database.sessions.begin() as session: - await session.execute(update(ApplicationState).values(initialized_at=None)) - - @app.get("/api/v1/test/teacher") - async def teacher(user: TeacherUser) -> dict[str, str]: - """Exercise the reusable teacher-only dependency on a protected operation.""" - return {"id": str(user.id)} - - @app.get("/api/v1/test/student") - async def student(user: UserAccount) -> dict[str, str]: - """Exercise the reusable student-only dependency.""" - return {"id": str(user.id)} - - @app.post("/api/v1/test/write") - async def write(user: AuthenticatedUser) -> dict[str, str]: - """Exercise CSRF enforcement inherited by a future cookie-authenticated route.""" - return {"id": str(user.id)} - - case: Harness | None = None - try: - async with app.router.lifespan_context(app): - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), - base_url="https://testserver", - headers=HEADERS, - ) as client: - case = Harness(app, database, client, mailer, prefix) - async with database.sessions() as session: - initial = await session.scalar(select(User).where(User.is_bootstrap)) - case.ids.append(initial.id) - response = await client.post( - "/api/v1/auth/login", - json={ - "identifier": prefix + "_setup", - "password": PASSWORD, - }, - ) - assert response.status_code == 200 - # Bootstrap sessions can only inspect/logout/complete initial setup. - assert ( - await client.post( - "/api/v1/admin/users", - json={ - "first_name": "Valentin", - "last_name": "Burgaud", - "email": f"{prefix}_forbidden@example.org", - "roles": ["teacher"], - }, - ) - ).status_code == 403 - case.admin_token = client.cookies.get(app.state.auth_settings.cookie_name) - response = await client.post( - "/api/v1/auth/setup", - json={ - "first_name": "Valentin", - "last_name": "Burgaud", - "email": f"{prefix}_1@example.org", - "password": PASSWORD, - }, - ) - assert response.status_code == 201, response.text - case.admin_username = response.json()["username"] - owner = int(response.json()["id"]) - case.ids.append(owner) - case.administrator = owner - assert (await client.get("/api/v1/auth/me")).status_code == 401 - assert ( - await client.post( - "/api/v1/auth/login", - json={ - "identifier": case.admin_username, - "password": PASSWORD, - }, - ) - ).status_code == 200 - case.admin_token = client.cookies.get(app.state.auth_settings.cookie_name) - yield case - finally: - if case and case.ids: - async with database.sessions.begin() as session: - await session.execute( - delete(AccountInvitation).where( - AccountInvitation.user_id.in_(case.ids) - | AccountInvitation.issued_by_user_id.in_(case.ids) - ) - ) - await clear_test_events(case.ids) - await session.execute(delete(User).where(User.id.in_(case.ids))) - await session.execute(update(ApplicationState).values(initialized_at=None)) - await database.close() - - @pytest.mark.asyncio async def test_manual_invitation_lifecycle(auth_case: Harness) -> None: """Keep manual invitations opt-in, single-use and independent of email verification.""" @@ -408,8 +225,8 @@ async def test_generic_failures_and_role_boundaries(auth_case: Harness) -> None: await case.client.post( "/api/v1/admin/users", json={ - "first_name": "Valentin", - "last_name": "Burgaud", + "first_name": "Exemple", + "last_name": "Fictif", "email": "unauthorized@example.org", "roles": ["admin"], }, @@ -684,8 +501,8 @@ async def test_delivery_failure_and_duplicates(auth_case: Harness) -> None: assert invitation.revoked_at is not None for data in ( { - "first_name": "Valentin", - "last_name": "Burgaud", + "first_name": "Exemple", + "last_name": "Fictif", "email": case.emails[username].upper(), "roles": ["user"], }, @@ -695,8 +512,8 @@ async def test_delivery_failure_and_duplicates(auth_case: Harness) -> None: await case.client.post( "/api/v1/admin/users", json={ - "first_name": "Valentin", - "last_name": "Burgaud", + "first_name": "Exemple", + "last_name": "Fictif", "email": "unknown_role@example.org", "roles": ["missing"], }, @@ -747,7 +564,7 @@ async def test_identity_key_rotation_preserves_login( stored.reference_adult_encrypted = case.app.state.identity_cipher.encrypt( stored.id, "reference_adult", - '{"first_name":"Marie","last_name":"Roy","phone":"+33612345678"}', + '{"first_name":"Modele","last_name":"Test","phone":"+33612345678"}', ) new_path = tmp_path / "rotated-keys" generate_keys(new_path) @@ -765,7 +582,7 @@ async def test_identity_key_rotation_preserves_login( assert actor.id == case.administrator stored = await session.get(User, actor.id) assert cipher.decrypt(actor.id, "birth_date", stored.birth_date_encrypted) == '"1988-03-12"' - assert "Marie" in cipher.decrypt( + assert "Modele" in cipher.decrypt( actor.id, "reference_adult", stored.reference_adult_encrypted ) @@ -905,8 +722,8 @@ async def test_setup_is_atomic_and_never_reopens( await client.post( "/api/v1/auth/setup", json={ - "first_name": "Valentin", - "last_name": "Burgaud", + "first_name": "Exemple", + "last_name": "Fictif", "email": "owner@example.org", "password": PASSWORD, }, @@ -923,8 +740,8 @@ async def test_setup_is_atomic_and_never_reopens( ids.append(int(login.json()["id"])) bootstrap_token = client.cookies.get(settings.cookie_name) body = { - "first_name": "Valentin", - "last_name": "Burgaud", + "first_name": "Exemple", + "last_name": "Fictif", "username": prefix, "email": "owner@example.org", "password": PASSWORD, @@ -1205,31 +1022,6 @@ async def test_expired_rate_counter_maintenance(auth_case: Harness) -> None: ) -async def login_status( - case: Harness, - identifier: str, - password: str, - ip: str, - settings: AuthSettings, - now: datetime | None = None, -) -> int: - """Return a service login status using an independent session and optional clock.""" - async with case.database.sessions() as session: - service = AuthService( - session, - settings, - case.app.state.identity_cipher, - case.app.state.passwords, - case.mailer, - clock=(lambda: now) if now is not None else None, - ) - try: - await service.login(identifier, password, ip) - return 200 - except AuthError as error: - return error.status - - @pytest.mark.asyncio @pytest.mark.parametrize("password, expected", [("Abcdefg1!@", 204), ("Abcdefgh12", 422)]) async def test_activation_uses_permanent_password_policy( diff --git a/backend/tests/integration/conftest.py b/backend/tests/integration/conftest.py new file mode 100644 index 0000000..f369484 --- /dev/null +++ b/backend/tests/integration/conftest.py @@ -0,0 +1,4 @@ +"""Register shared database-backed domain fixtures independently of test modules.""" + +from tests.support.documents import documents # noqa: F401 +from tests.support.timetable import workspace # noqa: F401 diff --git a/backend/tests/integration/database/__init__.py b/backend/tests/integration/database/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_postgres.py b/backend/tests/integration/database/test_postgres.py similarity index 97% rename from backend/tests/test_postgres.py rename to backend/tests/integration/database/test_postgres.py index 9130262..26da744 100644 --- a/backend/tests/test_postgres.py +++ b/backend/tests/integration/database/test_postgres.py @@ -26,7 +26,7 @@ TimetablePreferences, TimetableSchoolYear, ) -from tests.postgres import run_alembic +from tests.support.postgres import run_alembic pytestmark = [ pytest.mark.integration, @@ -116,7 +116,7 @@ async def test_kholloscope_migration_roundtrip(databases: tuple[Database, Databa ) ) ) - assert {"kholle_min_hours", "kholle_max_hours"} <= columns + assert columns == {"user_id", "school_year", "ranges", "revision"} assert ( await session.scalar( text( @@ -494,6 +494,17 @@ async def test_feature_migration_stages(databases: tuple[Database, Database]) -> ) is None ) + run_alembic("upgrade", "0007_timetable") + async with migration.sessions() as session: + columns = set( + await session.scalars( + text( + "SELECT column_name FROM information_schema.columns " + "WHERE table_schema = 'sophikron' AND table_name = 'teacher_availability'" + ) + ) + ) + assert columns == {"user_id", "school_year", "ranges", "revision"} run_alembic("upgrade", "head") async with migration.sessions() as session: assert await session.scalar( diff --git a/backend/tests/integration/kholloscope/__init__.py b/backend/tests/integration/kholloscope/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_kholloscope_generation_postgres.py b/backend/tests/integration/kholloscope/test_kholloscope_generation_postgres.py similarity index 99% rename from backend/tests/test_kholloscope_generation_postgres.py rename to backend/tests/integration/kholloscope/test_kholloscope_generation_postgres.py index 0b167a3..7c616ea 100644 --- a/backend/tests/test_kholloscope_generation_postgres.py +++ b/backend/tests/integration/kholloscope/test_kholloscope_generation_postgres.py @@ -25,7 +25,7 @@ ) from app.services.kholloscope_worker import generation_maintenance from app.services.timetable_engine import PARIS -from tests.test_timetable_workspace_postgres import Workspace, workspace # noqa: F401 +from tests.support.timetable import Workspace, workspace # noqa: F401 pytestmark = [ pytest.mark.integration, diff --git a/backend/tests/test_kholloscope_revision_postgres.py b/backend/tests/integration/kholloscope/test_kholloscope_revision_postgres.py similarity index 99% rename from backend/tests/test_kholloscope_revision_postgres.py rename to backend/tests/integration/kholloscope/test_kholloscope_revision_postgres.py index a64635d..623c76a 100644 --- a/backend/tests/test_kholloscope_revision_postgres.py +++ b/backend/tests/integration/kholloscope/test_kholloscope_revision_postgres.py @@ -28,7 +28,7 @@ from app.schemas.timetable import SeriesData from app.services.kholloscope_worker import generation_maintenance from app.services.timetable_engine import PARIS -from tests.test_timetable_workspace_postgres import Workspace, workspace # noqa: F401 +from tests.support.timetable import Workspace, workspace # noqa: F401 pytestmark = [ pytest.mark.integration, diff --git a/backend/tests/integration/lessons/__init__.py b/backend/tests/integration/lessons/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_lesson_documents_postgres.py b/backend/tests/integration/lessons/test_lesson_documents_postgres.py similarity index 92% rename from backend/tests/test_lesson_documents_postgres.py rename to backend/tests/integration/lessons/test_lesson_documents_postgres.py index afddd49..f39a458 100644 --- a/backend/tests/test_lesson_documents_postgres.py +++ b/backend/tests/integration/lessons/test_lesson_documents_postgres.py @@ -3,20 +3,19 @@ import asyncio import hashlib import os -from collections.abc import AsyncIterator from contextlib import suppress from datetime import date, timedelta import anyio import pytest -import pytest_asyncio from sqlalchemy import delete, select from app.models import User from app.models.lessons import LessonFile, LessonFileDeletion, LessonUpload from app.models.site import TeacherSubject from app.services.document_storage import DocumentStorage, cleanup_documents -from tests.test_lessons_postgres import CourseHarness +from tests.support.documents import reserve, upload +from tests.support.lessons import CourseHarness pytestmark = [ pytest.mark.integration, @@ -27,58 +26,6 @@ PAYLOAD = b'print("pedagogical fixture, never executed")\n' -@pytest_asyncio.fixture -async def documents(course: CourseHarness) -> AsyncIterator[CourseHarness]: - """Exercise real parsing, disk IO and database operations throughout the document lifecycle.""" - try: - yield course - finally: - async with course.case.database.sessions.begin() as session: - await session.execute( - delete(LessonFile).where(LessonFile.lesson_id.in_(course.course_ids)) - ) - await session.execute( - delete(LessonUpload).where(LessonUpload.lesson_id.in_(course.course_ids)) - ) - await cleanup_documents( - course.case.database, DocumentStorage(course.case.app.state.document_settings) - ) - - -async def reserve(course: CourseHarness, parent: int, **changes: object) -> str: - """Reserve a named Python document using the real authenticated API.""" - response = await course.case.client.post( - course.path + "/uploads", - json={ - "expected_version": course.state["version"], - "parent_id": parent, - "title": "Mon nom pédagogique", - "filename": "original.py", - "size_bytes": len(PAYLOAD), - **changes, - }, - ) - assert response.status_code == 201, response.text - return response.json()["upload_id"] - - -async def upload(course: CourseHarness, parent: int, **changes: object) -> dict: - """Run a real binary upload and retain the new course version.""" - key = await reserve(course, parent, **changes) - response = await course.case.client.put( - course.path + f"/uploads/{key}", - content=PAYLOAD, - headers={"Content-Type": "application/octet-stream"}, - ) - assert response.status_code == 200, response.text - course.state = response.json() - return next( - item - for item in course.state["elements"] - if item["kind"] == "file" and item["title"] == changes.get("title", "Mon nom pédagogique") - ) - - @pytest.mark.asyncio async def test_staff_sections_hide_entire_subtrees_but_teachers_and_collaborating_kholleurs_read( documents: CourseHarness, diff --git a/backend/tests/test_lessons_postgres.py b/backend/tests/integration/lessons/test_lessons_postgres.py similarity index 83% rename from backend/tests/test_lessons_postgres.py rename to backend/tests/integration/lessons/test_lessons_postgres.py index 22337be..2d61bdd 100644 --- a/backend/tests/test_lessons_postgres.py +++ b/backend/tests/integration/lessons/test_lessons_postgres.py @@ -1,26 +1,22 @@ """Actual PostgreSQL course permissions, scheduling, invariants and atomic audit events.""" import os -from collections.abc import AsyncIterator -from dataclasses import dataclass, field from datetime import date, timedelta from pathlib import Path import pytest -import pytest_asyncio from alembic.migration import MigrationContext from alembic.operations import Operations from alembic.script import ScriptDirectory -from sqlalchemy import Connection, delete, select, text +from sqlalchemy import Connection, select, text from sqlalchemy.exc import IntegrityError from app.core.config import DatabaseSettings from app.core.database import Database from app.models import ActivityEvent -from app.models.lessons import Lesson, LessonElement -from app.models.site import Subject, TeacherSubject -from tests.test_auth_postgres import PASSWORD, Harness -from tests.test_dashboard_postgres import clear_promotions +from app.models.lessons import LessonElement +from app.models.site import TeacherSubject +from tests.support.lessons import CourseHarness pytestmark = [ pytest.mark.integration, @@ -74,7 +70,7 @@ async def test_existing_lesson_policies_upgrade_preserves_private_content( def upgrade(sync_connection: Connection) -> None: """Apply the amended baseline helper with the migration role.""" - script = ScriptDirectory(str(Path(__file__).resolve().parents[1] / "alembic")) + script = ScriptDirectory(str(Path(__file__).resolve().parents[3] / "alembic")) with Operations.context(MigrationContext.configure(sync_connection)): script.get_revision("0005_lessons").module.upgrade_lesson_policies() @@ -133,7 +129,7 @@ async def test_collaborator_options_browse_live_search_and_exclusions( eligible = [teacher_id, *(identifier for identifier, _ in readers)] await course.login(course.owner) path = course.path + "/teacher-options" - for params in [{}, {"q": ""}, {"q": "V"}, {"q": " valentin "}]: + for params in [{}, {"q": ""}, {"q": "F"}, {"q": " exemple "}]: response = await case.client.get(path, params=params) assert response.status_code == 200, response.text assert [person["id"] for person in response.json()] == eligible[:5] @@ -169,131 +165,6 @@ async def test_collaborator_options_browse_live_search_and_exclusions( assert (await case.client.get(path)).status_code == 401 -@dataclass -class CourseHarness: - """Own only synthetic course records and principals for one isolated integration test.""" - - case: Harness - owner_id: int - owner: str - collaborator_id: int - collaborator: str - student_id: int - student: str - state: dict - course_ids: list[int] = field(default_factory=list) - promotion_ids: list[int] = field(default_factory=list) - - @property - def path(self) -> str: - """Return this fixture's course URL.""" - return f"/api/v1/lessons/{self.state['id']}" - - async def login(self, username: str) -> None: - """Switch principals through the real session API.""" - response = await self.case.client.post( - "/api/v1/auth/login", - json={"identifier": username, "password": PASSWORD}, - ) - assert response.status_code == 200, response.text - - async def mutation(self, suffix: str, data: dict, method: str = "post") -> dict: - """Save one revision and keep the returned state for the next authorized mutation.""" - response = await self.case.client.request( - method, - self.path + suffix, - json={"expected_version": self.state["version"], **data}, - ) - assert response.status_code in {200, 201}, response.text - self.state = response.json() - return self.state - - async def promotion(self, *, assign: bool = True) -> int: - """Create an active current-year promotion and optionally assign the fixture student.""" - self.case.as_admin() - today = date.fromisoformat(self.state["today"]) - year = today.year if today.month >= 9 else today.year - 1 - response = await self.case.client.post( - "/api/v1/admin/promotions", - json={ - "year": year, - "identifier": f"COURSE-{self.case.prefix}-{len(self.promotion_ids)}", - "color": "#123ABC", - }, - ) - assert response.status_code == 201, response.text - identifier = response.json()["id"] - self.promotion_ids.append(identifier) - if assign: - assert ( - await self.case.client.put( - f"/api/v1/admin/users/{self.student_id}/promotions/{identifier}", - ) - ).status_code == 204 - await self.login(self.owner) - await self.mutation(f"/promotions/{identifier}", {}, "put") - return identifier - - -@pytest_asyncio.fixture -async def course(auth_case: Harness) -> AsyncIterator[CourseHarness]: - """Create a course with independent owner, collaborator and student accounts.""" - owner_id, owner = await auth_case.create("teacher") - collaborator_id, collaborator = await auth_case.create("teacher") - student_id, student = await auth_case.create("user") - async with auth_case.database.sessions.begin() as session: - subject = Subject( - name=f"Maths {auth_case.prefix}", - name_key=auth_case.prefix, - icon="book", - color="#41754E", - ) - session.add(subject) - await session.flush() - subject_id = subject.id - session.add_all( - [ - TeacherSubject(user_id=identifier, subject_id=subject_id) - for identifier in (owner_id, collaborator_id) - ] - ) - await auth_case.client.post( - "/api/v1/auth/login", - json={"identifier": owner, "password": PASSWORD}, - ) - response = await auth_case.client.post( - "/api/v1/lessons", - json={ - "title": f"Cours {auth_case.prefix}", - "description": "Programme annuel", - "subject_id": subject_id, - }, - ) - assert response.status_code == 201, response.text - fixture = CourseHarness( - auth_case, - owner_id, - owner, - collaborator_id, - collaborator, - student_id, - student, - response.json(), - ) - fixture.course_ids.append(fixture.state["id"]) - try: - yield fixture - finally: - async with auth_case.database.sessions.begin() as session: - await session.execute(delete(Lesson).where(Lesson.id.in_(fixture.course_ids))) - await session.execute( - delete(TeacherSubject).where(TeacherSubject.subject_id == subject_id) - ) - await session.execute(delete(Subject).where(Subject.id == subject_id)) - if fixture.promotion_ids: - await clear_promotions(fixture.promotion_ids) - - @pytest.mark.asyncio async def test_catalogue_page_gates_and_default_school_year(course: CourseHarness) -> None: """Keep cards public to members while denying page bodies without active promotion grants.""" @@ -414,7 +285,7 @@ async def test_creator_collaborator_and_admin_permissions_follow_current_roles( }, ) ).status_code == 403 - assert (await case.client.get(f"{course.path}/teacher-options?q=Valentin")).status_code == 403 + assert (await case.client.get(f"{course.path}/teacher-options?q=Exemple")).status_code == 403 case.as_admin() changed = await case.client.patch( f"/api/v1/admin/users/{course.collaborator_id}/profile", diff --git a/backend/tests/integration/lessons/test_option_routes.py b/backend/tests/integration/lessons/test_option_routes.py new file mode 100644 index 0000000..62bae7b --- /dev/null +++ b/backend/tests/integration/lessons/test_option_routes.py @@ -0,0 +1,42 @@ +"""Live course option authorization and document-limit contracts.""" + +import os + +import pytest + +from app.services.file_validation import FILE_TYPES +from tests.support.lessons import CourseHarness + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("DB_INTEGRATION") != "1", reason="Disposable PostgreSQL required" + ), +] + + +@pytest.mark.asyncio +async def test_course_options_require_live_editor_and_admin_rights(course: CourseHarness) -> None: + """Expose promotion metadata to editors and responsibility candidates only to admins.""" + promotion = await course.promotion() + case = course.case + response = await case.client.get(course.path + "/promotion-options") + assert response.status_code == 200 + assert promotion in {row["id"] for row in response.json()} + assert (await case.client.get(course.path + "/promotion-options?limit=0")).status_code == 422 + params = {"subject_id": course.state["subject_id"], "q": "a"} + assert ( + await case.client.get(course.path + "/responsible-options", params=params) + ).status_code == 422 + params["q"] = "zz" + assert ( + await case.client.get(course.path + "/responsible-options", params=params) + ).status_code == 403 + case.as_admin() + response = await case.client.get(course.path + "/responsible-options", params=params) + assert response.status_code == 200 and response.json() == [] + await course.login(course.student) + assert (await case.client.get(course.path + "/promotion-options")).status_code == 403 + response = await case.client.get("/api/v1/lessons/document-limits") + assert response.status_code == 200 + assert response.json() == {"types": {key: value[0] for key, value in FILE_TYPES.items()}} diff --git a/backend/tests/test_shared_teaching_postgres.py b/backend/tests/integration/lessons/test_shared_teaching_postgres.py similarity index 96% rename from backend/tests/test_shared_teaching_postgres.py rename to backend/tests/integration/lessons/test_shared_teaching_postgres.py index 308b248..38c4f8d 100644 --- a/backend/tests/test_shared_teaching_postgres.py +++ b/backend/tests/integration/lessons/test_shared_teaching_postgres.py @@ -7,8 +7,8 @@ from icalendar import Calendar from app.models import TimetableSubscription -from tests.test_calendar_subscriptions_postgres import personal -from tests.test_timetable_workspace_postgres import Workspace, workspace # noqa: F401 +from tests.support.subscriptions import personal +from tests.support.timetable import Workspace, workspace # noqa: F401 pytestmark = [ pytest.mark.integration, diff --git a/backend/tests/integration/statistics/__init__.py b/backend/tests/integration/statistics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_api_monitoring_postgres.py b/backend/tests/integration/statistics/test_api_monitoring_postgres.py similarity index 61% rename from backend/tests/test_api_monitoring_postgres.py rename to backend/tests/integration/statistics/test_api_monitoring_postgres.py index 190766d..9a46a88 100644 --- a/backend/tests/test_api_monitoring_postgres.py +++ b/backend/tests/integration/statistics/test_api_monitoring_postgres.py @@ -2,14 +2,16 @@ import asyncio import os +from copy import copy from datetime import UTC, datetime, timedelta import pytest from sqlalchemy import delete from app.models.statistics import ApiMetric -from app.services.api_monitoring import ApiMonitor -from tests.test_auth_postgres import Harness +from app.services.api_monitoring import ApiMonitor, ApiMonitoringService +from app.services.auth import AuthService +from tests.support.authentication import Harness pytestmark = [ pytest.mark.integration, @@ -20,22 +22,43 @@ @pytest.mark.asyncio -async def test_atomic_monitoring_reduction_retention_and_authorization(auth_case: Harness) -> None: +async def test_atomic_monitoring_reduction_retention_and_authorization( + auth_case: Harness, + monkeypatch: pytest.MonkeyPatch, +) -> None: """Reduce many minute rows in SQL, preserve exact code counts and reject non-admin reads.""" case = auth_case - now = datetime.now(UTC).replace(second=0, microsecond=0) + # Keep every sample within one Paris day, away from live middleware observations. + now = datetime.now(UTC).replace(hour=12, minute=0, second=0, microsecond=0) - timedelta(days=2) + + def monitoring_with_fixed_clock(auth: AuthService) -> ApiMonitoringService: + """Freeze only monitoring reads, preserving real session creation and authentication.""" + isolated_auth = copy(auth) + isolated_auth.clock = lambda: now + timedelta(seconds=30) + return ApiMonitoringService(isolated_auth) + + monkeypatch.setattr("app.api.v1.statistics.ApiMonitoringService", monitoring_with_fixed_clock) first, second = ApiMonitor(), ApiMonitor() + outside = ApiMonitor() + outside_bucket = now + timedelta(hours=2) + outside.observe("other", 200, 1000, now=outside_bucket) for index in range(60): moment = now - timedelta(minutes=index) first.observe("other", 200, 1000, now=moment) second.observe("other", 503, 100000, now=moment) try: - await asyncio.gather(first.flush(case.database), second.flush(case.database)) - assert not first.pending and not second.pending + await asyncio.gather( + first.flush(case.database), + second.flush(case.database), + outside.flush(case.database), + ) + assert not first.pending and not second.pending and not outside.pending async with case.database.sessions() as session: row = await session.get(ApiMetric, (now, "other")) assert row.requests == 2 and row.statuses == {"200": 1, "503": 1} assert sum(row.histogram.values()) == 2 + outside_row = await session.get(ApiMetric, (outside_bucket, "other")) + assert outside_row.requests == 1 case.as_admin() for period, maximum in (("day", 1500), ("week", 169), ("month", 30)): response = await case.client.get( @@ -44,7 +67,7 @@ async def test_atomic_monitoring_reduction_retention_and_authorization(auth_case assert response.status_code == 200, response.text body = response.json() assert len(body["points"]) <= maximum - assert body["requests"] >= 2 + assert body["requests"] == 120 assert body["mean_ms"] == 50.5 and body["p95_ms"] == 100 assert body["server_error_rate"] == 50 point = next(point for point in body["points"] if point["requests"] > 0) @@ -73,10 +96,21 @@ async def test_atomic_monitoring_reduction_retention_and_authorization(auth_case async with case.database.sessions() as session: assert await session.get(ApiMetric, (now - timedelta(days=32), "other")) is None _, name = await case.create("teacher") - from tests.test_calendar_subscriptions_postgres import login + from tests.support.subscriptions import login await login(case, name) assert (await case.client.get("/api/v1/admin/monitoring")).status_code == 403 finally: async with case.database.sessions.begin() as session: - await session.execute(delete(ApiMetric).where(ApiMetric.category == "other")) + await session.execute( + delete(ApiMetric).where( + ApiMetric.category == "other", + ApiMetric.bucket.in_( + [ + *(now - timedelta(minutes=index) for index in range(60)), + outside_bucket, + now - timedelta(days=32), + ] + ), + ) + ) diff --git a/backend/tests/test_statistics_postgres.py b/backend/tests/integration/statistics/test_statistics_postgres.py similarity index 97% rename from backend/tests/test_statistics_postgres.py rename to backend/tests/integration/statistics/test_statistics_postgres.py index 06ad043..e869a14 100644 --- a/backend/tests/test_statistics_postgres.py +++ b/backend/tests/integration/statistics/test_statistics_postgres.py @@ -12,9 +12,9 @@ from app.models.statistics import LoginStatistic from app.services.activity import record_event from app.services.statistics_recording import record_login_failure -from tests.test_auth_postgres import Harness -from tests.test_lesson_documents_postgres import PAYLOAD, documents, upload # noqa: F401 -from tests.test_lessons_postgres import CourseHarness +from tests.support.authentication import Harness +from tests.support.documents import PAYLOAD, documents, upload # noqa: F401 +from tests.support.lessons import CourseHarness pytestmark = [ pytest.mark.integration, diff --git a/backend/tests/integration/timetable/__init__.py b/backend/tests/integration/timetable/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_calendar_subscriptions_postgres.py b/backend/tests/integration/timetable/test_calendar_subscriptions_postgres.py similarity index 92% rename from backend/tests/test_calendar_subscriptions_postgres.py rename to backend/tests/integration/timetable/test_calendar_subscriptions_postgres.py index dac1e71..38464e9 100644 --- a/backend/tests/test_calendar_subscriptions_postgres.py +++ b/backend/tests/integration/timetable/test_calendar_subscriptions_postgres.py @@ -11,9 +11,10 @@ from app.models import AuthRateLimit, TimetableCalendar, TimetableSubscription from app.models.site import SiteSettings from app.services.timetable import TimetableService -from tests.test_auth_postgres import PASSWORD, Harness -from tests.test_dashboard_postgres import clear_promotions, make_promotion -from tests.test_timetable_workspace_postgres import Workspace, workspace # noqa: F401 +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import Harness +from tests.support.subscriptions import feed, login, personal +from tests.support.timetable import Workspace, workspace # noqa: F401 pytestmark = [ pytest.mark.integration, @@ -23,31 +24,6 @@ ] -async def login(case: Harness, name: str) -> None: - """Switch to a real account without bypassing session authentication.""" - case.client.cookies.clear() - response = await case.client.post( - "/api/v1/auth/login", json={"identifier": name, "password": PASSWORD} - ) - assert response.status_code == 200, response.text - - -async def personal(case: Harness) -> dict: - """Read only the current owner's credential via its authenticated endpoint.""" - response = await case.client.get("/api/v1/timetable/subscription") - assert response.status_code == 200, response.text - return response.json() - - -async def feed(case: Harness, token: str) -> list: - """Parse the public ICS route, requiring successful private, nonindexed responses.""" - response = await case.client.get(f"/api/v1/timetable/feed/{token}.ics") - assert response.status_code == 200, response.text - assert "no-store" in response.headers["cache-control"] - assert "noindex" in response.headers["x-robots-tag"] - return Calendar.from_ical(response.content).walk("VEVENT") - - @pytest.mark.asyncio async def test_active_feed_minute_budget(auth_case: Harness) -> None: """Limit active links even when empty, reset expired windows and ignore revoked tokens.""" diff --git a/backend/tests/test_timetable_workspace_postgres.py b/backend/tests/integration/timetable/test_timetable_workspace_postgres.py similarity index 92% rename from backend/tests/test_timetable_workspace_postgres.py rename to backend/tests/integration/timetable/test_timetable_workspace_postgres.py index 12c4b64..859a9e8 100644 --- a/backend/tests/test_timetable_workspace_postgres.py +++ b/backend/tests/integration/timetable/test_timetable_workspace_postgres.py @@ -1,13 +1,10 @@ """Live annual calendars, authorization, archival and bounded-query personal feeds.""" import os -from collections.abc import AsyncIterator -from dataclasses import dataclass, field from datetime import date, datetime, timedelta, timezone from io import BytesIO import pytest -import pytest_asyncio from icalendar import Calendar from pypdf import PdfReader from sqlalchemy import delete, select @@ -35,8 +32,9 @@ ) from app.services.timetable_engine import PARIS from app.services.timetable_lifecycle import rollover -from tests.test_auth_postgres import PASSWORD, Harness -from tests.test_dashboard_postgres import clear_promotions, make_promotion +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import PASSWORD +from tests.support.timetable import Workspace pytestmark = [ pytest.mark.integration, @@ -115,152 +113,6 @@ async def test_kholloscope_database_constraints(workspace: "Workspace") -> None: await session.rollback() -@dataclass -class Workspace: - """Own only this scenario's accounts, promotions and annual calendars.""" - - case: Harness - promotion_id: int - teacher_id: int - teacher_name: str - pupil_id: int - pupil_name: str - school_year: int - settings: dict - calendar_id: int = 0 - calendar_ids: list[int] = field(default_factory=list) - - async def create(self, *, promotion: int | None = None, school_year: int | None = None) -> int: - """Create an independent annual calendar through the actual administrator API.""" - self.case.as_admin() - response = await self.case.client.post( - "/api/v1/timetable/calendars", - json={ - "name": f"{self.case.prefix}-{len(self.calendar_ids)}", - "promotion_id": promotion, - "school_year": school_year or self.school_year, - "settings": self.settings, - "is_paused": True, - }, - ) - assert response.status_code == 201, response.text - identifier = response.json()["id"] - self.calendar_ids.append(identifier) - return identifier - - async def board(self, identifier: int | None = None) -> dict: - """Read the real live board with an administrator session.""" - self.case.as_admin() - response = await self.case.client.get( - "/api/v1/timetable/board", params={"calendar_ids": identifier or self.calendar_id} - ) - assert response.status_code == 200, response.text - return response.json() - - async def add(self, **changes: object) -> dict: - """Save a recurring session and return its refreshed actual annual board.""" - state = await self.board() - year = state["years"][0] - beginning = date.fromisoformat(self.settings["start"]) - beginning += timedelta(days=(-beginning.weekday()) % 7) - response = await self.case.client.post( - f"/api/v1/timetable/years/{year['id']}/series", - json={ - "expected_revision": year["revision"], - "confirmed_live": True, - "block": { - "starts_on": beginning.isoformat(), - "start_slot": 0, - "duration_slots": 2, - "teacher_id": self.teacher_id, - "title": "Maths", - "interval": 1, - **changes, - }, - }, - ) - assert response.status_code == 201, response.text - return await self.board() - - async def broadcast(self) -> dict: - """Enable diffusion using the observed calendar revision.""" - state = await self.board() - agenda = state["calendars"][0] - response = await self.case.client.put( - f"/api/v1/timetable/calendars/{self.calendar_id}", - json={ - "name": agenda["name"], - "promotion_id": agenda["promotion_id"], - "is_paused": False, - "expected_revision": agenda["revision"], - "confirmed_live": True, - }, - ) - assert response.status_code == 200, response.text - return await self.board() - - async def login(self, username: str) -> None: - """Switch to a real account session without bypassing permission dependencies.""" - self.case.client.cookies.clear() - response = await self.case.client.post( - "/api/v1/auth/login", json={"identifier": username, "password": PASSWORD} - ) - assert response.status_code == 200, response.text - - -@pytest_asyncio.fixture -async def workspace(auth_case: Harness) -> AsyncIterator[Workspace]: - """Build an isolated roster and clean only explicitly created timetable records.""" - case = auth_case - promotion = await make_promotion(case, "LIVE-TIMETABLE") - teacher, teacher_name = await case.create("teacher") - pupil, pupil_name = await case.create() - school_year = date.today().year - (date.today().month < 9) - case.as_admin() - response = await case.client.post( - f"/api/v1/admin/promotions/{promotion}/users", json={"user_ids": [teacher, pupil]} - ) - assert response.status_code == 204, response.text - response = await case.client.post( - "/api/v1/timetable/school-years", json={"school_year": school_year} - ) - assert response.status_code == 201, response.text - w = Workspace( - case, - promotion, - teacher, - teacher_name, - pupil, - pupil_name, - school_year, - { - "start": f"{school_year}-09-01", - "end": f"{school_year + 1}-08-31", - "session_minutes": 60, - "day_start": 28800, - "day_end": 68400, - "lunch_start": 43200, - "lunch_end": 50400, - "breaks": [], - }, - ) - try: - w.calendar_id = await w.create(promotion=promotion) - yield w - finally: - async with case.database.sessions.begin() as session: - await session.execute( - delete(TimetableCalendar).where(TimetableCalendar.id.in_(w.calendar_ids)) - ) - await session.execute( - delete(TeacherAvailability).where(TeacherAvailability.user_id == teacher) - ) - await session.execute( - delete(TimetableSchoolYear).where(TimetableSchoolYear.school_year == school_year) - ) - await clear_promotions([promotion]) - - @pytest.mark.asyncio async def test_kholle_counts_exclude_archived_only_groups_and_retain_mixed_groups( workspace: Workspace, diff --git a/backend/tests/perf/__init__.py b/backend/tests/perf/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/perf/administration/__init__.py b/backend/tests/perf/administration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/perf/administration/test_search.py b/backend/tests/perf/administration/test_search.py new file mode 100644 index 0000000..f0d3b81 --- /dev/null +++ b/backend/tests/perf/administration/test_search.py @@ -0,0 +1,101 @@ +"""Encrypted PostgreSQL search latency at representative volumes.""" + +import asyncio +import os +from math import ceil +from time import perf_counter + +import pytest +from sqlalchemy import insert, select, text + +from app.models import Role, User, UserPromotion, UserRole +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import Harness + +pytestmark = [ + pytest.mark.perf, + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("DB_INTEGRATION") != "1", reason="Disposable PostgreSQL required" + ), +] + + +@pytest.mark.asyncio +async def test_interactive_search_representative_volumes(auth_case: Harness) -> None: + """Measure complete ASGI searches over encrypted PostgreSQL identities with three callers.""" + case = auth_case + promotion_id = await make_promotion(case, "SEARCH-BENCHMARK") + cipher = case.app.state.identity_cipher + try: + for count in (2000, 8000): + async with case.database.sessions.begin() as session: + ids = list( + ( + await session.scalars( + text( + "SELECT nextval(pg_get_serial_sequence('sophikron.users', 'id')) " + "FROM generate_series(1, :count)" + ), + {"count": count}, + ) + ).all() + ) + records = [] + for index, user_id in enumerate(ids): + username = f"benchmark{user_id}" + email = f"{username}@example.org" + first, last = ( + ("Exemple", "Fictif") if index % 10 == 0 else ("Alpha", "Specimen") + ) + records.append( + dict( + id=user_id, + first_name_encrypted=cipher.encrypt(user_id, "first_name", first), + last_name_encrypted=cipher.encrypt(user_id, "last_name", last), + username_encrypted=cipher.encrypt(user_id, "username", username), + email_encrypted=cipher.encrypt(user_id, "email", email), + username_lookup=cipher.lookup("username", username), + email_lookup=cipher.lookup("email", email), + ) + ) + await session.execute(insert(User), records) + role_id = await session.scalar(select(Role.id).where(Role.code == "user")) + await session.execute( + insert(UserRole), [dict(user_id=item, role_id=role_id) for item in ids] + ) + await session.execute( + insert(UserPromotion), + [dict(user_id=item, promotion_id=promotion_id) for item in ids], + ) + case.ids.extend(ids) + + async def timed_search() -> float: + """Measure full authenticated query, database loading, decryption and ranking.""" + start = perf_counter() + response = await case.client.get( + "/api/v1/admin/users/search", + params={ + "q": "exemple ficto", + "promotion_id": promotion_id, + }, + ) + elapsed = perf_counter() - start + assert response.status_code == 200 and len(response.json()) == 20 + assert all(item["last_name"] == "Fictif" for item in response.json()) + return elapsed + + await timed_search() + samples = [] + for _ in range(4): + samples.extend(await asyncio.gather(*(timed_search() for _ in range(3)))) + p95 = sorted(samples)[ceil(len(samples) * 0.95) - 1] + volume = 2000 if count == 2000 else 10000 + print( + f"Search benchmark: {volume} accounts, 3 concurrent callers, " + f"p95={p95 * 1000:.1f} ms" + ) + # A broad regression ceiling avoids turning a hardware-specific target into flaky CI. + assert p95 < 2, "Interactive search exceeded the two-second regression ceiling" + finally: + await clear_promotions([promotion_id]) diff --git a/backend/tests/perf/administration/test_search_ranking_latency.py b/backend/tests/perf/administration/test_search_ranking_latency.py new file mode 100644 index 0000000..9541502 --- /dev/null +++ b/backend/tests/perf/administration/test_search_ranking_latency.py @@ -0,0 +1,27 @@ +"""Measured performance regression budgets with correctness assertions.""" + +from collections.abc import Callable +from time import perf_counter + +import pytest + +from app.services.search import prepare_name, rank_prepared_names + +pytestmark = pytest.mark.perf + + +@pytest.mark.parametrize("count", [2000, 10000]) +def test_search_ranking_latency(count: int, record_property: Callable[[str, object], None]) -> None: + """Keep top-result correctness while measuring repeated large candidate ranking.""" + names = {i: prepare_name("Alpha", "Specimen") for i in range(count)} + names[count] = prepare_name("Exemple", "Fictif") + samples = [] + for _ in range(6): + start = perf_counter() + result = rank_prepared_names("exemple ficto", names, 20) + samples.append(perf_counter() - start) + assert result[0] == count + p95 = max(samples[1:]) + record_property("p95_seconds", p95) + record_property("accounts", count) + assert p95 < 2 diff --git a/backend/tests/perf/kholloscope/__init__.py b/backend/tests/perf/kholloscope/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/perf/kholloscope/conftest.py b/backend/tests/perf/kholloscope/conftest.py new file mode 100644 index 0000000..fa505b6 --- /dev/null +++ b/backend/tests/perf/kholloscope/conftest.py @@ -0,0 +1,3 @@ +"""Register the real small-model input fixture for solver performance tests.""" + +from tests.support.solver import solver_input # noqa: F401 diff --git a/backend/tests/perf/kholloscope/test_generation.py b/backend/tests/perf/kholloscope/test_generation.py new file mode 100644 index 0000000..3746e10 --- /dev/null +++ b/backend/tests/perf/kholloscope/test_generation.py @@ -0,0 +1,28 @@ +"""Real small-model CP-SAT runtime with exact annual-volume checks.""" + +import threading +from collections import Counter +from collections.abc import Callable +from time import perf_counter + +import pytest + +from app.services.kholloscope_solver import generate + +pytestmark = pytest.mark.perf + + +def test_generation_budget_and_exact_volumes( + solver_input: dict, + record_property: Callable[[str, object], None], +) -> None: + """A bounded real solve must return exact quotas rather than a fast partial schedule.""" + start = perf_counter() + result = generate(solver_input, {"time_limit": 5}, lambda _message: None, threading.Event()) + elapsed = perf_counter() - start + assert len(result["template"]) == 8 + assert Counter((s["track"], s["subject_id"]) for s in result["sessions"]) == Counter( + {(group, subject): 2 for group in (1, 2) for subject in range(1, 5)} + ) + record_property("elapsed_seconds", elapsed) + assert elapsed < 10 diff --git a/backend/tests/perf/lessons/__init__.py b/backend/tests/perf/lessons/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/perf/lessons/test_streaming.py b/backend/tests/perf/lessons/test_streaming.py new file mode 100644 index 0000000..8a0ecdb --- /dev/null +++ b/backend/tests/perf/lessons/test_streaming.py @@ -0,0 +1,51 @@ +"""Real bounded-memory document reception at multiple transfer sizes.""" + +import hashlib +import tracemalloc +from collections.abc import AsyncIterator, Callable +from pathlib import Path +from time import perf_counter + +import pytest + +from app.core.documents import DocumentSettings +from app.services.document_storage import DocumentStorage + +pytestmark = pytest.mark.perf + + +@pytest.mark.asyncio +@pytest.mark.parametrize("size", [1024 * 1024, 16 * 1024 * 1024]) +async def test_streaming_memory_and_time_budget( + tmp_path: Path, + size: int, + record_property: Callable[[str, object], None], +) -> None: + """Hash every byte while avoiding a Python allocation proportional to the entire upload.""" + chunk = b"x" * (64 * 1024) + expected = hashlib.sha256() + for _ in range(size // len(chunk)): + expected.update(chunk) + + async def stream() -> AsyncIterator[bytes]: + """Yield fixed-size chunks without building the complete payload in memory.""" + for _ in range(size // len(chunk)): + yield chunk + + storage = DocumentStorage(DocumentSettings(root=tmp_path, reserve_bytes=0)) + key = "a" * 32 + tracemalloc.start() + try: + start = perf_counter() + digest = await storage.receive(key, stream(), size) + elapsed = perf_counter() - start + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert digest == expected.hexdigest() + assert storage.path(key, temporary=True).stat().st_size == size + record_property("bytes", size) + record_property("peak_python_bytes", peak) + record_property("elapsed_seconds", elapsed) + assert peak < 8 * 1024 * 1024 + assert elapsed < 15 diff --git a/backend/tests/perf/statistics/__init__.py b/backend/tests/perf/statistics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/perf/statistics/test_calendar_window_budget.py b/backend/tests/perf/statistics/test_calendar_window_budget.py new file mode 100644 index 0000000..7870eb1 --- /dev/null +++ b/backend/tests/perf/statistics/test_calendar_window_budget.py @@ -0,0 +1,23 @@ +"""Measured performance regression budgets with correctness assertions.""" + +from collections.abc import Callable +from datetime import UTC, datetime +from time import perf_counter + +import pytest + +from app.services.statistics import statistics_window + +pytestmark = pytest.mark.perf + + +def test_calendar_window_budget(record_property: Callable[[str, object], None]) -> None: + """Keep repeated timezone-aware window calculations bounded and correct.""" + instant = datetime(2026, 10, 25, 23, 59, tzinfo=UTC) + start = perf_counter() + for _ in range(1000): + _, bins = statistics_window(instant, "month") + assert len(bins) == 30 + elapsed = perf_counter() - start + record_property("elapsed_seconds", elapsed) + assert elapsed < 5 diff --git a/backend/tests/perf/timetable/__init__.py b/backend/tests/perf/timetable/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/perf/timetable/test_annual_occurrences_budget.py b/backend/tests/perf/timetable/test_annual_occurrences_budget.py new file mode 100644 index 0000000..bb791c2 --- /dev/null +++ b/backend/tests/perf/timetable/test_annual_occurrences_budget.py @@ -0,0 +1,27 @@ +"""Measured performance regression budgets with correctness assertions.""" + +from collections.abc import Callable +from time import perf_counter + +import pytest + +from app.schemas.timetable import YearDocument +from app.services.timetable_engine import occurrences +from tests.support.calendar import series, settings + +pytestmark = pytest.mark.perf + + +def test_annual_occurrences_budget(record_property: Callable[[str, object], None]) -> None: + """Expand an annual calendar with many recurring blocks within a broad time budget.""" + document = YearDocument( + settings=settings(end="2027-07-01"), + series=[series(id=f"{i + 1:032x}", lineage=f"{i + 1:032x}") for i in range(100)], + ) + start = perf_counter() + events = occurrences(document) + elapsed = perf_counter() - start + assert len(events) >= 3000 + record_property("elapsed_seconds", elapsed) + record_property("occurrences", len(events)) + assert elapsed < 5 diff --git a/backend/tests/support/__init__.py b/backend/tests/support/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/support/administration.py b/backend/tests/support/administration.py new file mode 100644 index 0000000..53320b6 --- /dev/null +++ b/backend/tests/support/administration.py @@ -0,0 +1,49 @@ +"""Shared synthetic fixtures and helpers; never collected as tests.""" + +import os +from pathlib import Path + +from sqlalchemy import delete + +from app.core.config import DatabaseSettings +from app.core.database import Database +from app.models import ( + Promotion, + PromotionAccountBlock, + UserPromotion, +) +from tests.support.authentication import Harness + + +async def make_promotion(case: Harness, identifier: str = "PTSI") -> int: + """Create a synthetic promotion and return its generated integer identity.""" + case.as_admin() + response = await case.client.post( + "/api/v1/admin/promotions", + json={ + "year": 2019, + "identifier": identifier, + "color": "#123abc", + }, + ) + assert response.status_code == 201, response.text + return response.json()["id"] + + +async def clear_promotions(ids: list[int]) -> None: + """Remove synthetic catalogue rows through the migration role after memberships are gone.""" + database = Database( + DatabaseSettings( + user="sophikron_migrator", + password_file=Path(os.environ["DB_TEST_MIGRATION_PASSWORD_FILE"]), + ) + ) + try: + async with database.sessions.begin() as session: + await session.execute( + delete(PromotionAccountBlock).where(PromotionAccountBlock.promotion_id.in_(ids)) + ) + await session.execute(delete(UserPromotion).where(UserPromotion.promotion_id.in_(ids))) + await session.execute(delete(Promotion).where(Promotion.id.in_(ids))) + finally: + await database.close() diff --git a/backend/tests/support/authentication.py b/backend/tests/support/authentication.py new file mode 100644 index 0000000..ea95df7 --- /dev/null +++ b/backend/tests/support/authentication.py @@ -0,0 +1,238 @@ +"""Shared synthetic fixtures and helpers; never collected as tests.""" + +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +from uuid import uuid4 + +import httpx2 as httpx +import pytest_asyncio +from fastapi import FastAPI +from sqlalchemy import delete, select, update + +from app.core.auth_config import AuthSettings +from app.core.config import DatabaseSettings +from app.core.database import Database +from app.dependencies.auth import AuthenticatedUser, TeacherUser, UserAccount +from app.main import create_app +from app.models import ( + AccountInvitation, + ApplicationState, + User, +) +from app.services.auth import AuthService +from app.services.errors import AuthError +from app.services.mail import MailDeliveryError +from tests.support.cleanup import clear_test_events + +PASSWORD = "IndependentSophikronPassword2026!" + + +SECOND_PASSWORD = "DifferentIndependentPassword2026!" + + +HEADERS = {"Origin": "https://testserver", "X-CSRF-Protection": "1"} + + +class MemoryMailer: + """Capture invitation delivery only inside isolated test memory.""" + + available = True + + def __init__(self) -> None: + """Initialize captured deliveries and an explicit transport failure switch.""" + self.messages: list[tuple[str, str]] = [] + self.fail = False + + async def send_invitation(self, recipient: str, token: str) -> None: + """Capture successful sends or simulate a sanitized transport failure.""" + if self.fail: + raise MailDeliveryError("synthetic transport failure") + self.messages.append((recipient, token)) + + +@dataclass +class Harness: + """Own HTTP clients and only the account records created by this test.""" + + app: FastAPI + database: Database + client: httpx.AsyncClient + mailer: MemoryMailer + prefix: str + ids: list[int] = field(default_factory=list) + administrator: int | None = None + admin_token: str = "" + admin_username: str = "" + emails: dict[str, str] = field(default_factory=dict) + + def as_admin(self) -> None: + """Restore the fixture administrator's browser cookie after a role-specific login.""" + self.client.cookies.clear() + self.client.cookies.set( + self.app.state.auth_settings.cookie_name, + self.admin_token, + domain="testserver.local", + path="/", + ) + + async def create(self, role: str = "user", *, activate: bool = True) -> tuple[int, str]: + """Create and optionally activate a uniquely named account through the real HTTP API.""" + self.as_admin() + username = f"{self.prefix}_{len(self.ids)}" + response = await self.client.post( + "/api/v1/admin/users", + json={ + "first_name": "Exemple", + "last_name": "Fictif", + "email": f"{username}@example.org", + "roles": [role], + }, + ) + assert response.status_code == 201, response.text + email = f"{username}@example.org" + username = response.json()["username"] + self.emails[username] = email + user_id = int(response.json()["id"]) + self.ids.append(user_id) + if activate: + response = await self.client.post(f"/api/v1/admin/users/{user_id}/invite") + assert response.status_code == 204 + token = self.mailer.messages[-1][1] + response = await self.client.post( + "/api/v1/auth/activate", + json={ + "token": token, + "password": PASSWORD, + }, + ) + assert response.status_code == 204 + return user_id, username + + +@pytest_asyncio.fixture +async def auth_case(migrated_database: None, tmp_path: Path) -> AsyncIterator[Harness]: + """Exercise the initial administrator handover before yielding a normal installation.""" + database = Database(DatabaseSettings()) + mailer = MemoryMailer() + prefix = "u" + uuid4().hex[:12] + secret = tmp_path / "bootstrap-password" + secret.write_text(PASSWORD) + settings = AuthSettings(bootstrap_username=prefix + "_setup", bootstrap_password_file=secret) + app = create_app(mailer=mailer, auth_settings=settings) + async with database.sessions.begin() as session: + await session.execute(update(ApplicationState).values(initialized_at=None)) + + @app.get("/api/v1/test/teacher") + async def teacher(user: TeacherUser) -> dict[str, str]: + """Exercise the reusable teacher-only dependency on a protected operation.""" + return {"id": str(user.id)} + + @app.get("/api/v1/test/student") + async def student(user: UserAccount) -> dict[str, str]: + """Exercise the reusable student-only dependency.""" + return {"id": str(user.id)} + + @app.post("/api/v1/test/write") + async def write(user: AuthenticatedUser) -> dict[str, str]: + """Exercise CSRF enforcement inherited by a future cookie-authenticated route.""" + return {"id": str(user.id)} + + case: Harness | None = None + try: + async with app.router.lifespan_context(app): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="https://testserver", + headers=HEADERS, + ) as client: + case = Harness(app, database, client, mailer, prefix) + async with database.sessions() as session: + initial = await session.scalar(select(User).where(User.is_bootstrap)) + case.ids.append(initial.id) + response = await client.post( + "/api/v1/auth/login", + json={ + "identifier": prefix + "_setup", + "password": PASSWORD, + }, + ) + assert response.status_code == 200 + # Bootstrap sessions can only inspect/logout/complete initial setup. + assert ( + await client.post( + "/api/v1/admin/users", + json={ + "first_name": "Exemple", + "last_name": "Fictif", + "email": f"{prefix}_forbidden@example.org", + "roles": ["teacher"], + }, + ) + ).status_code == 403 + case.admin_token = client.cookies.get(app.state.auth_settings.cookie_name) + response = await client.post( + "/api/v1/auth/setup", + json={ + "first_name": "Exemple", + "last_name": "Fictif", + "email": f"{prefix}_1@example.org", + "password": PASSWORD, + }, + ) + assert response.status_code == 201, response.text + case.admin_username = response.json()["username"] + owner = int(response.json()["id"]) + case.ids.append(owner) + case.administrator = owner + assert (await client.get("/api/v1/auth/me")).status_code == 401 + assert ( + await client.post( + "/api/v1/auth/login", + json={ + "identifier": case.admin_username, + "password": PASSWORD, + }, + ) + ).status_code == 200 + case.admin_token = client.cookies.get(app.state.auth_settings.cookie_name) + yield case + finally: + if case and case.ids: + async with database.sessions.begin() as session: + await session.execute( + delete(AccountInvitation).where( + AccountInvitation.user_id.in_(case.ids) + | AccountInvitation.issued_by_user_id.in_(case.ids) + ) + ) + await clear_test_events(case.ids) + await session.execute(delete(User).where(User.id.in_(case.ids))) + await session.execute(update(ApplicationState).values(initialized_at=None)) + await database.close() + + +async def login_status( + case: Harness, + identifier: str, + password: str, + ip: str, + settings: AuthSettings, + now: datetime | None = None, +) -> int: + """Return a service login status using an independent session and optional clock.""" + async with case.database.sessions() as session: + service = AuthService( + session, + settings, + case.app.state.identity_cipher, + case.app.state.passwords, + case.mailer, + clock=(lambda: now) if now is not None else None, + ) + try: + await service.login(identifier, password, ip) + return 200 + except AuthError as error: + return error.status diff --git a/backend/tests/support/calendar.py b/backend/tests/support/calendar.py new file mode 100644 index 0000000..ea592d1 --- /dev/null +++ b/backend/tests/support/calendar.py @@ -0,0 +1,43 @@ +"""Shared synthetic fixtures and helpers; never collected as tests.""" + +from app.schemas.timetable import ( + SeriesData, + YearSettings, +) + + +def settings(**changes: object) -> YearSettings: + """Build a known Monday-to-Friday school term with realistic recess and lunch breaks.""" + return YearSettings.model_validate( + { + "start": "2026-09-07", + "end": "2026-11-06", + "day_start": 28800, + "day_end": 61200, + "session_minutes": 55, + "breaks": [ + {"start": 35400, "end": 36600}, + {"start": 43200, "end": 46800}, + {"start": 53400, "end": 54600}, + ], + **changes, + } + ) + + +def series(**changes: object) -> SeriesData: + """Build one whole-class Monday block spanning four teaching sessions.""" + return SeriesData.model_validate( + { + "id": "a" * 32, + "lineage": "a" * 32, + "starts_on": "2026-09-07", + "start_slot": 0, + "duration_slots": 8, + "subject_id": 1, + "teacher_id": 2, + "room_id": 3, + "interval": 1, + **changes, + } + ) diff --git a/backend/tests/cleanup.py b/backend/tests/support/cleanup.py similarity index 100% rename from backend/tests/cleanup.py rename to backend/tests/support/cleanup.py diff --git a/backend/tests/support/documents.py b/backend/tests/support/documents.py new file mode 100644 index 0000000..6675514 --- /dev/null +++ b/backend/tests/support/documents.py @@ -0,0 +1,64 @@ +"""Shared synthetic fixtures and helpers; never collected as tests.""" + +from collections.abc import AsyncIterator + +import pytest_asyncio +from sqlalchemy import delete + +from app.models.lessons import LessonFile, LessonUpload +from app.services.document_storage import DocumentStorage, cleanup_documents +from tests.support.lessons import CourseHarness + +PAYLOAD = b'print("pedagogical fixture, never executed")\n' + + +@pytest_asyncio.fixture +async def documents(course: CourseHarness) -> AsyncIterator[CourseHarness]: + """Exercise real parsing, disk IO and database operations throughout the document lifecycle.""" + try: + yield course + finally: + async with course.case.database.sessions.begin() as session: + await session.execute( + delete(LessonFile).where(LessonFile.lesson_id.in_(course.course_ids)) + ) + await session.execute( + delete(LessonUpload).where(LessonUpload.lesson_id.in_(course.course_ids)) + ) + await cleanup_documents( + course.case.database, DocumentStorage(course.case.app.state.document_settings) + ) + + +async def reserve(course: CourseHarness, parent: int, **changes: object) -> str: + """Reserve a named Python document using the real authenticated API.""" + response = await course.case.client.post( + course.path + "/uploads", + json={ + "expected_version": course.state["version"], + "parent_id": parent, + "title": "Mon nom pédagogique", + "filename": "original.py", + "size_bytes": len(PAYLOAD), + **changes, + }, + ) + assert response.status_code == 201, response.text + return response.json()["upload_id"] + + +async def upload(course: CourseHarness, parent: int, **changes: object) -> dict: + """Run a real binary upload and retain the new course version.""" + key = await reserve(course, parent, **changes) + response = await course.case.client.put( + course.path + f"/uploads/{key}", + content=PAYLOAD, + headers={"Content-Type": "application/octet-stream"}, + ) + assert response.status_code == 200, response.text + course.state = response.json() + return next( + item + for item in course.state["elements"] + if item["kind"] == "file" and item["title"] == changes.get("title", "Mon nom pédagogique") + ) diff --git a/backend/tests/support/lessons.py b/backend/tests/support/lessons.py new file mode 100644 index 0000000..92496a6 --- /dev/null +++ b/backend/tests/support/lessons.py @@ -0,0 +1,138 @@ +"""Shared synthetic fixtures and helpers; never collected as tests.""" + +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from datetime import date + +import pytest_asyncio +from sqlalchemy import delete + +from app.models.lessons import Lesson +from app.models.site import Subject, TeacherSubject +from tests.support.administration import clear_promotions +from tests.support.authentication import PASSWORD, Harness + + +@dataclass +class CourseHarness: + """Own only synthetic course records and principals for one isolated integration test.""" + + case: Harness + owner_id: int + owner: str + collaborator_id: int + collaborator: str + student_id: int + student: str + state: dict + course_ids: list[int] = field(default_factory=list) + promotion_ids: list[int] = field(default_factory=list) + + @property + def path(self) -> str: + """Return this fixture's course URL.""" + return f"/api/v1/lessons/{self.state['id']}" + + async def login(self, username: str) -> None: + """Switch principals through the real session API.""" + response = await self.case.client.post( + "/api/v1/auth/login", + json={"identifier": username, "password": PASSWORD}, + ) + assert response.status_code == 200, response.text + + async def mutation(self, suffix: str, data: dict, method: str = "post") -> dict: + """Save one revision and keep the returned state for the next authorized mutation.""" + response = await self.case.client.request( + method, + self.path + suffix, + json={"expected_version": self.state["version"], **data}, + ) + assert response.status_code in {200, 201}, response.text + self.state = response.json() + return self.state + + async def promotion(self, *, assign: bool = True) -> int: + """Create an active current-year promotion and optionally assign the fixture student.""" + self.case.as_admin() + today = date.fromisoformat(self.state["today"]) + year = today.year if today.month >= 9 else today.year - 1 + response = await self.case.client.post( + "/api/v1/admin/promotions", + json={ + "year": year, + "identifier": f"COURSE-{self.case.prefix}-{len(self.promotion_ids)}", + "color": "#123ABC", + }, + ) + assert response.status_code == 201, response.text + identifier = response.json()["id"] + self.promotion_ids.append(identifier) + if assign: + assert ( + await self.case.client.put( + f"/api/v1/admin/users/{self.student_id}/promotions/{identifier}", + ) + ).status_code == 204 + await self.login(self.owner) + await self.mutation(f"/promotions/{identifier}", {}, "put") + return identifier + + +@pytest_asyncio.fixture +async def course(auth_case: Harness) -> AsyncIterator[CourseHarness]: + """Create a course with independent owner, collaborator and student accounts.""" + owner_id, owner = await auth_case.create("teacher") + collaborator_id, collaborator = await auth_case.create("teacher") + student_id, student = await auth_case.create("user") + async with auth_case.database.sessions.begin() as session: + subject = Subject( + name=f"Maths {auth_case.prefix}", + name_key=auth_case.prefix, + icon="book", + color="#41754E", + ) + session.add(subject) + await session.flush() + subject_id = subject.id + session.add_all( + [ + TeacherSubject(user_id=identifier, subject_id=subject_id) + for identifier in (owner_id, collaborator_id) + ] + ) + await auth_case.client.post( + "/api/v1/auth/login", + json={"identifier": owner, "password": PASSWORD}, + ) + response = await auth_case.client.post( + "/api/v1/lessons", + json={ + "title": f"Cours {auth_case.prefix}", + "description": "Programme annuel", + "subject_id": subject_id, + }, + ) + assert response.status_code == 201, response.text + fixture = CourseHarness( + auth_case, + owner_id, + owner, + collaborator_id, + collaborator, + student_id, + student, + response.json(), + ) + fixture.course_ids.append(fixture.state["id"]) + try: + yield fixture + finally: + async with auth_case.database.sessions.begin() as session: + await session.execute(delete(Lesson).where(Lesson.id.in_(fixture.course_ids))) + await session.execute( + delete(TeacherSubject).where(TeacherSubject.subject_id == subject_id) + ) + await session.execute(delete(Subject).where(Subject.id == subject_id)) + if fixture.promotion_ids: + await clear_promotions(fixture.promotion_ids) diff --git a/backend/tests/postgres.py b/backend/tests/support/postgres.py similarity index 97% rename from backend/tests/postgres.py rename to backend/tests/support/postgres.py index 357a66b..ce7040d 100644 --- a/backend/tests/postgres.py +++ b/backend/tests/support/postgres.py @@ -26,7 +26,7 @@ def run_alembic(*arguments: str) -> None: environment["DB_PASSWORD_FILE"] = environment["DB_TEST_MIGRATION_PASSWORD_FILE"] result = subprocess.run( [sys.executable, "-m", "alembic", *arguments], - cwd=Path(__file__).resolve().parents[1], + cwd=Path(__file__).resolve().parents[2], env=environment, capture_output=True, text=True, diff --git a/backend/tests/support/solver.py b/backend/tests/support/solver.py new file mode 100644 index 0000000..aad8474 --- /dev/null +++ b/backend/tests/support/solver.py @@ -0,0 +1,55 @@ +"""Shared synthetic scenario fixtures.""" + +from datetime import date, timedelta + +import pytest + + +@pytest.fixture +def solver_input() -> dict: + """Build four teaching weeks and four subjects without any real group or pupil data.""" + weeks = [ + { + "start": (date(2026, 9, 7) + timedelta(weeks=n)).isoformat(), + "end": (date(2026, 9, 11) + timedelta(weeks=n)).isoformat(), + "days": 5, + "eligible": True, + "number": n + 1, + } + for n in range(4) + ] + return { + "base_date": "2026-09-01", + "calendars": [ + { + "id": 1, + "name": "PTSI", + "group_count": 2, + "period_start": "2026-09-07", + "period_end": "2026-10-02", + "weeks": weeks, + "settings": { + "start": "2026-09-07", + "end": "2026-10-02", + "day_start": 28800, + "day_end": 64800, + "session_minutes": 55, + "saturday": False, + "lunch_start": 43200, + "lunch_end": 50400, + "breaks": [], + "holidays": [], + }, + "requirements": [{"subject_id": s, "minutes": 120} for s in range(1, 5)], + } + ], + "bookings": {}, + "availability": { + str(t): [{"weekday": d, "start": 28800, "end": 64800} for d in range(5)] + for t in range(1, 5) + }, + "subjects": [{"id": s, "staff": [{"id": s, "sessions": 2}]} for s in range(1, 5)], + "selected_rooms": {str(s): [1] for s in range(1, 5)}, + "capacities": {"1": 2}, + "preferences": {}, + } diff --git a/backend/tests/support/subscriptions.py b/backend/tests/support/subscriptions.py new file mode 100644 index 0000000..d3ca1be --- /dev/null +++ b/backend/tests/support/subscriptions.py @@ -0,0 +1,31 @@ +"""Shared synthetic scenario fixtures.""" + +from icalendar import Calendar + +from tests.support.authentication import PASSWORD, Harness +from tests.support.timetable import Workspace, workspace # noqa: F401 + + +async def login(case: Harness, name: str) -> None: + """Switch to a real account without bypassing session authentication.""" + case.client.cookies.clear() + response = await case.client.post( + "/api/v1/auth/login", json={"identifier": name, "password": PASSWORD} + ) + assert response.status_code == 200, response.text + + +async def personal(case: Harness) -> dict: + """Read only the current owner's credential via its authenticated endpoint.""" + response = await case.client.get("/api/v1/timetable/subscription") + assert response.status_code == 200, response.text + return response.json() + + +async def feed(case: Harness, token: str) -> list: + """Parse the public ICS route, requiring successful private, nonindexed responses.""" + response = await case.client.get(f"/api/v1/timetable/feed/{token}.ics") + assert response.status_code == 200, response.text + assert "no-store" in response.headers["cache-control"] + assert "noindex" in response.headers["x-robots-tag"] + return Calendar.from_ical(response.content).walk("VEVENT") diff --git a/backend/tests/support/timetable.py b/backend/tests/support/timetable.py new file mode 100644 index 0000000..e45f332 --- /dev/null +++ b/backend/tests/support/timetable.py @@ -0,0 +1,162 @@ +"""Shared synthetic fixtures and helpers; never collected as tests.""" + +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from datetime import date, timedelta + +import pytest_asyncio +from sqlalchemy import delete + +from app.models import ( + TeacherAvailability, + TimetableCalendar, + TimetableSchoolYear, +) +from tests.support.administration import clear_promotions, make_promotion +from tests.support.authentication import PASSWORD, Harness + + +@dataclass +class Workspace: + """Own only this scenario's accounts, promotions and annual calendars.""" + + case: Harness + promotion_id: int + teacher_id: int + teacher_name: str + pupil_id: int + pupil_name: str + school_year: int + settings: dict + calendar_id: int = 0 + calendar_ids: list[int] = field(default_factory=list) + + async def create(self, *, promotion: int | None = None, school_year: int | None = None) -> int: + """Create an independent annual calendar through the actual administrator API.""" + self.case.as_admin() + response = await self.case.client.post( + "/api/v1/timetable/calendars", + json={ + "name": f"{self.case.prefix}-{len(self.calendar_ids)}", + "promotion_id": promotion, + "school_year": school_year or self.school_year, + "settings": self.settings, + "is_paused": True, + }, + ) + assert response.status_code == 201, response.text + identifier = response.json()["id"] + self.calendar_ids.append(identifier) + return identifier + + async def board(self, identifier: int | None = None) -> dict: + """Read the real live board with an administrator session.""" + self.case.as_admin() + response = await self.case.client.get( + "/api/v1/timetable/board", params={"calendar_ids": identifier or self.calendar_id} + ) + assert response.status_code == 200, response.text + return response.json() + + async def add(self, **changes: object) -> dict: + """Save a recurring session and return its refreshed actual annual board.""" + state = await self.board() + year = state["years"][0] + beginning = date.fromisoformat(self.settings["start"]) + beginning += timedelta(days=(-beginning.weekday()) % 7) + response = await self.case.client.post( + f"/api/v1/timetable/years/{year['id']}/series", + json={ + "expected_revision": year["revision"], + "confirmed_live": True, + "block": { + "starts_on": beginning.isoformat(), + "start_slot": 0, + "duration_slots": 2, + "teacher_id": self.teacher_id, + "title": "Maths", + "interval": 1, + **changes, + }, + }, + ) + assert response.status_code == 201, response.text + return await self.board() + + async def broadcast(self) -> dict: + """Enable diffusion using the observed calendar revision.""" + state = await self.board() + agenda = state["calendars"][0] + response = await self.case.client.put( + f"/api/v1/timetable/calendars/{self.calendar_id}", + json={ + "name": agenda["name"], + "promotion_id": agenda["promotion_id"], + "is_paused": False, + "expected_revision": agenda["revision"], + "confirmed_live": True, + }, + ) + assert response.status_code == 200, response.text + return await self.board() + + async def login(self, username: str) -> None: + """Switch to a real account session without bypassing permission dependencies.""" + self.case.client.cookies.clear() + response = await self.case.client.post( + "/api/v1/auth/login", json={"identifier": username, "password": PASSWORD} + ) + assert response.status_code == 200, response.text + + +@pytest_asyncio.fixture +async def workspace(auth_case: Harness) -> AsyncIterator[Workspace]: + """Build an isolated roster and clean only explicitly created timetable records.""" + case = auth_case + promotion = await make_promotion(case, "LIVE-TIMETABLE") + teacher, teacher_name = await case.create("teacher") + pupil, pupil_name = await case.create() + school_year = date.today().year - (date.today().month < 9) + case.as_admin() + response = await case.client.post( + f"/api/v1/admin/promotions/{promotion}/users", json={"user_ids": [teacher, pupil]} + ) + assert response.status_code == 204, response.text + response = await case.client.post( + "/api/v1/timetable/school-years", json={"school_year": school_year} + ) + assert response.status_code == 201, response.text + w = Workspace( + case, + promotion, + teacher, + teacher_name, + pupil, + pupil_name, + school_year, + { + "start": f"{school_year}-09-01", + "end": f"{school_year + 1}-08-31", + "session_minutes": 60, + "day_start": 28800, + "day_end": 68400, + "lunch_start": 43200, + "lunch_end": 50400, + "breaks": [], + }, + ) + try: + w.calendar_id = await w.create(promotion=promotion) + yield w + finally: + async with case.database.sessions.begin() as session: + await session.execute( + delete(TimetableCalendar).where(TimetableCalendar.id.in_(w.calendar_ids)) + ) + await session.execute( + delete(TeacherAvailability).where(TeacherAvailability.user_id == teacher) + ) + await session.execute( + delete(TimetableSchoolYear).where(TimetableSchoolYear.school_year == school_year) + ) + await clear_promotions([promotion]) diff --git a/backend/tests/test_statistics.py b/backend/tests/test_statistics.py deleted file mode 100644 index 1576cde..0000000 --- a/backend/tests/test_statistics.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Calendar boundaries, safe storage metering and completed-transfer instrumentation.""" - -import asyncio -from datetime import UTC, datetime -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import AsyncMock -from zoneinfo import ZoneInfo - -import pytest - -from app.api.v1.lesson_documents import download -from app.core.documents import DocumentSettings -from app.services.statistics import folder_usage, statistics_window - - -@pytest.mark.parametrize("day,hours", [("2027-03-28", 23), ("2026-10-25", 25), ("2026-10-26", 24)]) -def test_statistics_paris_calendar_hours(day: str, hours: int) -> None: - """Keep both repeated hours and omit the nonexistent spring hour without shifting days.""" - now = datetime.fromisoformat(day + "T23:59:59").replace(tzinfo=ZoneInfo("Europe/Paris")) - start, bins = statistics_window(now, "day") - assert len(bins) == hours and start == bins[0] - assert len(set(bins)) == hours - assert all(item.astimezone(ZoneInfo("Europe/Paris")).date().isoformat() == day for item in bins) - - -def test_today_does_not_fabricate_zero_activity_in_future_hours() -> None: - """Stop at the current partial hour rather than drawing a drop to zero in the future.""" - now = datetime(2026, 10, 26, 2, 30, tzinfo=ZoneInfo("Europe/Paris")) - _, bins = statistics_window(now, "day") - assert len(bins) == 3 and all(item <= now for item in bins) - - -@pytest.mark.parametrize("period,days", [("week", 7), ("month", 30)]) -def test_statistics_calendar_days(period: str, days: int) -> None: - """Include today and preceding calendar days across daylight-saving transitions.""" - now = datetime(2026, 10, 26, 0, 10, tzinfo=UTC) - start, bins = statistics_window(now, period) - assert start == bins[0] and len(bins) == days - assert bins[-1].astimezone(ZoneInfo("Europe/Paris")).date() == now.date() - assert all(item.astimezone(ZoneInfo("Europe/Paris")).hour == 0 for item in bins) - - -def test_statistics_measure_only_document_folders(tmp_path: Path) -> None: - """Do not confuse whole-filesystem usage, unrelated root files or directories with documents.""" - settings = DocumentSettings(root=tmp_path) - assert folder_usage(settings) == (0, 0) - (tmp_path / "objects").mkdir() - (tmp_path / "temporary").mkdir() - (tmp_path / "objects" / "document").write_bytes(b"12345") - (tmp_path / "objects" / "nested").mkdir() - (tmp_path / "temporary" / "upload").write_bytes(b"123") - (tmp_path / "unrelated").write_bytes(b"do not count") - assert folder_usage(settings) == (5, 3) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("outcome", ["complete", "short", "cancelled", "failed"]) -async def test_only_completed_transfers_are_counted(outcome: str) -> None: - """Never count an interrupted or short stream and always close the document handle.""" - source = AsyncMock() - source.read.side_effect = { - "complete": [b"data", b""], - "short": [b"da", b""], - "cancelled": [b"da", asyncio.CancelledError()], - "failed": [OSError("interrupted")], - }[outcome] - file = SimpleNamespace( - id=2, lesson_id=1, original_name="document.py", media_type="text/plain", size_bytes=4 - ) - service = SimpleNamespace( - download=AsyncMock(return_value=(file, source)), record_download=AsyncMock() - ) - actor = SimpleNamespace(id=3) - response = await download(1, 2, actor, service) - if outcome in {"cancelled", "failed"}: - with pytest.raises(asyncio.CancelledError if outcome == "cancelled" else OSError): - async for _chunk in response.body_iterator: - pass - else: - chunks = [chunk async for chunk in response.body_iterator] - assert b"".join(chunks) == (b"data" if outcome == "complete" else b"da") - assert service.record_download.await_count == int(outcome == "complete") - source.aclose.assert_awaited_once() diff --git a/backend/tests/unit/__init__.py b/backend/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/unit/administration/__init__.py b/backend/tests/unit/administration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_administration.py b/backend/tests/unit/administration/test_administration.py similarity index 83% rename from backend/tests/test_administration.py rename to backend/tests/unit/administration/test_administration.py index 485f95f..873efc1 100644 --- a/backend/tests/test_administration.py +++ b/backend/tests/unit/administration/test_administration.py @@ -21,13 +21,13 @@ @pytest.mark.parametrize( "first,last,prefix", [ - ("Valentin", "BURGAUD", "vburg"), - ("Valentin", "Roy", "vroy"), - ("Valentin", "Rémi", "vremi"), - ("Dionis", "DU SEJOUR", "dduse"), - ("Élodie", "D’Artagnan", "edart"), - ("Anne-Marie", "Le Bœuf", "alebo"), - ("Œdipe", "Ægir", "oaegi"), + ("Exemple", "FICTIF", "efict"), + ("Exemple", "Test", "etest"), + ("Exemple", "Démo", "edemo"), + ("Compte", "DU TEST", "cdute"), + ("Échantillon", "D’Exemple", "edexe"), + ("Alpha-Modele", "Le Bœuf", "alebo"), + ("Œpsilon", "Æchantillon", "oaech"), ], ) def test_username_normalization(first: str, last: str, prefix: str) -> None: @@ -59,14 +59,14 @@ def test_invalid_names(name: str) -> None: def test_allowed_roles(roles: list[str]) -> None: """Keep administrator-only accounts valid without implying teacher permissions.""" data = CreateUserRequest( - first_name="Valentin", last_name="Roy", email="v@example.org", roles=roles + first_name="Exemple", last_name="Test", email="account@example.org", roles=roles ) assert data.roles == roles and data.promotion_ids == [] def test_default_student_role() -> None: """Give new accounts only student access when roles are omitted.""" - data = CreateUserRequest(first_name="Valentin", last_name="Roy", email="v@example.org") + data = CreateUserRequest(first_name="Exemple", last_name="Test", email="account@example.org") assert data.roles == ["user"] @@ -95,9 +95,9 @@ async def test_admin_only_creation_rejects_promotions_before_writes() -> None: """Reject ineligible creation before reserving an ID or inserting any account.""" service = object.__new__(AuthService) data = CreateUserRequest( - first_name="Camille", - last_name="Martin", - email="camille@example.org", + first_name="Compte", + last_name="Specimen", + email="compte@example.org", roles=["admin"], promotion_ids=[1], ) @@ -122,7 +122,7 @@ def test_forbidden_roles(roles: list[str]) -> None: """Refuse incompatible or obsolete role combinations before any account is created.""" with pytest.raises(ValidationError): CreateUserRequest( - first_name="Valentin", last_name="Roy", email="v@example.org", roles=roles + first_name="Exemple", last_name="Test", email="account@example.org", roles=roles ) @@ -139,7 +139,7 @@ def test_strict_creation(extra: dict[str, object]) -> None: """Forbid caller-selected usernames/passwords and invalid membership lists.""" with pytest.raises(ValidationError): CreateUserRequest.model_validate( - dict(first_name="Valentin", last_name="Roy", email="v@example.org", roles=["user"]) + dict(first_name="Exemple", last_name="Test", email="test@example.org", roles=["user"]) | extra ) @@ -154,18 +154,18 @@ def test_promotion_validation() -> None: PromotionUpdate.model_validate(payload) -@pytest.mark.parametrize("query", ["burg", "burgaud val", "valentin burgo", "VALENTIN BURGAUD"]) +@pytest.mark.parametrize("query", ["fict", "fictif exe", "exemple ficto", "EXEMPLE FICTIF"]) def test_fuzzy_relevance(query: str) -> None: """Return the intended person for partial, reversed and misspelled French names.""" - names = [(1, "Valentin", "Burgaud"), (2, "Alice", "Martin"), (3, "Paul", "Durand")] + names = [(1, "Exemple", "Fictif"), (2, "Alpha", "Specimen"), (3, "Profil", "Fictice")] assert rank_names(query, names, 20)[0] == 1 def test_fuzzy_accents_separators_and_order() -> None: """Favor exact names, tolerate accents/separators and bound short-query noise.""" - names = [(1, "Paul", "Rémilly"), (2, "Alice", "Rémi"), (3, "Dionis", "DU SEJOUR")] - assert rank_names("remi", names, 1) == [2] - assert rank_names("dusejour", names, 20)[0] == 3 + names = [(1, "Profil", "Démolly"), (2, "Alpha", "Démo"), (3, "Compte", "DU TEST")] + assert rank_names("demo", names, 1) == [2] + assert rank_names("dutest", names, 20)[0] == 3 assert rank_names("zz", names, 20) == [] assert rank_names("--", names, 20) == [] @@ -206,11 +206,11 @@ async def test_username_collision_retry_and_exhaustion() -> None: service.repo = MagicMock() service.repo.by_lookup = AsyncMock(side_effect=[object(), None]) with patch("app.services.auth.secrets.SystemRandom.shuffle"): - assert await service._generate_username("Valentin", "Roy") == "vroy101" + assert await service._generate_username("Exemple", "Test") == "etest101" assert service.repo.by_lookup.await_count == 2 service.repo.by_lookup = AsyncMock(return_value=object()) with pytest.raises(AuthError) as error: - await service._generate_username("Valentin", "Roy") + await service._generate_username("Exemple", "Test") assert error.value.status == 409 and service.repo.by_lookup.await_count == 900 @@ -235,16 +235,16 @@ def test_name_cache_capacity_expiry_and_invalidation() -> None: cipher = MagicMock() cipher.decrypt.side_effect = lambda user_id, field, value: value.decode() cache = NameSearchCache(max_entries=1, ttl_seconds=60, clock=lambda: now[0]) - candidate = [(1, b"Valentin", b"Burgaud")] - assert cache.prepare(candidate, cipher)[1].last_name == "Burgaud" + candidate = [(1, b"Exemple", b"Fictif")] + assert cache.prepare(candidate, cipher)[1].last_name == "Fictif" cache.prepare(candidate, cipher) assert cipher.decrypt.call_count == 2 - assert cache.prepare([(1, b"Valentin", b"Roy")], cipher)[1].last_name == "Roy" + assert cache.prepare([(1, b"Exemple", b"Test")], cipher)[1].last_name == "Test" assert cipher.decrypt.call_count == 4 now[0] = 61 - cache.prepare([(1, b"Valentin", b"Roy")], cipher) + cache.prepare([(1, b"Exemple", b"Test")], cipher) assert cipher.decrypt.call_count == 6 - assert set(cache.prepare([(2, b"Alice", b"Martin")], cipher)) == {2} + assert set(cache.prepare([(2, b"Alpha", b"Specimen")], cipher)) == {2} cache.prepare(candidate, cipher) assert cipher.decrypt.call_count == 10 # ID 1 was evicted by the one-entry capacity. assert cache.prepare([], cipher) == {} diff --git a/backend/tests/unit/administration/test_commune_route.py b/backend/tests/unit/administration/test_commune_route.py new file mode 100644 index 0000000..b5c5220 --- /dev/null +++ b/backend/tests/unit/administration/test_commune_route.py @@ -0,0 +1,29 @@ +"""Commune lookup authorization before outbound reference-data requests.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from app.api.v1.profiles import communes +from app.services.errors import AuthError + + +@pytest.mark.asyncio +@pytest.mark.parametrize("denied", [False, True]) +async def test_commune_lookup_revalidates_permission_before_network(denied: bool) -> None: + """Strip the public query and avoid any outbound request when the grant is denied.""" + actor = SimpleNamespace(id=7) + auth = SimpleNamespace(db=MagicMock(), _actor=AsyncMock()) + if denied: + auth._actor.side_effect = AuthError(403, "Forbidden") + with patch("app.api.v1.profiles.search_communes", new_callable=AsyncMock) as search: + search.return_value = [] + if denied: + with pytest.raises(AuthError): + await communes(actor, auth, " Paris ") + search.assert_not_awaited() + else: + assert await communes(actor, auth, " Paris ") == [] + search.assert_awaited_once_with("Paris") + auth._actor.assert_awaited_once_with(actor, permission="profiles.manage") diff --git a/backend/tests/test_communes.py b/backend/tests/unit/administration/test_communes.py similarity index 100% rename from backend/tests/test_communes.py rename to backend/tests/unit/administration/test_communes.py diff --git a/backend/tests/unit/administration/test_competency_codes.py b/backend/tests/unit/administration/test_competency_codes.py new file mode 100644 index 0000000..361874a --- /dev/null +++ b/backend/tests/unit/administration/test_competency_codes.py @@ -0,0 +1,43 @@ +"""Automatic competency labels, natural order and modular parent reassignment.""" + +import pytest +from pydantic import ValidationError + +from app.models.curricula import Competency +from app.schemas.curricula import CompetencyFields +from app.services.competency_codes import alphabetic, competency_codes + + +def nodes(count: int) -> list[Competency]: + """Build ordered synthetic competencies without database access.""" + return [Competency(id=i, name=str(i), position=i) for i in range(1, count + 1)] + + +def test_competency_hierarchical_codes() -> None: + """Number roots, children, grandchildren and deeper branches with alternating segments.""" + codes, ordered = competency_codes(nodes(6), [(1, 3), (3, 4), (4, 5), (3, 6)]) + assert codes == {1: "A", 2: "B", 3: "A.1", 4: "A.1.a", 5: "A.1.a.1", 6: "A.1.b"} + assert ordered == [1, 3, 4, 5, 6, 2] + + +def test_competency_shared_node_has_one_code_and_detachment_recomputes_it() -> None: + """Use the first shortest path and reassign a root label after complete detachment.""" + sample = nodes(4) + assert competency_codes(sample, [(1, 3), (2, 3), (3, 4)])[0][3] == "A.1" + assert competency_codes(sample, [(2, 3), (3, 4)])[0][3] == "B.1" + assert competency_codes(sample, [(3, 4)])[0][3] == "C" + assert competency_codes(sample, [(1, 3), (2, 4), (3, 4)])[0][4] == "B.1" + + +def test_competency_codes_continue_after_z_and_sort_numeric_siblings() -> None: + """Keep Z before AA and child 2 before child 10.""" + assert alphabetic(26, uppercase=True) == "Z" + assert alphabetic(27, uppercase=True) == "AA" + codes, ordered = competency_codes(nodes(30), [(1, i) for i in range(2, 31)]) + assert codes[11] == "A.10" and ordered == list(range(1, 31)) + + +def test_competency_manual_codes_are_not_accepted() -> None: + """Prevent direct API clients from overriding generated labels.""" + with pytest.raises(ValidationError): + CompetencyFields(name="Analyser", expected_version=0, code="Z") diff --git a/backend/tests/test_config.py b/backend/tests/unit/administration/test_config.py similarity index 74% rename from backend/tests/test_config.py rename to backend/tests/unit/administration/test_config.py index c6acd82..858f552 100644 --- a/backend/tests/test_config.py +++ b/backend/tests/unit/administration/test_config.py @@ -10,7 +10,8 @@ def test_environment_and_secret( - settings_factory: Callable[..., DatabaseSettings], tmp_path: Path, + settings_factory: Callable[..., DatabaseSettings], + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """Read separate environment variables and preserve special password characters.""" @@ -19,8 +20,11 @@ def test_environment_and_secret( password = " space@:/?#%'\\end " secret.write_bytes((password + "\r\n").encode()) for name, value in { - "DB_HOST": "db", "DB_NAME": "sophikron", "DB_USER": "app", - "DB_PASSWORD_FILE": str(secret), "DB_POOL_SIZE": "3", + "DB_HOST": "db", + "DB_NAME": "sophikron", + "DB_USER": "app", + "DB_PASSWORD_FILE": str(secret), + "DB_POOL_SIZE": "3", }.items(): monkeypatch.setenv(name, value) settings = DatabaseSettings() @@ -34,12 +38,20 @@ def test_environment_and_secret( @pytest.mark.parametrize( "content", - [b"", b" ", b"private-secret\nsecond-line", b"private-secret\0suffix", - b"\xffprivate-secret", b"private-secret" * 400], + [ + b"", + b" ", + b"private-secret\nsecond-line", + b"private-secret\0suffix", + b"\xffprivate-secret", + b"private-secret" * 400, + ], ids=["empty", "whitespace", "multiline", "null-byte", "invalid-encoding", "oversized"], ) def test_invalid_secret( - settings_factory: Callable[..., DatabaseSettings], tmp_path: Path, content: bytes, + settings_factory: Callable[..., DatabaseSettings], + tmp_path: Path, + content: bytes, ) -> None: """Reject empty, multiline, non-UTF-8 and oversized secrets without echoing them.""" secret = tmp_path / "invalid-password" @@ -64,7 +76,9 @@ def test_required_setting( """Require each connection setting independently, without fallback credentials.""" settings = settings_factory() values = { - "host": settings.host, "name": settings.name, "user": settings.user, + "host": settings.host, + "name": settings.name, + "user": settings.user, "password_file": settings.password_file, } del values[field] @@ -78,12 +92,21 @@ def test_required_setting( @pytest.mark.parametrize( ("field", "value"), - [("pool_size", 0), ("max_overflow", -1), ("pool_timeout", 0), - ("pool_timeout", "nan"), ("port", 65536), ("statement_timeout_ms", 0), - ("health_timeout", -1), ("sslmode", "invalid")], + [ + ("pool_size", 0), + ("max_overflow", -1), + ("pool_timeout", 0), + ("pool_timeout", "nan"), + ("port", 65536), + ("statement_timeout_ms", 0), + ("health_timeout", -1), + ("sslmode", "invalid"), + ], ) def test_invalid_settings( - settings_factory: Callable[..., DatabaseSettings], field: str, value: object, + settings_factory: Callable[..., DatabaseSettings], + field: str, + value: object, ) -> None: """Reject invalid limits before opening any network connection.""" with pytest.raises(ValidationError) as error: diff --git a/backend/tests/unit/administration/test_curricula.py b/backend/tests/unit/administration/test_curricula.py new file mode 100644 index 0000000..f3b694f --- /dev/null +++ b/backend/tests/unit/administration/test_curricula.py @@ -0,0 +1,66 @@ +"""Programme input boundaries and modular graph cycle detection.""" + +import pytest +from pydantic import ValidationError + +from app.schemas.administration import PromotionCreate, PromotionSnapshot +from app.schemas.curricula import CompetencyFields, CurriculumFields +from app.services.curricula import validate_parents +from app.services.errors import AuthError + + +@pytest.mark.parametrize("parents", [[1], [2], [3], [1, 4]]) +def test_reject_self_and_descendant_parents(parents: list[int]) -> None: + """Prevent cycles even through multiple levels or shared descendants.""" + with pytest.raises(AuthError, match="cycle"): + validate_parents(1, parents, [(1, 2), (2, 3), (4, 3)]) + + +def test_allow_shared_child_and_detachment() -> None: + """Permit multiple independent parents and complete detachment to a root.""" + validate_parents(3, [1, 2], [(1, 3), (2, 3)]) + validate_parents(3, [], [(1, 3), (2, 3)]) + + +@pytest.mark.parametrize( + "changes", + [ + {"semester": 0}, + {"semester": 5}, + {"parent_ids": [1, 1]}, + {"parent_ids": [-1]}, + {"name": " "}, + {"color": "red"}, + {"expected_version": -1}, + {"comment": "x" * 12001}, + ], +) +def test_competency_input_bounds(changes: dict[str, object]) -> None: + """Reject invalid values before entering a transaction.""" + with pytest.raises(ValidationError): + CompetencyFields.model_validate({"name": "Analyser", "expected_version": 0, **changes}) + + +def test_optional_text_and_semester() -> None: + """Allow simple root competencies without imposing SII's three levels.""" + data = CompetencyFields(name=" Analyser ", expected_version=0, comment=" ") + assert data.name == "Analyser" + assert data.semester is None and data.comment is None + assert data.parent_ids == [] and data.color is None + + +def test_legacy_promotion_snapshot_remains_readable() -> None: + """Keep old journal references readable without accepting old fields in current writes.""" + old = {"year": 2026, "identifier": "PT", "color": "#123456", "track_id": 7} + assert PromotionSnapshot.model_validate(old).track_id == 7 + with pytest.raises(ValidationError): + PromotionCreate.model_validate(old) + + +@pytest.mark.parametrize( + "url", ["javascript:alert(1)", "file:///programme.pdf", "https://a:b@example.org/p.pdf"] +) +def test_source_link_rejects_unsafe_schemes_and_credentials(url: str) -> None: + """Only permit web links without embedded credentials.""" + with pytest.raises(ValidationError): + CurriculumFields(title="Programme", subject_ids=[1], source_url=url) diff --git a/backend/tests/unit/administration/test_curriculum_files.py b/backend/tests/unit/administration/test_curriculum_files.py new file mode 100644 index 0000000..a614647 --- /dev/null +++ b/backend/tests/unit/administration/test_curriculum_files.py @@ -0,0 +1,78 @@ +"""Portable graph validation without filesystem access or code execution.""" + +import json + +import pytest + +from app.schemas.curricula import CompetencyImport +from app.services.curriculum_files import REQUEST_LIMIT, parse_import +from app.services.errors import AuthError + + +def document(nodes: list[dict]) -> dict: + """Wrap local nodes in the supported file format.""" + return {"format": "sophikron.competencies", "version": 1, "subject_name": "SII", "nodes": nodes} + + +def parse(nodes: list[dict]) -> CompetencyImport: + """Exercise the raw file string carried inside the authenticated request.""" + return parse_import( + json.dumps({"expected_version": 0, "document": json.dumps(document(nodes))}).encode() + ) + + +def test_portable_content_remains_inert_and_shared_nodes_remain_unique() -> None: + """Keep teaching text verbatim, including strings that resemble source code.""" + result = parse( + [ + {"id": 1, "name": "A", "knowledge": ""}, + {"id": 2, "name": "B"}, + {"id": 3, "name": "C", "parent_ids": [1, 2]}, + ] + ) + assert result.document.nodes[0].knowledge == "" + assert result.document.nodes[2].parent_ids == [1, 2] + + +@pytest.mark.parametrize( + "nodes", + [ + [{"id": 1, "name": "A", "parent_ids": [1]}], + [{"id": 1, "name": "A", "parent_ids": [2]}, {"id": 2, "name": "B", "parent_ids": [1]}], + [{"id": 1, "name": "A", "parent_ids": [9]}], + [{"id": 1, "name": "A"}, {"id": 1, "name": "B"}], + [{"id": 1, "name": "A", "color": "javascript:alert(1)"}], + [{"id": 1, "name": "A", "semester": 5}], + [{"id": 1, "name": "A", "execute": "dangerous()"}], + [{"id": 1, "name": "A", "parent_ids": [2, 2]}, {"id": 2, "name": "B"}], + [{"id": i, "name": "A", "parent_ids": [i - 1] if i > 1 else []} for i in range(1, 130)], + ], +) +def test_invalid_graphs_fail_without_recursion(nodes: list[dict]) -> None: + """Reject invalid identities, fields, cycles and excessive depth.""" + with pytest.raises(AuthError) as error: + parse(nodes) + assert error.value.status == 422 + + +@pytest.mark.parametrize( + "body", + [ + b'{"expected_version":0,"expected_version":1}', + b'{"__proto__":{}}', + b"not json", + ("[" * 2000 + "]" * 2000).encode(), + json.dumps({"expected_version": 0, "document": '{"format":"a","format":"b"}'}).encode(), + ], +) +def test_bad_json_is_rejected(body: bytes) -> None: + """Bound malformed or ambiguous JSON before model validation.""" + with pytest.raises(AuthError): + parse_import(body) + + +def test_oversized_json_is_rejected() -> None: + """Reject oversized bodies before invoking the JSON parser.""" + with pytest.raises(AuthError) as error: + parse_import(b" " * (REQUEST_LIMIT + 1)) + assert error.value.status == 413 diff --git a/backend/tests/test_groups.py b/backend/tests/unit/administration/test_groups.py similarity index 100% rename from backend/tests/test_groups.py rename to backend/tests/unit/administration/test_groups.py diff --git a/backend/tests/test_main.py b/backend/tests/unit/administration/test_main.py similarity index 91% rename from backend/tests/test_main.py rename to backend/tests/unit/administration/test_main.py index 763a65c..5b2342e 100644 --- a/backend/tests/test_main.py +++ b/backend/tests/unit/administration/test_main.py @@ -34,11 +34,15 @@ def test_health_check(settings_factory: Callable[..., DatabaseSettings]) -> None @pytest.mark.parametrize( "failure", - [OperationalError("SELECT 1", {}, Exception("private connection details")), - OSError("private connection details"), TimeoutError("private connection details")], + [ + OperationalError("SELECT 1", {}, Exception("private connection details")), + OSError("private connection details"), + TimeoutError("private connection details"), + ], ) def test_health_check_database_unavailable( - settings_factory: Callable[..., DatabaseSettings], failure: Exception, + settings_factory: Callable[..., DatabaseSettings], + failure: Exception, caplog: pytest.LogCaptureFixture, ) -> None: """Return an anonymous 503 and recover without restarting the application.""" diff --git a/backend/tests/unit/administration/test_profile_boundaries.py b/backend/tests/unit/administration/test_profile_boundaries.py new file mode 100644 index 0000000..2b91f32 --- /dev/null +++ b/backend/tests/unit/administration/test_profile_boundaries.py @@ -0,0 +1,185 @@ +"""Profile privacy, patch authorization and atomic revision checks.""" + +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from app.schemas.profile import AdminProfileUpdate, OrientationUpdate, SchoolProfile +from app.services.errors import AuthError +from app.services.profiles import ProfileService + + +@pytest.fixture +def profile_service() -> ProfileService: + """Keep the real service and isolate database, identity and presentation boundaries.""" + db = MagicMock() + db.scalars = AsyncMock(return_value=[]) + db.flush = AsyncMock() + db.execute = AsyncMock() + repo = SimpleNamespace( + permissions=AsyncMock(return_value={"profiles.manage"}), + user=AsyncMock(), + roles=AsyncMock(return_value={"user"}), + ) + auth = SimpleNamespace(db=db, repo=repo, _actor=AsyncMock(), _lifecycle_lock=AsyncMock()) + service = ProfileService(auth) + return service + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "field,value", + [ + ("first_name", "Alpha"), + ("last_name", "Specimen"), + ("email", "new@example.org"), + ("orientation_project", "Engineering"), + ("previous_school", "School"), + ("phone", "+33612345678"), + ("birth_date", "2005-01-02"), + ], +) +async def test_private_field_write_is_encrypted_and_audited( + profile_service: ProfileService, + field: str, + value: str, +) -> None: + """Encrypt changes, increment revisions and keep private values out of audit data.""" + service = profile_service + user = SimpleNamespace( + id=2, + profile_version=2, + status="active", + first_name_encrypted=b"old", + last_name_encrypted=b"old", + email_encrypted=b"old", + ) + service.target = AsyncMock(return_value=user) + service.auth.repo.user.return_value = user + service.auth.repo.revoke_invitations = AsyncMock() + service.auth.clock = MagicMock(return_value=datetime(2026, 11, 10, tzinfo=UTC)) + service.auth.cipher = SimpleNamespace( + decrypt=MagicMock(return_value="Old"), + encrypt=MagicMock(return_value=b"encrypted"), + lookup=MagicMock(return_value=b"lookup"), + ) + service.decode = MagicMock(return_value=SchoolProfile()) + service.present = AsyncMock(return_value="saved") + with patch("app.services.profiles.record_event", new_callable=AsyncMock) as event: + result = await service.update( + SimpleNamespace(id=1), 2, AdminProfileUpdate(expected_version=2, **{field: value}) + ) + assert result == "saved" and user.profile_version == 3 + assert getattr(user, field + "_encrypted") == b"encrypted" + assert event.call_args.kwargs["data"] == {"changed_fields": [field]} + if field == "email": + assert user.email_verified_at is None and user.email_lookup == b"lookup" + service.auth.repo.revoke_invitations.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("owner,manager", [(True, False), (False, True), (False, False)]) +async def test_profile_target_uses_current_scope( + profile_service: ProfileService, + owner: bool, + manager: bool, +) -> None: + """Restrict reads to the owner or the caller's current authorized scope.""" + actor = SimpleNamespace(id=1) + user = SimpleNamespace(id=1 if owner else 2, is_bootstrap=False) + profile_service.auth.repo.permissions.return_value = {"profiles.manage"} if manager else set() + profile_service.auth.repo.user.return_value = user + profile_service.db.scalar = AsyncMock(return_value=user) + assert await profile_service.target(actor, 2, owner=owner) is user + if owner or manager: + profile_service.auth.repo.user.assert_awaited_once_with(1 if owner else 2) + else: + profile_service.auth.repo.user.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("user", [None, SimpleNamespace(is_bootstrap=True)]) +async def test_unavailable_profile_is_hidden(profile_service: ProfileService, user: object) -> None: + """Missing and bootstrap profiles return the same public error.""" + profile_service.auth.repo.user.return_value = user + with pytest.raises(AuthError) as error: + await profile_service.target(SimpleNamespace(id=1), 2) + assert error.value.status == 404 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "scenario", ["denied_admin", "denied_orientation", "stale", "unchanged", "orientation"] +) +async def test_profile_patch_checks_before_writes( + profile_service: ProfileService, scenario: str +) -> None: + """Refuse unauthorized or stale changes and leave unchanged patches without audit writes.""" + actor = SimpleNamespace(id=1) + user = SimpleNamespace(id=2, profile_version=2, status="active") + profile_service.target = AsyncMock(return_value=user) + profile_service.auth.repo.user.return_value = user + profile_service.auth.repo.permissions.return_value = ( + set() if scenario.startswith("denied") else {"profiles.manage", "orientation.manage"} + ) + profile_service.decode = MagicMock(return_value=SchoolProfile()) + profile_service.present = AsyncMock(return_value="presented") + orientation = scenario in {"denied_orientation", "orientation"} + data = ( + OrientationUpdate(expected_version=2, orientation_project=None) + if orientation + else AdminProfileUpdate(expected_version=1 if scenario == "stale" else 2) + ) + with patch("app.services.profiles.record_event", new_callable=AsyncMock) as event: + if scenario.startswith("denied") or scenario == "stale": + with pytest.raises(AuthError) as error: + await profile_service.update(actor, 2, data) + assert error.value.status == (409 if scenario == "stale" else 403) + profile_service.db.flush.assert_not_awaited() + profile_service.present.assert_not_awaited() + else: + assert await profile_service.update(actor, 2, data) == "presented" + assert user.profile_version == 2 + event.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "values", + [ + {"city": "Paris"}, + {"city": "Paris", "postal_code": None, "commune_code": "75056"}, + ], +) +async def test_location_patch_is_coherent_before_transaction( + profile_service: ProfileService, + values: dict, +) -> None: + """Reject incomplete location updates without modifying profile data.""" + data = AdminProfileUpdate(expected_version=2, **values) + with pytest.raises(AuthError) as error: + await profile_service.update(SimpleNamespace(id=1), 2, data) + assert error.value.status == 422 + profile_service.auth._lifecycle_lock.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("scenario", ["unchanged", "self_demotion", "unknown_role"]) +async def test_role_replacement_preserves_grants_on_rejection( + profile_service: ProfileService, + scenario: str, +) -> None: + """Avoid writes for identical grants and reject self-demotion or unknown roles.""" + profile_service.auth.repo.roles.return_value = {"admin"} + profile_service.auth.repo.role_records = AsyncMock(return_value=[]) + actor = SimpleNamespace(id=1) + target = SimpleNamespace(id=2 if scenario == "unknown_role" else 1) + if scenario == "unchanged": + assert not await profile_service.replace_roles(actor, target, ["admin"]) + else: + with pytest.raises(AuthError) as error: + await profile_service.replace_roles(actor, target, ["teacher"]) + assert error.value.status == (409 if scenario == "self_demotion" else 422) + profile_service.db.execute.assert_not_awaited() diff --git a/backend/tests/test_releases.py b/backend/tests/unit/administration/test_releases.py similarity index 78% rename from backend/tests/test_releases.py rename to backend/tests/unit/administration/test_releases.py index 957df10..b001dde 100644 --- a/backend/tests/test_releases.py +++ b/backend/tests/unit/administration/test_releases.py @@ -23,22 +23,31 @@ def test_invalid_tags(tag: str) -> None: def test_release_transport(monkeypatch: pytest.MonkeyPatch) -> None: """Derive a trusted release link rather than forwarding arbitrary response URLs.""" + def transport(request: object, timeout: int) -> io.BytesIO: """Return a bounded synthetic public release response.""" assert timeout == 4 - return io.BytesIO(json.dumps({ - "tag_name": "v0.2.0", "draft": False, "prerelease": False, - "html_url": "https://untrusted.invalid", - }).encode()) + return io.BytesIO( + json.dumps( + { + "tag_name": "v0.2.0", + "draft": False, + "prerelease": False, + "html_url": "https://untrusted.invalid", + } + ).encode() + ) monkeypatch.setattr(releases, "urlopen", transport) assert releases.fetch_release() == ( - "0.2.0", "https://github.com/Xharos/sophikron/releases/tag/v0.2.0" + "0.2.0", + "https://github.com/Xharos/sophikron/releases/tag/v0.2.0", ) def test_no_release(monkeypatch: pytest.MonkeyPatch) -> None: """Treat the GitHub no-release response as a successful empty lookup.""" + def transport(*args: object, **kwargs: object) -> None: """Simulate the public repository without a published release.""" raise HTTPError(releases.API_URL, 404, "Not Found", {}, None) @@ -47,8 +56,9 @@ def transport(*args: object, **kwargs: object) -> None: assert releases.fetch_release() is None -@pytest.mark.parametrize("body", [b"x" * 262145, b"{}", b"not json"], - ids=["oversized", "missing-fields", "invalid-json"]) +@pytest.mark.parametrize( + "body", [b"x" * 262145, b"{}", b"not json"], ids=["oversized", "missing-fields", "invalid-json"] +) def test_invalid_response(monkeypatch: pytest.MonkeyPatch, body: bytes) -> None: """Reject oversized or malformed responses without retaining external content.""" monkeypatch.setattr(releases, "urlopen", lambda *a, **kw: io.BytesIO(body)) diff --git a/backend/tests/unit/administration/test_search_cache.py b/backend/tests/unit/administration/test_search_cache.py new file mode 100644 index 0000000..436e193 --- /dev/null +++ b/backend/tests/unit/administration/test_search_cache.py @@ -0,0 +1,92 @@ +"""Identity cache isolation, expiry and deterministic search contracts.""" + +from unittest.mock import Mock + +import pytest + +from app.services.search import NameSearchCache, prepare_name, rank_names, rank_prepared_names + + +def test_prepare_name_preserves_display_and_normalizes_search() -> None: + """Keep original spelling while expanding accents for matching.""" + result = prepare_name("Échantillon", "D'Œuvre") + assert result.first_name == "Échantillon" + assert result.last_name == "D'Œuvre" + assert result.text == "echantillon d oeuvre" + assert "doeuvreechantillon" in result.compact_forms + + +@pytest.mark.parametrize("query", ["", " ", "a", "123"]) +def test_short_search_returns_no_identity(query: str) -> None: + """Do not disclose matches for uninformative normalized queries.""" + assert rank_names(query, [(1, "Alpha", "Specimen")], 20) == [] + + +def test_ranking_is_bounded_and_uses_only_supplied_candidates() -> None: + """Exact matches lead and the caller's authorization scope is preserved.""" + names = [(1, "Alpha", "Specimen"), (2, "Alpho", "Specimen"), (3, "Bravo", "Fictice")] + assert rank_names("Alpha Specimen", names, 1) == [1] + assert rank_names("Alpha Specimen", [], 20) == [] + assert rank_prepared_names("Alpha", {1: prepare_name("Alpha", "Specimen")}, 0) == [] + + +def test_cache_reuses_matching_ciphertext_and_clear_releases_entries() -> None: + """Reuse matching names but decrypt again after explicit shutdown cleanup.""" + cipher = Mock() + cipher.decrypt.side_effect = ["Alpha", "Specimen", "Alpha", "Specimen"] + cache = NameSearchCache() + candidates = [(1, b"first", b"last")] + first = cache.prepare(candidates, cipher) + assert cache.prepare(candidates, cipher) == first + assert cipher.decrypt.call_count == 2 + assert cache.prepare([], cipher) == {} + cache.clear() + assert cache.prepare(candidates, cipher) == first + assert cipher.decrypt.call_count == 4 + + +def test_cache_expires_at_deadline() -> None: + """Expire at the TTL boundary even when ciphertext has not changed.""" + clock = Mock(return_value=0) + cipher = Mock() + cipher.decrypt.side_effect = ["Alpha", "Specimen"] * 2 + cache = NameSearchCache(clock=clock, ttl_seconds=10) + candidates = [(1, b"first", b"last")] + cache.prepare(candidates, cipher) + clock.return_value = 9 + cache.prepare(candidates, cipher) + assert cipher.decrypt.call_count == 2 + clock.return_value = 10 + cache.prepare(candidates, cipher) + assert cipher.decrypt.call_count == 4 + + +def test_cache_revalidates_changed_identity() -> None: + """Never serve a stale display name after the database ciphertext changes.""" + cipher = Mock() + cipher.decrypt.side_effect = ["Alpha", "Specimen", "Alpha", "Fictice"] + cache = NameSearchCache() + cache.prepare([(1, b"a", b"b")], cipher) + assert cache.prepare([(1, b"a", b"c")], cipher)[1].last_name == "Fictice" + + +def test_capacity_evicts_the_least_recent_identity() -> None: + """An evicted entry must be decrypted again rather than retained beyond capacity.""" + cipher = Mock() + cipher.decrypt.side_effect = ["Alpha", "Specimen", "Bravo", "Fictice", "Alpha", "Specimen"] + cache = NameSearchCache(max_entries=1) + cache.prepare([(1, b"a", b"b")], cipher) + cache.prepare([(2, b"c", b"d")], cipher) + cache.prepare([(1, b"a", b"b")], cipher) + assert cipher.decrypt.call_count == 6 + + +def test_decryption_failure_is_not_cached() -> None: + """Propagate corrupted ciphertext errors and allow a subsequent valid lookup.""" + cipher = Mock() + cipher.decrypt.side_effect = ValueError("corrupt") + cache = NameSearchCache() + with pytest.raises(ValueError, match="corrupt"): + cache.prepare([(1, b"a", b"b")], cipher) + cipher.decrypt.side_effect = ["Alpha", "Specimen"] + assert cache.prepare([(1, b"a", b"b")], cipher)[1].first_name == "Alpha" diff --git a/backend/tests/unit/administration/test_site_behaviors.py b/backend/tests/unit/administration/test_site_behaviors.py new file mode 100644 index 0000000..d403409 --- /dev/null +++ b/backend/tests/unit/administration/test_site_behaviors.py @@ -0,0 +1,147 @@ +"""Public configuration and subject mutation behavior, including authorization failures.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from app.schemas.site import SettingsUpdate, SubjectUpdate +from app.services.errors import AuthError +from app.services.site import SiteService + + +@pytest.fixture +def site_service() -> SiteService: + """Provide a transactional session double without replacing the service under test.""" + db = MagicMock() + db.get = AsyncMock() + db.scalar = AsyncMock() + db.scalars = AsyncMock() + db.execute = AsyncMock() + db.flush = AsyncMock() + auth = SimpleNamespace(db=db, _actor=AsyncMock(), _lifecycle_lock=AsyncMock()) + service = SiteService(auth) + service._event = AsyncMock() + return service + + +@pytest.mark.asyncio +@pytest.mark.parametrize("exists", [False, True]) +async def test_public_settings_whitelist(site_service: SiteService, exists: bool) -> None: + """Publish presentation fields only, with defaults when no row exists.""" + site_service.db.get.return_value = ( + SimpleNamespace( + name="School", home_text="Welcome", text_color="#244BC1", version=2, secret="private" + ) + if exists + else None + ) + result = await site_service.public() + assert result.settings.name == ("School" if exists else "Sophikron") + assert "secret" not in result.model_dump()["settings"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("scenario", ["changed", "unchanged", "stale", "denied"]) +async def test_site_settings_revision_and_audit(site_service: SiteService, scenario: str) -> None: + """Reject stale or unauthorized writes and journal only actual changes without text bodies.""" + row = SimpleNamespace(name="School", home_text="Welcome", text_color="#244BC1", version=2) + site_service.db.get.return_value = row + actor = SimpleNamespace(id=1) + if scenario == "denied": + site_service.auth._actor.side_effect = AuthError(403, "Forbidden") + data = SettingsUpdate( + name="New school" if scenario == "changed" else "School", + home_text="Welcome", + expected_version=1 if scenario == "stale" else 2, + ) + if scenario in {"stale", "denied"}: + with pytest.raises(AuthError) as error: + await site_service.settings_save(actor, data) + assert error.value.status == (409 if scenario == "stale" else 403) + assert row.version == 2 and row.name == "School" + site_service._event.assert_not_awaited() + else: + result = await site_service.settings_save(actor, data) + assert result.version == (3 if scenario == "changed" else 2) + if scenario == "changed": + facts = site_service._event.call_args.args[-1] + assert facts == { + "changed_fields": ["name"], + "previous_name": "School", + "name": "New school", + } + else: + site_service._event.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("state", ["missing", "stale", "archived", "valid"]) +async def test_subject_edit_revisions(site_service: SiteService, state: str) -> None: + """A successful edit changes the canonical key and invalidates dependent course revisions.""" + row = SimpleNamespace( + id=3, + name="Maths", + name_key="maths", + color="#244BC1", + icon="book", + is_active=state != "archived", + version=2, + ) + site_service.db.get.return_value = None if state == "missing" else row + data = SubjectUpdate(name="Physics", expected_version=1 if state == "stale" else 2) + if state != "valid": + with pytest.raises(AuthError) as error: + await site_service.subject_save(SimpleNamespace(id=1), data, 3) + assert error.value.status == (404 if state == "missing" else 409) + site_service.db.execute.assert_not_awaited() + site_service._event.assert_not_awaited() + else: + result = await site_service.subject_save(SimpleNamespace(id=1), data, 3) + assert result.name == "Physics" and result.version == 3 and row.name_key == "physics" + site_service.db.execute.assert_awaited_once() + site_service.db.flush.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("state", ["missing", "stale", "used", "unused"]) +async def test_subject_archival_protects_courses(site_service: SiteService, state: str) -> None: + """Used subjects cannot be archived and unused subjects lose their teaching assignments.""" + row = SimpleNamespace( + id=3, name="Maths", color="#244BC1", icon="book", is_active=True, version=2 + ) + site_service.db.get.return_value = None if state == "missing" else row + site_service.db.scalar.return_value = 9 if state == "used" else None + site_service.db.scalars.return_value = [] + if state != "unused": + with pytest.raises(AuthError) as error: + await site_service.subject_archive( + SimpleNamespace(id=1), 3, 1 if state == "stale" else 2 + ) + assert error.value.status == (404 if state == "missing" else 409) + site_service.db.execute.assert_not_awaited() + else: + await site_service.subject_archive(SimpleNamespace(id=1), 3, 2) + assert not row.is_active and row.version == 3 + assert site_service.db.execute.await_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mine", [False, True]) +async def test_subject_catalogue_scope_and_counts(site_service: SiteService, mine: bool) -> None: + """Teacher catalogues request their own grant and do not expose administrator counts.""" + row = SimpleNamespace( + id=3, name="Maths", icon="book", color="#244BC1", is_active=True, version=2 + ) + rows = MagicMock() + rows.all.return_value = [row] + site_service.db.scalars.return_value = rows + site_service.db.scalar.side_effect = [1] if mine else [1, 4, 6] + actor = SimpleNamespace(id=7) + result = await site_service.subjects(actor, mine=mine, q=" %_\\ ", is_active=None) + item = result["items"][0] + assert result["total"] == 1 + assert (item.teacher_count, item.lesson_count) == ((0, 0) if mine else (4, 6)) + site_service.auth._actor.assert_awaited_once_with( + actor, permission="teacher.access" if mine else "users.manage" + ) diff --git a/backend/tests/unit/auth/__init__.py b/backend/tests/unit/auth/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/unit/auth/test_additional_boundaries.py b/backend/tests/unit/auth/test_additional_boundaries.py new file mode 100644 index 0000000..2b3d644 --- /dev/null +++ b/backend/tests/unit/auth/test_additional_boundaries.py @@ -0,0 +1,53 @@ +"""Explicit role checks, detached identity and disabled delivery contracts.""" + +from types import SimpleNamespace + +import pytest + +from app.core.security_policy import validate_password +from app.dependencies.auth import RequirePermission, RequireRole +from app.services.auth import UserContext +from app.services.errors import AuthError +from app.services.mail import DisabledMailer, MailDeliveryError + + +@pytest.mark.parametrize("permission", ["", "statistics.read"]) +def test_permission_policy_rejects_empty_configuration(permission: str) -> None: + """Require an explicit capability instead of accidentally permitting an empty policy.""" + if not permission: + with pytest.raises(ValueError, match="required"): + RequirePermission(permission) + else: + assert RequirePermission(permission).permission == permission + + +@pytest.mark.parametrize("password", ["Aa1!short", "a" * 129, "ABCDEFGHI1!", "Abcdefgh1é!"]) +def test_password_policy_rejects_invalid_categories(password: str) -> None: + """Invalid lengths, alphabets and missing categories are refused.""" + with pytest.raises(ValueError): + validate_password(password) + + +def test_password_policy_accepts_complete_ascii_password() -> None: + """A bounded password with every required category is accepted.""" + assert validate_password("Abcdefghi1!") is None + + +@pytest.mark.asyncio +async def test_role_policy_returns_principal_or_denies() -> None: + """A role check accepts an explicit match and denies unrelated roles.""" + actor = UserContext(SimpleNamespace(roles=("teacher",)), session_id=1) + assert actor.roles == ("teacher",) + assert await RequireRole("teacher")(actor) is actor + with pytest.raises(AuthError): + await RequireRole("admin")(actor) + + +@pytest.mark.asyncio +async def test_disabled_delivery_fails_without_exposing_credentials() -> None: + """Disabled SMTP must fail explicitly rather than discard an invitation silently.""" + mailer = DisabledMailer() + assert mailer.available is False + with pytest.raises(MailDeliveryError) as error: + await mailer.send_invitation("synthetic@example.org", "synthetic-secret") + assert "synthetic" not in str(error.value) diff --git a/backend/tests/test_auth_security.py b/backend/tests/unit/auth/test_auth_security.py similarity index 100% rename from backend/tests/test_auth_security.py rename to backend/tests/unit/auth/test_auth_security.py diff --git a/backend/tests/test_bff.py b/backend/tests/unit/auth/test_bff.py similarity index 100% rename from backend/tests/test_bff.py rename to backend/tests/unit/auth/test_bff.py diff --git a/backend/tests/test_route_security.py b/backend/tests/unit/auth/test_route_security.py similarity index 100% rename from backend/tests/test_route_security.py rename to backend/tests/unit/auth/test_route_security.py diff --git a/backend/tests/unit/database/__init__.py b/backend/tests/unit/database/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_database.py b/backend/tests/unit/database/test_database.py similarity index 96% rename from backend/tests/test_database.py rename to backend/tests/unit/database/test_database.py index 81735be..ff04403 100644 --- a/backend/tests/test_database.py +++ b/backend/tests/unit/database/test_database.py @@ -13,7 +13,7 @@ from app.core.config import DatabaseSettings from app.core.database import Database, get_db from app.main import create_app -from tests.postgres import run_alembic +from tests.support.postgres import run_alembic @pytest.mark.asyncio @@ -95,7 +95,7 @@ def test_migration_helper_refuses_unsafe_targets( monkeypatch.setenv("DB_INTEGRATION", integration) monkeypatch.setenv("DB_NAME", name) monkeypatch.setenv("DB_USER", user) - with patch("tests.postgres.subprocess.run") as execute: + with patch("tests.support.postgres.subprocess.run") as execute: with pytest.raises(pytest.fail.Exception, match="Integration tests require"): run_alembic("downgrade", "base") execute.assert_not_called() @@ -103,7 +103,7 @@ def test_migration_helper_refuses_unsafe_targets( def test_feature_migration_chain() -> None: """Keep the ordered feature revisions and a single upgrade head.""" - scripts = ScriptDirectory(str(Path(__file__).resolve().parents[1] / "alembic")) + scripts = ScriptDirectory(str(Path(__file__).resolve().parents[3] / "alembic")) expected = [ "0001_authentication", "0002_configuration", @@ -113,6 +113,7 @@ def test_feature_migration_chain() -> None: "0006_promotion_groups", "0007_timetable", "0008_kholloscope", + "0009_curricula", ] revisions = list(reversed(list(scripts.walk_revisions()))) assert [revision.revision for revision in revisions] == expected diff --git a/backend/tests/unit/kholloscope/__init__.py b/backend/tests/unit/kholloscope/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/unit/kholloscope/conftest.py b/backend/tests/unit/kholloscope/conftest.py new file mode 100644 index 0000000..02d3b52 --- /dev/null +++ b/backend/tests/unit/kholloscope/conftest.py @@ -0,0 +1,3 @@ +"""Shared solver input fixture for generation and revision unit tests.""" + +from tests.support.solver import solver_input # noqa: F401 diff --git a/backend/tests/unit/kholloscope/test_assignment_context.py b/backend/tests/unit/kholloscope/test_assignment_context.py new file mode 100644 index 0000000..7d98573 --- /dev/null +++ b/backend/tests/unit/kholloscope/test_assignment_context.py @@ -0,0 +1,34 @@ +"""Pupil assignment contexts retain exact promotion and group boundaries.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from app.services.kholloscope_generation import KholloscopeGenerationService + + +@pytest.mark.asyncio +async def test_assignment_context_maps_only_matching_groups() -> None: + """A pupil in another promotion or group cannot enter the selected audience.""" + service = object.__new__(KholloscopeGenerationService) + service.repo = SimpleNamespace( + calendars=AsyncMock( + return_value=[ + SimpleNamespace(id=10, promotion_id=1), + SimpleNamespace(id=20, promotion_id=2), + ] + ) + ) + service.db = SimpleNamespace( + scalars=AsyncMock( + return_value=[ + SimpleNamespace(promotion_id=1, group_number=1, user_id=100), + SimpleNamespace(promotion_id=1, group_number=2, user_id=101), + SimpleNamespace(promotion_id=2, group_number=1, user_id=102), + ] + ) + ) + result = await service.assignment_context(2026, [{"calendar_id": 10, "group": 1}]) + assert result["pupils"] == {(10, 1): {100}} + assert result["pupil_calendars"] == {100: {10}, 101: {10}, 102: {20}} diff --git a/backend/tests/test_kholle.py b/backend/tests/unit/kholloscope/test_kholle.py similarity index 100% rename from backend/tests/test_kholle.py rename to backend/tests/unit/kholloscope/test_kholle.py diff --git a/backend/tests/test_kholloscope_assignment.py b/backend/tests/unit/kholloscope/test_kholloscope_assignment.py similarity index 99% rename from backend/tests/test_kholloscope_assignment.py rename to backend/tests/unit/kholloscope/test_kholloscope_assignment.py index 7fb511c..0b4e505 100644 --- a/backend/tests/test_kholloscope_assignment.py +++ b/backend/tests/unit/kholloscope/test_kholloscope_assignment.py @@ -15,7 +15,7 @@ from app.services.kholloscope_assignment import remove_kholles, repair_rotation, rotated_sessions from app.services.kholloscope_solver import GenerationError, overlaps from app.services.timetable_engine import occurrences -from tests.test_timetable import series, settings +from tests.support.calendar import series, settings @pytest.mark.asyncio diff --git a/backend/tests/test_kholloscope_generation.py b/backend/tests/unit/kholloscope/test_kholloscope_generation.py similarity index 95% rename from backend/tests/test_kholloscope_generation.py rename to backend/tests/unit/kholloscope/test_kholloscope_generation.py index cab8c8c..c7693bd 100644 --- a/backend/tests/test_kholloscope_generation.py +++ b/backend/tests/unit/kholloscope/test_kholloscope_generation.py @@ -28,7 +28,10 @@ def test_time_distribution_defaults_and_saved_compatibility() -> None: """Supply recommended shares for new jobs and saved jobs without these options.""" assert GenerationRules().time_distribution() == (5, 15, 75, 5) assert GenerationRules.from_saved_options({"time_limit": 900}).time_distribution() == ( - 5, 15, 75, 5 + 5, + 15, + 75, + 5, ) rules = GenerationRules(time_stability_percent=10, time_rotation_percent=70) assert GenerationRules.from_saved_options(rules.model_dump()) == rules @@ -73,56 +76,6 @@ def solve(solver: object, model: object) -> object: assert budgets[:3] == pytest.approx([45, 873 * 15 / 95, 738 * 75 / 80]) -@pytest.fixture -def solver_input() -> dict: - """Build four teaching weeks and four subjects without any real group or pupil data.""" - weeks = [ - { - "start": (date(2026, 9, 7) + timedelta(weeks=n)).isoformat(), - "end": (date(2026, 9, 11) + timedelta(weeks=n)).isoformat(), - "days": 5, - "eligible": True, - "number": n + 1, - } - for n in range(4) - ] - return { - "base_date": "2026-09-01", - "calendars": [ - { - "id": 1, - "name": "PTSI", - "group_count": 2, - "period_start": "2026-09-07", - "period_end": "2026-10-02", - "weeks": weeks, - "settings": { - "start": "2026-09-07", - "end": "2026-10-02", - "day_start": 28800, - "day_end": 64800, - "session_minutes": 55, - "saturday": False, - "lunch_start": 43200, - "lunch_end": 50400, - "breaks": [], - "holidays": [], - }, - "requirements": [{"subject_id": s, "minutes": 120} for s in range(1, 5)], - } - ], - "bookings": {}, - "availability": { - str(t): [{"weekday": d, "start": 28800, "end": 64800} for d in range(5)] - for t in range(1, 5) - }, - "subjects": [{"id": s, "staff": [{"id": s, "sessions": 2}]} for s in range(1, 5)], - "selected_rooms": {str(s): [1] for s in range(1, 5)}, - "capacities": {"1": 2}, - "preferences": {}, - } - - def test_exact_template_and_annual_anonymous_volumes(solver_input: dict) -> None: """Cover every abstract group annually and every subject per fortnight, two each week.""" logs = [] @@ -153,10 +106,10 @@ def test_generation_default_budget_and_log_millisecond_boundaries() -> None: assert GenerationRules(time_limit=1800).time_limit == 1800 submitted = datetime(2026, 11, 6, tzinfo=timezone.utc) assert run_log_lines( - "Première ligne\n Deuxième ligne\n\n", + "Pdemoère ligne\n Deuxième ligne\n\n", submitted, at=submitted + timedelta(minutes=2, seconds=3, milliseconds=45), - ) == ["[02:03:045] Première ligne", "[02:03:045] Deuxième ligne"] + ) == ["[02:03:045] Pdemoère ligne", "[02:03:045] Deuxième ligne"] assert run_log_lines("Avant", submitted, at=submitted - timedelta(seconds=1)) == [ "[00:00:000] Avant" ] diff --git a/backend/tests/test_kholloscope_pdf.py b/backend/tests/unit/kholloscope/test_kholloscope_pdf.py similarity index 94% rename from backend/tests/test_kholloscope_pdf.py rename to backend/tests/unit/kholloscope/test_kholloscope_pdf.py index a1621d6..2ff689e 100644 --- a/backend/tests/test_kholloscope_pdf.py +++ b/backend/tests/unit/kholloscope/test_kholloscope_pdf.py @@ -22,14 +22,14 @@ def test_two_promotions_export_eight_subject_pages_and_two_rosters() -> None: "name": f"Promotion {c} 2026/2027", "weeks": [{"start": "2026-09-07"}, {"start": "2026-09-14"}], "groups": [ - {"number": c, "students": [{"last_name": f"Élève {c}", "first_name": "Zoé"}]} + {"number": c, "students": [{"last_name": f"Élève {c}", "first_name": "Zêta"}]} ], } for c in (1, 2) ] catalog = { "subjects": [{"id": s, "name": f"Matière {s}", "color": "#244BC1"} for s in range(1, 5)], - "teachers": [{"id": 7, "name": "Émilie Dupont"}], + "teachers": [{"id": 7, "name": "Échantillon Temoin"}], "rooms": [{"id": 8, "name": "B208"}], } sessions = [ @@ -50,28 +50,28 @@ def test_two_promotions_export_eight_subject_pages_and_two_rosters() -> None: calendars, sessions, catalog, - "Compte Élodie", + "Compte Échantillon", datetime(2026, 11, 5, 13, 45, tzinfo=timezone.utc), ) reader = PdfReader(BytesIO(pdf)) assert len(reader.pages) == 10 - assert reader.metadata.author == "Compte Élodie" + assert reader.metadata.author == "Compte Échantillon" for page in reader.pages: assert page.mediabox.width > page.mediabox.height text = page.extract_text() assert all( value in text for value in ( - "Compte Élodie", + "Compte Échantillon", "05/11/2026", "14:45", ) ) if "COMPOSITION DES GROUPES" in text: - assert "ÉLÈVE" in text and "Zoé" in text and "Groupe" in text + assert "ÉLÈVE" in text and "Zêta" in text and "Groupe" in text else: - assert all(v in text for v in ("Émilie Dupont", "B208", "07/09", "Matière", "*")) - assert "Zoé" not in text + assert all(v in text for v in ("Échantillon Temoin", "B208", "07/09", "Matière", "*")) + assert "Zêta" not in text assert "10 / 10" in reader.pages[-1].extract_text() # A painted group rectangle reaches the full table cell bounds, not an inset badge. subject = reader.pages[1] @@ -199,7 +199,7 @@ async def catalog(_actor: object) -> dict: repo=SimpleNamespace(permissions=permissions), cipher=SimpleNamespace( decrypt=Mock( - side_effect=lambda _uid, field, _data: {"last_name": "Élève", "first_name": "Zoé"}[ + side_effect=lambda _uid, field, _data: {"last_name": "Élève", "first_name": "Zêta"}[ field ] ) @@ -236,7 +236,7 @@ async def catalog(_actor: object) -> dict: exported = await service.pdf(SimpleNamespace(id=9), 2026) pages = PdfReader(BytesIO(exported)).pages assert len(pages) == 2 - assert "ÉLÈVE Zoé" in pages[0].extract_text() + assert "ÉLÈVE Zêta" in pages[0].extract_text() assert "Compte Test" in pages[0].extract_text() assert "Mathématiques" in pages[1].extract_text() assert not active diff --git a/backend/tests/test_kholloscope_revision.py b/backend/tests/unit/kholloscope/test_kholloscope_revision.py similarity index 99% rename from backend/tests/test_kholloscope_revision.py rename to backend/tests/unit/kholloscope/test_kholloscope_revision.py index f38f409..eb106eb 100644 --- a/backend/tests/test_kholloscope_revision.py +++ b/backend/tests/unit/kholloscope/test_kholloscope_revision.py @@ -29,7 +29,7 @@ from app.services.kholloscope_versions import effective_metadata, effective_sessions from app.services.timetable_engine import PARIS, occurrences from app.services.timetable_occupancy import replacement_room_problem -from tests.test_kholloscope_generation import solver_input # noqa: F401 +from tests.support.solver import solver_input # noqa: F401 def test_export_schedule_switches_only_on_effective_dates() -> None: @@ -310,7 +310,7 @@ def test_immediate_room_change_does_not_activate_future_service() -> None: def test_retired_group_removal_preserves_recurring_history() -> None: """Cancel only a future occurrence while keeping earlier ICS identities and statistics.""" - from tests.test_timetable import series, settings + from tests.support.calendar import series, settings document = YearDocument(settings=settings(), series=[series(kind="kholle")]) before = occurrences(document) diff --git a/backend/tests/unit/lessons/__init__.py b/backend/tests/unit/lessons/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_attendance_pdf.py b/backend/tests/unit/lessons/test_attendance_pdf.py similarity index 79% rename from backend/tests/test_attendance_pdf.py rename to backend/tests/unit/lessons/test_attendance_pdf.py index b67f658..212fa3d 100644 --- a/backend/tests/test_attendance_pdf.py +++ b/backend/tests/unit/lessons/test_attendance_pdf.py @@ -26,7 +26,7 @@ def test_group_tables_paginate_with_parallel_headings(variant: str, columns: int AttendanceGroup( f"Groupe {index}", [ - AttendanceStudent(f"Élève-{index}-{pupil:03}", "Jean", archived=pupil == 89) + AttendanceStudent(f"Élève-{index}-{pupil:03}", "Jeu", archived=pupil == 89) for pupil in range(90) ], ) @@ -64,7 +64,7 @@ def test_global_contains_assignments_and_escaped_names() -> None: render_attendance_pdf( "PTSI", "#4361EE", - [AttendanceStudent("", "Jean", assignments=("A", "X", "01"))], + [AttendanceStudent("", "Jeu", assignments=("A", "X", "01"))], "Enseignant", GENERATED, "global", @@ -103,7 +103,7 @@ def render(students: list[AttendanceStudent]) -> PdfReader: "PTSI", "#4361EE", students, - "DUPONT Émilie", + "TEMOIN Échantillon", GENERATED, ) ) @@ -112,17 +112,17 @@ def render(students: list[AttendanceStudent]) -> PdfReader: def test_standard_roster_fits_one_a4_page_with_private_generation_details() -> None: """Keep 45 pupils on one A4 page with all requested headings and Paris time.""" - pdf = render([AttendanceStudent(f"Élève {i:02}", "jean-pierre") for i in range(45)]) + pdf = render([AttendanceStudent(f"Élève {i:02}", "jeu-exemple") for i in range(45)]) assert len(pdf.pages) == 1 page = pdf.pages[0] assert float(page.mediabox.width) == pytest.approx(A4[0], abs=0.01) assert float(page.mediabox.height) == pytest.approx(A4[1], abs=0.01) text = page.extract_text() assert "PTSI" in text and "NOM" in text and "Prénom" in text and "Remarque" in text - assert text.count("Jean-Pierre") == 45 + assert text.count("Jeu-Exemple") == 45 assert "ÉLÈVE 00" in text and "ÉLÈVE 44" in text - assert "DUPONT Émilie" in text and "29/10/2026 à 13:34:56" in text - assert pdf.metadata.author == "DUPONT Émilie" + assert "TEMOIN Échantillon" in text and "29/10/2026 à 13:34:56" in text + assert pdf.metadata.author == "TEMOIN Échantillon" operators = page.get_contents().operations # Exact promotion title color and alternating light-grey row backgrounds are drawn. fills = [tuple(float(value) for value in operands) for operands, op in operators if op == b"rg"] @@ -132,10 +132,10 @@ def test_standard_roster_fits_one_a4_page_with_private_generation_details() -> N def test_large_roster_repeats_title_columns_and_footer_on_every_page() -> None: """Paginate without losing pupils or generation metadata.""" - pdf = render([AttendanceStudent(f"Élève {i:03}", "Camille") for i in range(125)]) + pdf = render([AttendanceStudent(f"Élève {i:03}", "Compte") for i in range(125)]) assert len(pdf.pages) >= 3 texts = [page.extract_text() for page in pdf.pages] - assert sum(text.count("Camille") for text in texts) == 125 + assert sum(text.count("Compte") for text in texts) == 125 for text in texts: assert all( value in text @@ -144,7 +144,7 @@ def test_large_roster_repeats_title_columns_and_footer_on_every_page() -> None: "NOM", "Prénom", "Remarque", - "DUPONT Émilie", + "TEMOIN Échantillon", "29/10/2026 à 13:34:56", ) ) @@ -154,24 +154,24 @@ def test_archived_pupils_sort_last_with_struck_through_names_and_safe_markup() - """Sort both sections alphabetically, preserve accents and escape paragraph markup.""" pdf = render( [ - AttendanceStudent("Albert", "élise", archived=True), - AttendanceStudent("Zulu", "marie"), - AttendanceStudent("Éclair", "jean-luc"), - AttendanceStudent("Durand", "léa & zoé"), + AttendanceStudent("Alpha", "échantillon", archived=True), + AttendanceStudent("Zulu", "modele"), + AttendanceStudent("Éclair", "jeu-test"), + AttendanceStudent("Donnee", "démo & zêta"), ] ) page = pdf.pages[0] text = page.extract_text() - assert text.index("DURAND") < text.index("ÉCLAIR") < text.index("ZULU") < text.index("ALBERT") - assert "Élise" in text and "Jean-Luc" in text and "Léa & Zoé" in text + assert text.index("DONNEE") < text.index("ÉCLAIR") < text.index("ZULU") < text.index("ALPHA") + assert "Échantillon" in text and "Jeu-Test" in text and "Démo & Zêta" in text lines = [operands for operands, op in page.get_contents().operations if op == b"l"] # Two additional strokes cross the archived pupil's surname and first name. plain = render( [ - AttendanceStudent("Albert", "élise"), - AttendanceStudent("Zulu", "marie"), - AttendanceStudent("Éclair", "jean-luc"), - AttendanceStudent("Durand", "léa & zoé"), + AttendanceStudent("Alpha", "échantillon"), + AttendanceStudent("Zulu", "modele"), + AttendanceStudent("Éclair", "jeu-test"), + AttendanceStudent("Donnee", "démo & zêta"), ] ) plain_lines = [op for _, op in plain.pages[0].get_contents().operations if op == b"l"] @@ -182,7 +182,7 @@ def test_empty_roster_and_long_names_render_without_overflow() -> None: """Handle empty promotions and wrap long identity fields instead of clipping them.""" assert len(render([]).pages) == 1 last_name = "Trèslongnom" * 10 - first_name = "Marie-" * 15 + first_name = "Modele-" * 15 pdf = render([AttendanceStudent(last_name, first_name)]) text = "".join(pdf.pages[0].extract_text().split()) assert last_name.upper() in text and first_name.title() in text @@ -192,9 +192,9 @@ def test_account_badges_distinguish_active_pending_and_archived_accounts() -> No """Draw one green badge for an active account and red badges for other states.""" pdf = render( [ - AttendanceStudent("Active", "Alice", active=True), - AttendanceStudent("Pending", "Benoît"), - AttendanceStudent("Archived", "Camille", archived=True), + AttendanceStudent("Active", "Alpha", active=True), + AttendanceStudent("Pending", "Bêta"), + AttendanceStudent("Archived", "Compte", archived=True), ] ) fills = [ @@ -217,10 +217,19 @@ def test_global_omits_undefined_partitions_and_colors_only_letter_groups() -> No assert len(set(GROUP_COLORS.values())) == 5 assert "01" not in GROUP_COLORS - pdf = PdfReader(BytesIO(render_attendance_pdf( - "PTSI", "#4361EE", [AttendanceStudent("Nom", "Jean", assignments=("A", "", ""))], - "Enseignant", GENERATED, "global", defined_partitions=["halves"], - ))) + pdf = PdfReader( + BytesIO( + render_attendance_pdf( + "PTSI", + "#4361EE", + [AttendanceStudent("Nom", "Jeu", assignments=("A", "", ""))], + "Enseignant", + GENERATED, + "global", + defined_partitions=["halves"], + ) + ) + ) text = pdf.pages[0].extract_text() assert "Demi" in text and "Tiers" not in text and "Khôlle" not in text assert "Remarque" in text @@ -230,8 +239,10 @@ def test_group_tables_have_gutters_and_no_unused_custom_columns() -> None: """Separate mini tables horizontally and vertically, fitting columns to custom groups.""" from app.services.attendance_pdf import grouped_tables - groups = [AttendanceGroup(f"Groupe {index}", [AttendanceStudent("Nom", "Jean")]) - for index in range(15)] + groups = [ + AttendanceGroup(f"Groupe {index}", [AttendanceStudent("Nom", "Jeu")]) + for index in range(15) + ] story = grouped_tables(groups, 3, 530) assert len(story) == 10 # Five rows, each followed by vertical whitespace. assert story[0]._colWidths[1::2] == [12, 12] diff --git a/backend/tests/test_document_storage.py b/backend/tests/unit/lessons/test_document_storage.py similarity index 100% rename from backend/tests/test_document_storage.py rename to backend/tests/unit/lessons/test_document_storage.py diff --git a/backend/tests/test_lessons.py b/backend/tests/unit/lessons/test_lessons.py similarity index 100% rename from backend/tests/test_lessons.py rename to backend/tests/unit/lessons/test_lessons.py diff --git a/backend/tests/unit/statistics/__init__.py b/backend/tests/unit/statistics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_api_monitoring.py b/backend/tests/unit/statistics/test_api_monitoring.py similarity index 100% rename from backend/tests/test_api_monitoring.py rename to backend/tests/unit/statistics/test_api_monitoring.py diff --git a/backend/tests/unit/statistics/test_background_monitoring.py b/backend/tests/unit/statistics/test_background_monitoring.py new file mode 100644 index 0000000..0b502bc --- /dev/null +++ b/backend/tests/unit/statistics/test_background_monitoring.py @@ -0,0 +1,49 @@ +"""Background task cancellation and aggregate merging without real waiting.""" + +import asyncio +from unittest.mock import AsyncMock, patch + +import pytest + +from app.services.api_monitoring import ApiMonitor, empty_aggregate, merge_aggregate +from app.services.document_storage import document_maintenance + + +def test_merge_preserves_sums_maximum_and_histograms() -> None: + """Combine independent observations without replacing counters or averaging maxima.""" + target, source = empty_aggregate(), empty_aggregate() + target["max_us"], source["max_us"] = 12, 5 + source["statuses"][200] = 3 + source["histogram"][10] = 3 + merge_aggregate(target, source) + assert target["max_us"] == 12 + assert target["statuses"][200] == 3 and target["histogram"][10] == 3 + assert source["statuses"][200] == 3 + + +@pytest.mark.asyncio +async def test_monitor_flushes_before_sleep_and_propagates_cancellation() -> None: + """Cancellation terminates the task after its first flush without an extra iteration.""" + monitor = ApiMonitor() + database = object() + with patch.object(monitor, "flush", new_callable=AsyncMock) as flush: + with patch("app.services.api_monitoring.asyncio.sleep", side_effect=asyncio.CancelledError): + with pytest.raises(asyncio.CancelledError): + await monitor.run(database) + flush.assert_awaited_once_with(database) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", [None, OSError("storage unavailable")]) +async def test_document_worker_retains_retry_after_failure(failure: Exception | None) -> None: + """A cleanup failure still reaches the retry delay; cancellation remains observable.""" + with patch( + "app.services.document_storage.cleanup_documents", new_callable=AsyncMock + ) as cleanup: + cleanup.side_effect = failure + with patch( + "app.services.document_storage.asyncio.sleep", side_effect=asyncio.CancelledError + ): + with pytest.raises(asyncio.CancelledError): + await document_maintenance(None, None) + cleanup.assert_awaited_once_with(None, None) diff --git a/backend/tests/unit/statistics/test_download_tracking.py b/backend/tests/unit/statistics/test_download_tracking.py new file mode 100644 index 0000000..fab841d --- /dev/null +++ b/backend/tests/unit/statistics/test_download_tracking.py @@ -0,0 +1,39 @@ +"""Statistics download tracking contracts.""" + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from app.api.v1.lesson_documents import download + + +@pytest.mark.asyncio +@pytest.mark.parametrize("outcome", ["complete", "short", "cancelled", "failed"]) +async def test_only_completed_transfers_are_counted(outcome: str) -> None: + """Never count an interrupted or short stream and always close the document handle.""" + source = AsyncMock() + source.read.side_effect = { + "complete": [b"data", b""], + "short": [b"da", b""], + "cancelled": [b"da", asyncio.CancelledError()], + "failed": [OSError("interrupted")], + }[outcome] + file = SimpleNamespace( + id=2, lesson_id=1, original_name="document.py", media_type="text/plain", size_bytes=4 + ) + service = SimpleNamespace( + download=AsyncMock(return_value=(file, source)), record_download=AsyncMock() + ) + actor = SimpleNamespace(id=3) + response = await download(1, 2, actor, service) + if outcome in {"cancelled", "failed"}: + with pytest.raises(asyncio.CancelledError if outcome == "cancelled" else OSError): + async for _chunk in response.body_iterator: + pass + else: + chunks = [chunk async for chunk in response.body_iterator] + assert b"".join(chunks) == (b"data" if outcome == "complete" else b"da") + assert service.record_download.await_count == int(outcome == "complete") + source.aclose.assert_awaited_once() diff --git a/backend/tests/unit/statistics/test_series.py b/backend/tests/unit/statistics/test_series.py new file mode 100644 index 0000000..eec645e --- /dev/null +++ b/backend/tests/unit/statistics/test_series.py @@ -0,0 +1,33 @@ +"""Independent bucket counts and period-wide distinct totals.""" + +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +from app.services.statistics import StatisticsService + + +def test_missing_buckets_are_zero_without_summing_distinct_users() -> None: + """Period-wide unique users must not be inferred by summing daily uniques.""" + start = datetime(2026, 9, 1, tzinfo=UTC) + response = SimpleNamespace( + timestamps=[start + timedelta(days=i) for i in range(3)], series={}, totals={} + ) + service = object.__new__(StatisticsService) + service.fill_series( + response, + "downloads", + "users", + [(start, 3, 2), (start + timedelta(days=2), 4, 2)], + 7, + 2, + ) + assert response.series == {"downloads": [3, 0, 4], "users": [2, 0, 2]} + assert response.totals == {"downloads": 7, "users": 2} + + +def test_empty_series_has_zero_totals() -> None: + """An empty data source produces zeros for every requested time bucket.""" + response = SimpleNamespace(timestamps=[datetime(2026, 9, 1, tzinfo=UTC)], series={}, totals={}) + object.__new__(StatisticsService).fill_series(response, "downloads", "users", [], 0, 0) + assert response.series == {"downloads": [0], "users": [0]} + assert response.totals == {"downloads": 0, "users": 0} diff --git a/backend/tests/unit/statistics/test_storage.py b/backend/tests/unit/statistics/test_storage.py new file mode 100644 index 0000000..cc723c4 --- /dev/null +++ b/backend/tests/unit/statistics/test_storage.py @@ -0,0 +1,19 @@ +"""Statistics storage contracts.""" + +from pathlib import Path + +from app.core.documents import DocumentSettings +from app.services.statistics import folder_usage + + +def test_statistics_measure_only_document_folders(tmp_path: Path) -> None: + """Do not confuse whole-filesystem usage, unrelated root files or directories with documents.""" + settings = DocumentSettings(root=tmp_path) + assert folder_usage(settings) == (0, 0) + (tmp_path / "objects").mkdir() + (tmp_path / "temporary").mkdir() + (tmp_path / "objects" / "document").write_bytes(b"12345") + (tmp_path / "objects" / "nested").mkdir() + (tmp_path / "temporary" / "upload").write_bytes(b"123") + (tmp_path / "unrelated").write_bytes(b"do not count") + assert folder_usage(settings) == (5, 3) diff --git a/backend/tests/unit/statistics/test_storage_failures.py b/backend/tests/unit/statistics/test_storage_failures.py new file mode 100644 index 0000000..26a3b85 --- /dev/null +++ b/backend/tests/unit/statistics/test_storage_failures.py @@ -0,0 +1,52 @@ +"""Storage failure contracts without accessing persistent document data.""" + +from pathlib import Path +from unittest.mock import patch + +import pytest + +from app.core.documents import DocumentSettings +from app.services.statistics import folder_usage + + +@pytest.mark.parametrize("folder", ["objects", "temporary"]) +def test_unreadable_folder_reports_unavailable(tmp_path: Path, folder: str) -> None: + """Report unavailable metering rather than a misleading zero on access failure.""" + (tmp_path / folder).mkdir() + with patch("app.services.statistics.os.scandir", side_effect=PermissionError): + assert folder_usage(DocumentSettings(root=tmp_path)) == (None, None) + + +def test_disappearing_file_does_not_break_metering(tmp_path: Path) -> None: + """Ignore files removed between directory enumeration and metadata inspection.""" + from unittest.mock import MagicMock + + (tmp_path / "objects").mkdir() + entry = MagicMock() + entry.stat.side_effect = FileNotFoundError + entries = MagicMock() + entries.__enter__.return_value = [entry] + with patch("app.services.statistics.os.scandir", return_value=entries): + assert folder_usage(DocumentSettings(root=tmp_path)) == (0, 0) + + +def test_symbolic_root_is_not_followed(tmp_path: Path) -> None: + """Reject symbolic document roots before reading their contents.""" + with patch.object(Path, "is_symlink", return_value=True): + assert folder_usage(DocumentSettings(root=tmp_path)) == (None, None) + + +def test_symbolic_managed_folder_is_not_followed(tmp_path: Path) -> None: + """Reject a managed-folder link even when the root itself is regular.""" + with patch.object(Path, "is_symlink", side_effect=[False, True]): + assert folder_usage(DocumentSettings(root=tmp_path)) == (None, None) + + +def test_regular_files_only_are_counted(tmp_path: Path) -> None: + """Exclude subdirectories without recursively scanning unmanaged children.""" + folder = tmp_path / "objects" + folder.mkdir() + (folder / "nested").mkdir() + (folder / "nested" / "ignored").write_bytes(b"x" * 20) + (folder / "empty").touch() + assert folder_usage(DocumentSettings(root=tmp_path)) == (0, 0) diff --git a/backend/tests/unit/statistics/test_windows.py b/backend/tests/unit/statistics/test_windows.py new file mode 100644 index 0000000..8d32e65 --- /dev/null +++ b/backend/tests/unit/statistics/test_windows.py @@ -0,0 +1,35 @@ +"""Statistics windows contracts.""" + +from datetime import UTC, datetime +from zoneinfo import ZoneInfo + +import pytest + +from app.services.statistics import statistics_window + + +@pytest.mark.parametrize("day,hours", [("2027-03-28", 23), ("2026-10-25", 25), ("2026-10-26", 24)]) +def test_statistics_paris_calendar_hours(day: str, hours: int) -> None: + """Keep both repeated hours and omit the nonexistent spring hour without shifting days.""" + now = datetime.fromisoformat(day + "T23:59:59").replace(tzinfo=ZoneInfo("Europe/Paris")) + start, bins = statistics_window(now, "day") + assert len(bins) == hours and start == bins[0] + assert len(set(bins)) == hours + assert all(item.astimezone(ZoneInfo("Europe/Paris")).date().isoformat() == day for item in bins) + + +def test_today_does_not_fabricate_zero_activity_in_future_hours() -> None: + """Stop at the current partial hour rather than drawing a drop to zero in the future.""" + now = datetime(2026, 10, 26, 2, 30, tzinfo=ZoneInfo("Europe/Paris")) + _, bins = statistics_window(now, "day") + assert len(bins) == 3 and all(item <= now for item in bins) + + +@pytest.mark.parametrize("period,days", [("week", 7), ("month", 30)]) +def test_statistics_calendar_days(period: str, days: int) -> None: + """Include today and preceding calendar days across daylight-saving transitions.""" + now = datetime(2026, 10, 26, 0, 10, tzinfo=UTC) + start, bins = statistics_window(now, period) + assert start == bins[0] and len(bins) == days + assert bins[-1].astimezone(ZoneInfo("Europe/Paris")).date() == now.date() + assert all(item.astimezone(ZoneInfo("Europe/Paris")).hour == 0 for item in bins) diff --git a/backend/tests/unit/timetable/__init__.py b/backend/tests/unit/timetable/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/unit/timetable/test_authorization_matrix.py b/backend/tests/unit/timetable/test_authorization_matrix.py new file mode 100644 index 0000000..9921b89 --- /dev/null +++ b/backend/tests/unit/timetable/test_authorization_matrix.py @@ -0,0 +1,74 @@ +"""Live calendar scope and academic revision rejection matrices.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from app.services.errors import AuthError +from app.services.timetable import TimetableService + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "permissions,bootstrap,write,allowed", + [ + ({"users.manage"}, False, True, True), + ({"teaching.read"}, False, False, True), + ({"kholleur.access"}, False, False, True), + ({"teaching.read"}, False, True, False), + (set(), False, False, False), + ({"users.manage"}, True, False, False), + ], +) +async def test_calendar_access_matrix( + permissions: set, bootstrap: bool, write: bool, allowed: bool +) -> None: + """Students and bootstrap accounts never gain calendar access from frontend visibility.""" + service = object.__new__(TimetableService) + service.db = MagicMock() + service.today = MagicMock(return_value="today") + service.auth = SimpleNamespace( + _actor=AsyncMock(return_value=SimpleNamespace(is_bootstrap=bootstrap)), + repo=SimpleNamespace(permissions=AsyncMock(return_value=permissions)), + ) + with patch("app.services.timetable_lifecycle.rollover", new_callable=AsyncMock) as rollover: + if allowed: + assert await service.authorize(SimpleNamespace(id=1), write=write) == ( + "users.manage" in permissions + ) + rollover.assert_awaited_once() + else: + with pytest.raises(AuthError) as error: + await service.authorize(SimpleNamespace(id=1), write=write) + assert error.value.status == 403 + rollover.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "scenario", ["year_missing", "calendar_missing", "archived", "live", "stale", "valid"] +) +async def test_year_lock_rejects_invalid_mutations(scenario: str) -> None: + """Only current revisions on editable, acknowledged calendars may proceed.""" + service = object.__new__(TimetableService) + service.auth = SimpleNamespace(_lifecycle_lock=AsyncMock()) + service.authorize = AsyncMock(return_value=True) + row = SimpleNamespace(calendar_id=3, revision="current") + calendar = SimpleNamespace( + is_archived=scenario == "archived", is_paused=scenario != "live", promotion_id=1 + ) + service.db = SimpleNamespace( + scalar=AsyncMock(return_value=None if scenario == "year_missing" else row), + get=AsyncMock(return_value=None if scenario == "calendar_missing" else calendar), + ) + version = SimpleNamespace( + confirmed_live=False, expected_revision="old" if scenario == "stale" else "current" + ) + if scenario == "valid": + assert await service._year(2, SimpleNamespace(id=1), version) is row + else: + with pytest.raises(AuthError) as error: + await service._year(2, SimpleNamespace(id=1), version) + assert error.value.status == (404 if scenario.endswith("missing") else 409) + service.auth._lifecycle_lock.assert_awaited_once() diff --git a/backend/tests/test_calendar_subscriptions.py b/backend/tests/unit/timetable/test_calendar_subscriptions.py similarity index 96% rename from backend/tests/test_calendar_subscriptions.py rename to backend/tests/unit/timetable/test_calendar_subscriptions.py index 3a9a48b..1869e0e 100644 --- a/backend/tests/test_calendar_subscriptions.py +++ b/backend/tests/unit/timetable/test_calendar_subscriptions.py @@ -34,11 +34,11 @@ def test_export_subject_and_audience_notes(target: str, number: int | None, labe "target_number": number, "audience_label": "Option allemand", "promotion_label": "PTSI", - "teacher": "Camille Martin", + "teacher": "Compte Specimen", } ) assert summary == "TD - MATHÉMATIQUES" - assert notes == f"PTSI — {label}\nCamille Martin" + assert notes == f"PTSI — {label}\nCompte Specimen" def test_export_subjectless_session_without_teacher() -> None: diff --git a/backend/tests/unit/timetable/test_occupied_ranges.py b/backend/tests/unit/timetable/test_occupied_ranges.py new file mode 100644 index 0000000..315c9da --- /dev/null +++ b/backend/tests/unit/timetable/test_occupied_ranges.py @@ -0,0 +1,18 @@ +"""Empty source calendars cannot claim common pupil occupancy.""" + +from unittest.mock import AsyncMock + +import pytest + +from app.services.teacher_availability import TeacherAvailabilityService +from tests.support.calendar import settings + + +@pytest.mark.asyncio +@pytest.mark.parametrize("events", [{}, {1: []}, {1: [], 2: [{"id": "event"}]}]) +async def test_empty_source_has_no_common_occupied_range(events: dict) -> None: + """An empty participating calendar yields no intersection and performs no roster query.""" + service = object.__new__(TeacherAvailabilityService) + service.db = AsyncMock() + assert await service._occupied_ranges(events, {1: 1, 2: 2}, settings()) == [] + service.db.execute.assert_not_awaited() diff --git a/backend/tests/unit/timetable/test_reference_validation.py b/backend/tests/unit/timetable/test_reference_validation.py new file mode 100644 index 0000000..9a36657 --- /dev/null +++ b/backend/tests/unit/timetable/test_reference_validation.py @@ -0,0 +1,111 @@ +"""Server-side reference validation independent of calendar UI restrictions.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from app.models import Promotion, Subject, User +from app.models.timetable import TimetableRoom +from app.schemas.timetable import SessionFields +from app.services.errors import AuthError +from app.services.timetable import TimetableService + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "scenario,expected", + [ + ("valid", None), + ("subject_missing", 422), + ("subject_archived", 422), + ("room_missing", 422), + ("room_archived", 422), + ("teacher_missing", 422), + ("teacher_disabled", 422), + ("teacher_bootstrap", 422), + ("teacher_no_role", 422), + ("kholleur_course", 422), + ("kholleur_kholle", None), + ("promotion_missing", 409), + ("promotion_archived", 409), + ("historical", None), + ("unavailable_override", None), + ], +) +async def test_live_reference_matrix(scenario: str, expected: int | None) -> None: + """Reject unavailable subjects, rooms and teaching identities on the server.""" + subject = SimpleNamespace(is_active=scenario not in {"subject_archived", "historical"}) + room = SimpleNamespace(is_active=scenario != "room_archived") + teacher = SimpleNamespace( + is_bootstrap=scenario == "teacher_bootstrap", + status="disabled" + if scenario in {"teacher_disabled", "historical", "unavailable_override"} + else "active", + ) + promotion = SimpleNamespace(is_active=scenario != "promotion_archived") + objects = {Subject: subject, TimetableRoom: room, User: teacher, Promotion: promotion} + missing = { + "subject_missing": Subject, + "room_missing": TimetableRoom, + "teacher_missing": User, + "promotion_missing": Promotion, + } + if scenario in missing: + objects[missing[scenario]] = None + + async def get(model: type, _identifier: int) -> object: + """Return a typed reference double selected by the real service query.""" + return objects[model] + + roles = ( + set() + if scenario == "teacher_no_role" + else ({"kholleur"} if scenario.startswith("kholleur") else {"teacher"}) + ) + service = object.__new__(TimetableService) + service.db = SimpleNamespace(get=AsyncMock(side_effect=get)) + service.auth = SimpleNamespace(repo=SimpleNamespace(roles=AsyncMock(return_value=roles))) + block = SessionFields( + subject_id=1, + room_id=2, + teacher_id=3, + kind="kholle" if scenario == "kholleur_kholle" else "course", + ) + arguments = { + "historical": scenario == "historical", + "allow_unavailable_teacher": scenario == "unavailable_override", + } + if expected is None: + assert ( + await service._references(block, SimpleNamespace(promotion_id=4), **arguments) is None + ) + else: + with pytest.raises(AuthError) as error: + await service._references(block, SimpleNamespace(promotion_id=4), **arguments) + assert error.value.status == expected + + +@pytest.mark.asyncio +@pytest.mark.parametrize("target", ["student", "custom", "kholles"]) +@pytest.mark.parametrize("member", [False, True]) +async def test_audience_requires_current_membership(target: str, member: bool) -> None: + """Named recipients and groups must still belong to the calendar's current promotion.""" + service = object.__new__(TimetableService) + service.db = SimpleNamespace( + get=AsyncMock(side_effect=[SimpleNamespace(is_active=True), member]), + scalar=AsyncMock(return_value=1 if member else None), + ) + service.auth = SimpleNamespace(repo=SimpleNamespace(roles=AsyncMock())) + block = SessionFields( + title="Study", + target_kind=target, + target_number=1 if target != "student" else None, + target_user_id=1 if target == "student" else None, + ) + if member: + assert await service._references(block, SimpleNamespace(promotion_id=4)) is None + else: + with pytest.raises(AuthError) as error: + await service._references(block, SimpleNamespace(promotion_id=4)) + assert error.value.status == 422 diff --git a/backend/tests/test_teacher_availability.py b/backend/tests/unit/timetable/test_teacher_availability.py similarity index 99% rename from backend/tests/test_teacher_availability.py rename to backend/tests/unit/timetable/test_teacher_availability.py index bfd757e..7bb6f11 100644 --- a/backend/tests/test_teacher_availability.py +++ b/backend/tests/unit/timetable/test_teacher_availability.py @@ -13,7 +13,7 @@ teaching_audience_label, ) from app.services.timetable import TimetableService -from tests.test_timetable import settings +from tests.support.calendar import settings @pytest.mark.parametrize("values", [{}, {"ranges": [{"weekday": 0, "start": 9, "end": 8}]}]) diff --git a/backend/tests/test_timetable.py b/backend/tests/unit/timetable/test_timetable.py similarity index 94% rename from backend/tests/test_timetable.py rename to backend/tests/unit/timetable/test_timetable.py index fe9e33c..0676a9b 100644 --- a/backend/tests/test_timetable.py +++ b/backend/tests/unit/timetable/test_timetable.py @@ -31,6 +31,7 @@ teaching_weeks, validate_series, ) +from tests.support.calendar import series, settings @pytest.mark.asyncio @@ -51,43 +52,6 @@ def test_school_year_changes_at_september_first() -> None: assert current_school_year(date(2027, 1, 1)) == 2026 -def settings(**changes: object) -> YearSettings: - """Build a known Monday-to-Friday school term with realistic recess and lunch breaks.""" - return YearSettings.model_validate( - { - "start": "2026-09-07", - "end": "2026-11-06", - "day_start": 28800, - "day_end": 61200, - "session_minutes": 55, - "breaks": [ - {"start": 35400, "end": 36600}, - {"start": 43200, "end": 46800}, - {"start": 53400, "end": 54600}, - ], - **changes, - } - ) - - -def series(**changes: object) -> SeriesData: - """Build one whole-class Monday block spanning four teaching sessions.""" - return SeriesData.model_validate( - { - "id": "a" * 32, - "lineage": "a" * 32, - "starts_on": "2026-09-07", - "start_slot": 0, - "duration_slots": 8, - "subject_id": 1, - "teacher_id": 2, - "room_id": 3, - "interval": 1, - **changes, - } - ) - - @pytest.mark.asyncio @pytest.mark.parametrize("kind", ["course", "kholle"]) async def test_room_removal_reports_usage_including_exceptions(kind: str) -> None: diff --git a/backend/tests/test_timetable_diagnostics.py b/backend/tests/unit/timetable/test_timetable_diagnostics.py similarity index 98% rename from backend/tests/test_timetable_diagnostics.py rename to backend/tests/unit/timetable/test_timetable_diagnostics.py index 9b7b429..b3d2b04 100644 --- a/backend/tests/test_timetable_diagnostics.py +++ b/backend/tests/unit/timetable/test_timetable_diagnostics.py @@ -7,7 +7,7 @@ from app.schemas.timetable import BlockFields, SeriesFields, YearDocument, YearSettings from app.services.timetable_diagnostics import annual_diagnostics, kholle_diagnostics, largest_gap from app.services.timetable_engine import apply_event_change, occurrences, series_dates -from tests.test_timetable import series, settings +from tests.support.calendar import series, settings def grid(**changes: object) -> YearSettings: @@ -112,14 +112,19 @@ def test_pt_partial_year_accepts_natural_12_or_13_but_not_broken_cycles(phase: i last = first + timedelta(weeks=24, days=4) cfg = grid(end=last.isoformat(), holidays=[], session_minutes=55) requirements = { - "start": first.isoformat(), "end": last.isoformat(), + "start": first.isoformat(), + "end": last.isoformat(), "subjects": [{"subject_id": 1, "minutes": 750}], } audience = [{"promotion_id": 10, "kind": "kholles", "number": 2}] sessions = [ event( - (first + timedelta(weeks=week)).isoformat(), "16:00:00", "16:55:00", - kind="kholle", target_kind="kholles", target_number=2, + (first + timedelta(weeks=week)).isoformat(), + "16:00:00", + "16:55:00", + kind="kholle", + target_kind="kholles", + target_number=2, ) for week in range(phase, 25, 2) ] diff --git a/backend/tests/test_timetable_occupancy.py b/backend/tests/unit/timetable/test_timetable_occupancy.py similarity index 99% rename from backend/tests/test_timetable_occupancy.py rename to backend/tests/unit/timetable/test_timetable_occupancy.py index acf6b4f..ea9aaad 100644 --- a/backend/tests/test_timetable_occupancy.py +++ b/backend/tests/unit/timetable/test_timetable_occupancy.py @@ -6,7 +6,7 @@ from app.services.teacher_availability import effective_ranges from app.services.timetable_engine import PARIS, occurrences from app.services.timetable_occupancy import fully_occupied_ranges, room_capacity_conflicts -from tests.test_timetable import series, settings +from tests.support.calendar import series, settings def event( diff --git a/backend/tests/test_timetable_pdf.py b/backend/tests/unit/timetable/test_timetable_pdf.py similarity index 96% rename from backend/tests/test_timetable_pdf.py rename to backend/tests/unit/timetable/test_timetable_pdf.py index 9fd4b7a..0b2198e 100644 --- a/backend/tests/test_timetable_pdf.py +++ b/backend/tests/unit/timetable/test_timetable_pdf.py @@ -23,7 +23,7 @@ def event(identifier: str, **changes: object) -> dict: "subject_id": 1, "subject_label": "Mathématiques", "title": "Titre", - "teacher": "DUPONT Émilie", + "teacher": "TEMOIN Échantillon", "color": "#4361EE", "target_kind": "promotion", **changes, @@ -32,7 +32,7 @@ def event(identifier: str, **changes: object) -> dict: def test_export_styles_teacher_and_room() -> None: """Embed bold teachers and italic room names while preserving searchable accented text.""" - from tests.test_timetable import settings + from tests.support.calendar import settings data = render_timetable_pdf( "Planning", settings().model_dump(mode="json"), [event("styled", room="B208")] @@ -44,7 +44,7 @@ def test_export_styles_teacher_and_room() -> None: (text, str((font or {}).get("/BaseFont", ""))) ) ) - assert any("DUPONT" in text and "Bold" in font for text, font in fragments) + assert any("TEMOIN" in text and "Bold" in font for text, font in fragments) assert any("B208" in text and "Oblique" in font for text, font in fragments) @@ -144,7 +144,7 @@ def test_landscape_page_contains_labels_breaks_and_no_dates_or_kholles(saturday: settings, [ event("one", target_kind="halves", target_number=1), - event("two", kind="tp", subject_label="Physique", teacher="MARTIN Jean"), + event("two", kind="tp", subject_label="Physique", teacher="SPECIMEN Jeu"), event("kh", kind="kholle", teacher="Excluded"), ], ) @@ -163,8 +163,8 @@ def test_landscape_page_contains_labels_breaks_and_no_dates_or_kholles(saturday: "TD", "TP", "Groupe A", - "DUPONT Émilie", - "MARTIN Jean", + "TEMOIN Échantillon", + "SPECIMEN Jeu", "Pause", "Self", ): diff --git a/backend/tests/unit/timetable/test_year_contracts.py b/backend/tests/unit/timetable/test_year_contracts.py new file mode 100644 index 0000000..89d9ff9 --- /dev/null +++ b/backend/tests/unit/timetable/test_year_contracts.py @@ -0,0 +1,34 @@ +"""Academic-label validation and immutable year catalogue contracts.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from app.services.errors import AuthError +from app.services.timetable import TimetableService +from tests.support.calendar import settings + + +@pytest.mark.parametrize("year", [2025, 2027]) +def test_year_label_rejects_outside_dates(year: int) -> None: + """A valid document cannot be assigned to another academic year.""" + with pytest.raises(AuthError): + TimetableService.validate_year_bounds(year, settings()) + + +def test_year_label_accepts_matching_dates() -> None: + """The selected academic year accepts a valid daily grid within its bounds.""" + assert TimetableService.validate_year_bounds(2026, settings()) is None + + +@pytest.mark.asyncio +async def test_common_years_preserves_usage_and_revision() -> None: + """Do not discard permanent usage markers when exposing the year catalogue.""" + service = object.__new__(TimetableService) + service.db = SimpleNamespace( + scalars=AsyncMock( + return_value=[SimpleNamespace(school_year=2026, used=True, revision="r1")] + ) + ) + assert await service.common_years() == [{"school_year": 2026, "used": True, "revision": "r1"}] diff --git a/backend/tests/unit/tooling/__init__.py b/backend/tests/unit/tooling/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/test_compose.py b/backend/tests/unit/tooling/test_compose.py similarity index 87% rename from backend/tests/test_compose.py rename to backend/tests/unit/tooling/test_compose.py index c9794aa..7c077a3 100644 --- a/backend/tests/test_compose.py +++ b/backend/tests/unit/tooling/test_compose.py @@ -8,7 +8,7 @@ import pytest -ROOT = Path(__file__).resolve().parents[2] +ROOT = Path(__file__).resolve().parents[4] @pytest.mark.skipif(shutil.which("docker") is None, reason="Docker Compose CLI required") @@ -17,7 +17,8 @@ def test_compose_trust_boundary(local: bool, frontend_port: int, tmp_path: Path) -> None: """Keep public ports on loopback and migration credentials out of the runtime service.""" environment = { - key: value for key, value in os.environ.items() + key: value + for key, value in os.environ.items() if not key.startswith(("DB_", "AUTH_", "SOPHIKRON_", "COMPOSE_", "BFF_", "API_")) and key not in {"FRONTEND_PORT", "BACKEND_PORT"} } @@ -33,7 +34,12 @@ def test_compose_trust_boundary(local: bool, frontend_port: int, tmp_path: Path) command.extend(["-f", str(ROOT / "compose.local.yaml")]) result = subprocess.run( [*command, "config", "--format", "json"], - cwd=ROOT, env=environment, capture_output=True, text=True, check=True, timeout=30, + cwd=ROOT, + env=environment, + capture_output=True, + text=True, + check=True, + timeout=30, ) services = json.loads(result.stdout)["services"] for name in ("backend", "frontend", "migrate"): @@ -45,15 +51,15 @@ def test_compose_trust_boundary(local: bool, frontend_port: int, tmp_path: Path) assert service["tmpfs"] == ["/tmp:rw,noexec,nosuid,nodev,size=64m,mode=1777"] for service in services.values(): assert service["logging"] == { - "driver": "json-file", "options": {"max-size": "10m", "max-file": "3"} + "driver": "json-file", + "options": {"max-size": "10m", "max-file": "3"}, } for service in services.values(): for port in service.get("ports", []): assert port["host_ip"] == "127.0.0.1" backend = services["backend"] document_mount = next( - mount for mount in backend["volumes"] - if mount["target"] == "/var/lib/sophikron/documents" + mount for mount in backend["volumes"] if mount["target"] == "/var/lib/sophikron/documents" ) assert document_mount["type"] == "volume" assert document_mount.get("read_only", False) is False diff --git a/backend/tests/test_demo_seed.py b/backend/tests/unit/tooling/test_demo_seed.py similarity index 99% rename from backend/tests/test_demo_seed.py rename to backend/tests/unit/tooling/test_demo_seed.py index 402eb80..e12f78e 100644 --- a/backend/tests/test_demo_seed.py +++ b/backend/tests/unit/tooling/test_demo_seed.py @@ -11,7 +11,7 @@ @pytest.fixture def demo_seed(monkeypatch: pytest.MonkeyPatch) -> ModuleType: """Load the repository's demo entry point with isolated authentication inputs.""" - monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / "script")) + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[4] / "script")) monkeypatch.delenv("SOPHIKRON_SEED_EMAIL", raising=False) monkeypatch.delenv("SOPHIKRON_SEED_PASSWORD", raising=False) module = import_module("seed_demo_data") diff --git a/backend/tests/unit/tooling/test_entrypoints.py b/backend/tests/unit/tooling/test_entrypoints.py new file mode 100644 index 0000000..d68762b --- /dev/null +++ b/backend/tests/unit/tooling/test_entrypoints.py @@ -0,0 +1,52 @@ +"""Administration and validation entry points with synthetic inputs only.""" + +import sys +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest + +from app import cli +from app.services import file_validation + + +@pytest.mark.parametrize("failure", [False, True]) +def test_cli_reports_sanitized_outcome( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + failure: bool, +) -> None: + """Report success or a generic failure without exposing internal exception details.""" + monkeypatch.setattr(sys, "argv", ["cli", "prune-rate-limits"]) + execute = AsyncMock(side_effect=ValueError("private-diagnostic") if failure else None) + monkeypatch.setattr(cli, "execute", execute) + if failure: + with pytest.raises(SystemExit) as error: + cli.main() + assert error.value.code == 1 + else: + cli.main() + execute.assert_awaited_once() + assert "private-diagnostic" not in str(capsys.readouterr()) + + +@pytest.mark.parametrize("valid", [False, True]) +def test_validation_entrypoint_emits_only_mime_or_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + valid: bool, +) -> None: + """Validate real text bytes and reject invalid content without parser diagnostics.""" + path = tmp_path / "sample.py" + path.write_bytes(b"print('hello')\n" if valid else b"\x00") + monkeypatch.setattr(sys, "argv", ["validator", str(path), "py"]) + # Never apply subprocess OS resource limits to the pytest process. + if file_validation.os.name == "posix": + import resource + + monkeypatch.setattr(resource, "setrlimit", lambda *_arguments: None) + assert file_validation.main() == (0 if valid else 1) + output = capsys.readouterr() + assert output.err == "" + assert bool(output.out.strip()) == valid diff --git a/backend/tests/test_run_tests.py b/backend/tests/unit/tooling/test_run_tests.py similarity index 93% rename from backend/tests/test_run_tests.py rename to backend/tests/unit/tooling/test_run_tests.py index 72b13e9..c780c9b 100644 --- a/backend/tests/test_run_tests.py +++ b/backend/tests/unit/tooling/test_run_tests.py @@ -8,6 +8,12 @@ import run_tests +def test_termination_signal_remains_observable() -> None: + """Convert termination into an interrupt so runner cleanup can execute.""" + with pytest.raises(KeyboardInterrupt): + run_tests.interrupted(15, None) + + @pytest.mark.parametrize("pytest_status", [0, 1]) def test_runner_cleans_up_after_pytest( monkeypatch: pytest.MonkeyPatch, diff --git a/backend/tests/verify.py b/backend/tests/verify.py new file mode 100644 index 0000000..b7cb8bc --- /dev/null +++ b/backend/tests/verify.py @@ -0,0 +1,40 @@ +"""Run disposable verification with in-memory coverage, safe on network-mounted workspaces.""" + +import gzip +import shutil +from pathlib import Path + +from coverage import Coverage + +from tests.function_inventory import main as audit_functions + + +def main() -> int: + """Run all selected tests and export portable coverage reports even after test failures. + + Returns + ------- + int + The test runner's status, without suppressing failed application expectations. + """ + coverage = Coverage(data_file=None) + coverage.start() + try: + import run_tests + + result = run_tests.main() + finally: + coverage.stop() + coverage.json_report() + report = Path("reports/coverage.json") + with report.open("rb") as source, gzip.open(report.with_suffix(".json.gz"), "wb") as target: + shutil.copyfileobj(source, target) + report.unlink() + coverage.html_report() + coverage.report() + audit_result = audit_functions(["--strict"]) + return result or audit_result + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/README.md b/docs/README.md index 6aa25b0..dd92ce6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,6 +17,8 @@ Use synthetic data locally; the [demo guide](../script/README.md) describes API- | [Frontend/BFF](frontend-bff.md) | Pages, cookies, same-origin requests, proxy trust and HTTPS deployment | | [Courses and documents](lessons.md) | Content trees, inherited access, private files, quotas, cleanup and backup/restore | | [Timetables](timetable.md) | Audiences, annual settings, publication, diagnostics and ICS | +| [Kholloscope generation](kholloscope-generation.md) | Preparation, private jobs, group assignment and dated publication revisions | +| [Curricula](curricula.md) | Competency graphs, permissions, JSON exchange and undo | | [Statistics](statistics.md) | Pedagogical indicators, storage and API monitoring | | [Architecture decisions](decisions/README.md) | Why schema and deployment boundaries were chosen | diff --git a/docs/administration.md b/docs/administration.md index de392d6..a1b2484 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -16,9 +16,9 @@ Session and invitation credentials remain independent random secrets, never inte ```json { - "first_name": "Valentin", - "last_name": "BURGAUD", - "email": "valentin@example.org", + "first_name": "Exemple", + "last_name": "FICTIF", + "email": "exemple@example.org", "roles": ["user"], "promotion_ids": [1, 2] } @@ -31,8 +31,8 @@ bootstrap account alone may omit names/email and use its explicitly configured u The server generates the username once: normalized first initial + first four normalized family-name letters (or the complete shorter name) + a random suffix from 100 through 999. Accents, apostrophes, -hyphens and spaces disappear; `œ` becomes `oe`, `æ` becomes `ae`. Examples: `vburg103`, `vroy103`, -`vremi103`, `dduse103`. There are 900 suffixes per prefix. Each is tried at most once in random order; +hyphens and spaces disappear; `œ` becomes `oe`, `æ` becomes `ae`. Examples: `efict103`, `etest103`, +`edemo103`, `cdute103`. There are 900 suffixes per prefix. Each is tried at most once in random order; exhaustion returns 409. The lifecycle transaction lock serializes generators across API workers; the unique HMAC index remains the final database uniqueness control. @@ -434,7 +434,7 @@ also applies this revision. No new dependency or external service is required. ## Interactive search -`GET /api/v1/admin/users/search?q=valentin%20burgo&limit=20` requires `users.read`. +`GET /api/v1/admin/users/search?q=exemple%20ficto&limit=20` requires `users.read`. Queries contain 2–100 characters; limit is 1–20. Optional `role`, `status`, `promotion_id` filters restrict candidates before decryption. Results contain `id`, `username`, `first_name`, `last_name`, `status`, without email. Administrator results also include current `roles` and `promotions` @@ -556,6 +556,15 @@ retention purge; define retention before production and use a privileged mainten ## Migrations and verification +Curriculum metadata is managed at `/curricula`, not in a separate dashboard pathway tab. +Promotions accept optional `curriculum_id` and keep their free identifiers and existing calendars. +Administrators manage all curricula; teachers edit competencies only in currently assigned active +subjects; kholleurs read all reference programmes. Competency graphs, generated codes, JSON files +and revision-protected undo are described in [curricula](curricula.md) and +[ADR 0011](decisions/0011-curricula-and-competency-graphs.md). +The `curriculum.changed` journal payload identifies the action, programme, subject, competency, +modified fields, parent/child counts or imported count without copying long teaching text. + See [database migrations](database.md#migrations) for the complete feature history and compatibility rules, and [release verification](../CONTRIBUTING.md#verification-before-a-release) for shared commands. The PostgreSQL integration tests verify diff --git a/docs/authentication.md b/docs/authentication.md index 3d8c422..1ae940d 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -222,7 +222,7 @@ The temporary account can log in, inspect `/auth/me`, log out, and call `POST /a It cannot create/invite ordinary accounts or change passwords. Complete setup with: ```json -{"first_name":"Valentin","last_name":"Burgaud","email":"operator@example.org","password":"ExampleAdminPassword2026!"} +{"first_name":"Exemple","last_name":"Fictif","email":"operator@example.org","password":"ExampleAdminPassword2026!"} ``` Roles cannot be supplied. The service creates an active permanent administrator, sets @@ -413,12 +413,12 @@ with UI labels for first activation, resend/expiry and password reset. The invitation is committed before SMTP; no SQL transaction is held during network IO. A known or uncertain transport failure revokes that link and returns a generic error. A crash can leave an -unsent invitation record: explicit resend safely replaces it. This increment does not promise -transactional email delivery or add an outbox storing plaintext invitation secrets. +unsent invitation record: explicit resend safely replaces it. Delivery is not transactional; +there is no outbox storing plaintext invitation secrets. SMTP links place the token in a URL **fragment**, not a query string, to keep it out of ordinary -access logs. The eventual client activation page must read the fragment and POST it in JSON. That -page is implemented at `/activate` by SvelteKit. Manual delivery never marks email as verified. +access logs. The SvelteKit `/activate` page reads the fragment and submits the token through the BFF. +Manual delivery never marks email as verified. See [invitations and password resets](frontend-bff.md#invitations-and-password-resets). ## Activity and login statistics @@ -462,6 +462,4 @@ Added dependencies: `argon2-cffi` (MIT), `cryptography` (Apache-2.0 OR BSD-3-Cla search. Keep their releases reviewed and maintained; passing these checks is not a comprehensive security assessment. -See the [kholloscope release security review](security-review.md) for the route authentication -inventory, explicit draft capabilities, dependency findings and verification limits. diff --git a/docs/curricula.md b/docs/curricula.md new file mode 100644 index 0000000..9f9f7e6 --- /dev/null +++ b/docs/curricula.md @@ -0,0 +1,169 @@ +# Curricula and competencies + +A curriculum represents one pathway and its current official two-year programme, such as PTSI/PT. +Administrators create it at /curricula, select existing subjects, and supply a title, optional +description and HTTP(S) official PDF URL. The PDF remains external: the server does not fetch it. +There is no separate pathway catalogue or official-edition history. See [ADR 0011](decisions/0011-curricula-and-competency-graphs.md). + +Promotions may reference a curriculum through nullable curriculum_id. Their free names, academic +years and timetable/calendar associations remain independent. Assigning a curriculum is optional. + +## Storage and concurrency + +| Store | Purpose and integrity | +| --- | --- | +| curricula | Title, description, source URL, active state and concurrency version | +| curriculum_subjects | Selected existing subjects; composite curriculum/subject key | +| competencies | One identity with name, optional semester 1-4, knowledge, comment, color and position | +| competency_links | Directed parent/child links; both endpoints constrained to the same curriculum/subject | +| curriculum_undo | Bounded inverse operations keyed by actor and curriculum, with revision and payload | +| promotions.curriculum_id | Optional foreign key; the referenced curriculum cannot be deleted while linked | + +The consolidated migration is 0009_curricula, following 0008_kholloscope. It creates the final schema +directly. There is no tracks table, track_id field or editable competency code column. + +The version field is in active use: writes carry expected_version and return HTTP 409 when another +write has intervened. It is not an official programme edition. Metadata, competencies and imports +advance this curriculum-wide counter. Locks and live authorization checks serialize with account +and subject-assignment changes. A stale graph from another subject must be refreshed before editing. + +The hierarchy is a DAG. Self-links, descendant-as-parent links and cross-subject/curriculum parents +are rejected. A shared competency remains one row and one displayed identity. Deleting a node +removes its edges, retaining all children; children with no remaining parent become roots. Removing +a subject from a curriculum is refused while it contains competencies. Archived subjects/curricula +remain readable but reject graph writes. Optional text is normalized to null when empty. + +Automatic codes follow the first shortest path in sibling position/ID order. Root letters continue +beyond Z to AA; deeper segments alternate numbers and lowercase letters, for example A.1.a.1. +Each identity has one code even with several parents. Codes and display order are recomputed after +reparenting/deletion. Color is explicit or inherited from the canonical branch and subject. + +## Roles and API + +| Capability | Default grants | Effective scope | +| --- | --- | --- | +| curricula.read | admin, teacher, kholleur | All curriculum metadata and subject graphs, including export | +| curricula.edit | teacher | Competencies/import in currently assigned active subjects of active curricula | +| curricula.manage | admin | All metadata and active-subject graph editing/import | + +Students, guests and bootstrap sessions cannot access this feature. Hidden buttons are convenience; +backend services always check current rights. Writes retain the existing session, Origin and CSRF +policy. API paths below are relative to /api/v1 and private responses use no-store caching. + +| Method and path | Operation | +| --- | --- | +| GET /curricula/catalog | Curricula, selected subjects and effective editing flags | +| POST /curricula | Create administrator-owned metadata | +| PUT /curricula/{id} | Update metadata with expected_version | +| GET /curricula/{id}/subjects/{subject_id} | Read a complete subject graph and current revision | +| POST /curricula/{id}/subjects/{subject_id}/nodes | Create a competency and incoming parent links | +| PUT /curricula/{id}/subjects/{subject_id}/nodes/{node_id} | Replace fields and incoming links | +| DELETE /curricula/{id}/subjects/{subject_id}/nodes/{node_id} | Delete only that competency | +| POST /curricula/{id}/undo | Undo the actor's latest eligible operation | +| GET /curricula/{id}/subjects/{subject_id}/export | Downloadable portable subject document | +| POST /curricula/{id}/subjects/{subject_id}/import | Append a validated document atomically | + +The SvelteKit page uses allowlisted POST commands through /curricula/data; file operations use +/curricula/transfer. Services, not routing/UI code, own permissions, graph mutations and transactions. +Metadata and ordinary node writes retain the 16 KiB default request guard. A programme link rejects +credentials and unsupported URL schemes and causes no server-side outbound request. + +## JSON files + +The download modal selects a subject. Its JSON contains all competencies, including collapsed ones, +with names, semesters, knowledge, comments, colors, positions and all parents. The filename is the +subject name plus .json, preserving accents and replacing control/path/reserved filename characters. +Windows device basenames are prefixed with an underscore. The portable format is: + +```json +{"format":"sophikron.competencies","version":1,"subject_name":"SII","nodes":[ + {"id":1,"name":"Analyser","parent_ids":[],"semester":null,"knowledge":null,"comment":null,"color":"#4361EE","position":0}, + {"id":2,"name":"Analyser le besoin","parent_ids":[1],"semester":1,"knowledge":"Associated knowledge","comment":null,"color":null,"position":1} +]} +``` + +The document version describes the file format, independently of the curriculum concurrency version. +File IDs are local references: imports create fresh database IDs. Codes are regenerated, never trusted +from the file. An import adds to the chosen subject, without matching by name or replacing anything. +Importing the same file twice creates duplicate content. The whole batch is transactional and may +be undone as one action. A failed import changes neither nodes, revision nor history. + +The modal reuses the document dropzone for one file, by drag/drop or file selection. The browser +checks extension, announced MIME type, byte size and format before previewing the count. It sends +the original JSON text so the server can detect duplicate keys. Server validation is authoritative: + +- Maximum file size: 4 MiB; maximum subject size: 2,000 nodes including existing ones after import. +- Maximum file graph: 20,000 edges, 100 parents per node and 128 levels; field lengths match node editing. +- Reject unknown fields/format versions, duplicate or prototype-related keys, invalid colors/semesters, + duplicate IDs/parents, missing parents, self-links and cycles. Cycle/depth checks use an iterative queue. +- Parse as JSON only. Never evaluate text or interpolate it as HTML. No uploaded file is written to disk. +- Only the exact backend import route and the BFF transfer route accept 8 MiB + 4 KiB request envelopes, + allowing the original file text to be JSON-escaped. Other JSON routes keep their ordinary limits. + +The import API expects expected_version and document (original JSON string, or an object for API +clients). Unsupported Content-Type is 415, invalid content is 422, oversized requests/exports are +413, and stale edits are 409. Export also refuses graphs beyond the exchange-format limits rather +than returning an unusable document. User-facing errors do not echo uploaded contents. + +## Exploration and editing + +The header links to /curricula only for authorized users. One curriculum is selected at a time. +Subjects retain their existing emblems/colors and can be hidden or isolated. Their graphs are fetched +on page entry so direct-child counts are available before expansion; counts exclude grandchildren. +Metadata and undo controls are icon buttons with accessible labels and tooltips. + +Desktop uses Three.js with HTML labels. Visible depths form concentric rings around each subject; +opening/closing a branch recalculates angles and radii for all open branches. Actual rectangles and +visible descendant demand determine spacing. Hidden descendants reserve no space. Direct segments +connect clipped block borders; particles use the same segments. Shared cross-links can still cross. +Nodes shrink/desaturate slightly with depth, capped after three levels, while borders retain strong +branch color. Long labels are truncated in the graph but remain available in tooltips and dialogs. + +Wheel zooms, dragging the background pans, dragging a node temporarily displaces it. Soft repulsion +and damped springs restore its anchor. Space or Recenter fits final visible anchors during expansion. +Search uses inherited colors and subject names to distinguish identical names; selecting a result +reveals and highlights its ancestor paths/links for ten seconds. Fullscreen toggles its label and +behavior and tracks browser-driven exits. Reduced motion disables drift/particles and background +rendering pauses when hidden or in the outline. GPU resources are released on leaving the graph. + +At widths up to 650 px, only the compact text outline is available and no WebGL context is created. +Returning to desktop recreates the renderer/canvas. The outline lists descendants immediately below +their canonical parent, with indentation and parent-colored borders; shared identities appear once. +Clicking a subject title adds a root competency when permitted; readers see a non-editable title. + +Editing uses one modal. Name is a single-line input and Enter saves. Semester is initially collapsed. +Relations contains parents and display position; Presentation contains only inherited/custom color +with synchronized native picker and HEX field. Add-child/delete actions sit left, cancel/save right, +wrapping on narrow screens. Delete confirmation retains its explicit child-preservation explanation. + +## Undo and journal + +Undo and Ctrl+Z (Cmd+Z on macOS) reverse eligible competency edits from the current page, including +one imported batch. Text fields keep native undo. At most twenty inverse operations per user and +curriculum are retained. Undo restores identities/relations, recalculates codes and rechecks current +subject rights and the exact revision. Any intervening write prevents unsafe reversal. Curriculum +metadata and navigation are outside this undo scope. History is operational recovery, not editions +of the official programme. Journal entries identify action, curriculum, subject, competency, changed +fields, relation counts or imported count without copying long teaching text. + +## Migration compatibility and verification + +Only a fresh database or the supported exact 0008 baseline can apply the consolidated 0009 directly. +Databases using earlier development schemas require an inspected transition, even when their feature rows are +empty. A reused 0009 revision ID can represent a different schema: upgrade head alone +cannot repair the old 0009 schema. Preserve backups and complete the old chain with its original code +before considering a schema-equivalence review and controlled version-table transition. Do not reset +or downgrade a valuable database to bypass this. No automatic transition/stamping is performed. +Downgrading consolidated 0009 to 0008 deletes curriculum data/history and promotion associations; +existing promotions, subjects and calendars survive. Published migrations become immutable. + +Run the complete backend suite with backend/run_tests.py using the configured interpreter and Docker. +It uses the existing isolated Compose runner and synthetic secrets, with migration upgrade/downgrade, +metadata comparison, default grants, retained older rows, DAG constraints, rights, concurrency, codes, +JSON and undo tests. Never point migration tests at a valuable database. + +From frontend/, run npm run check, npm run lint, npm test and npm run build. Browser verification is +node tests/curricula-browser.mjs (set PLAYWRIGHT_CHANNEL=chrome to use installed Chrome). It covers +expansion, zoom/pan, editing, text hierarchy, responsive mobile-only/no-WebGL behavior, fullscreen, +roles, color synchronization, JSON download filename, drag/drop, import and undo against synthetic +HTTP fixtures. Real API/database guarantees are covered separately by PostgreSQL tests. diff --git a/docs/database.md b/docs/database.md index 074f2b1..8a152e0 100644 --- a/docs/database.md +++ b/docs/database.md @@ -256,7 +256,7 @@ Connections use `search_path=pg_catalog`; qualify application tables explicitly Alembic inspects only the application schema and uses a dedicated connection with `NullPool`. Most autonomous IDs are bigint identities; singleton and token-keyed tables have dedicated keys; associations use composite keys. -The release baseline contains eight feature migrations: +The release baseline contains nine feature migrations: | Revision | Schema responsibility | | --- | --- | @@ -267,14 +267,26 @@ The release baseline contains eight feature migrations: | `0005_lessons` | Course content, documents, permissions and statistics | | `0006_promotion_groups` | Standard promotion partitions and pupil group assignments | | `0007_timetable` | Annual calendars, rooms, availability, compact series, custom audiences, archive policy, encrypted revocable ICS links and lifetime ICS usage totals | -| `0008_kholloscope` | Kholle requirements, academic label creation order, subject commitments, preparation workflow, room capacity, durable generation/revision jobs and explicit read/write capabilities; removal of legacy availability hour bounds | +| `0008_kholloscope` | Kholle requirements, academic label creation order, subject commitments, preparation workflow, room capacity, durable generation/revision jobs and explicit read/write capabilities | +| `0009_curricula` | Current multi-subject curricula, subject-scoped competency DAGs, optional promotion association, bounded revision-protected undo and staff read/edit/manage grants | The release-check cache belongs to `0002_configuration`. -The final head is `0008_kholloscope`. It consolidates the unreleased former revisions 0008–0014 -with explicit authorization to rewrite this feature's history. It supports fresh databases and -databases still at `0007_timetable`. An installation stamped with one of the replaced revisions -needs a reviewed transition; deleting application records does not reset its Alembic revision. -Never artificially stamp it to bypass a schema mismatch. +The kholloscope revision `0008_kholloscope` follows `0007_timetable` and adds preparation and +durable generation jobs. The final head is `0009_curricula`. It creates `curricula`, `curriculum_subjects`, +`competencies`, `competency_links` and `curriculum_undo`, plus nullable `promotions.curriculum_id`. +`curricula.version` is the optimistic concurrency counter checked by +metadata edits, competency mutations, imports and undo; `after_version` protects inverse operations. +This is separate from the JSON file format version. Both endpoints of competency links use composite +foreign keys; cycle prevention and current subject rights are enforced transactionally by services. + +Fresh databases and an exact supported 0008 baseline can apply the new head. Databases stamped +with incompatible development schemas need an inspected transition; a reused revision ID does not +prove schema equivalence. An empty feature catalogue does not make those schemas equivalent. +Do not apply a blind stamp or destructive downgrade to resolve the mismatch. A downgrade of +`0009_curricula` removes all curriculum data/undo and promotion associations while +preserving older promotions, subjects and calendars. Tests round-trip this on a disposable database. +See [curriculum contracts and migration compatibility](curricula.md) and +[ADR 0011](decisions/0011-curricula-and-competency-graphs.md). The kholloscope schema uses the following integrity rules: @@ -289,15 +301,14 @@ The kholloscope schema uses the following integrity rules: - Requirements, workflow details and solver payloads remain validated JSONB documents. Real teacher/subject/room references in published events use existing timetable foreign keys. -All application tables have runtime references; retained job snapshots and rollback metadata are -used by stale-source detection, dated revisions and publication rollback. They are not redundant -copies to remove. No speculative JSONB indexes or duplicate event tables are introduced. +Retained job snapshots and rollback metadata support stale-source detection, dated revisions and +publication rollback. Published events remain in the timetable tables. See [ADR 0010](decisions/0010-kholloscope-drafts-and-revisions.md). API monitoring has no foreign keys to pedagogical tables, so it can be created in configuration. ICS usage belongs to the timetable feature. The timetable migration creates the final schema directly, -including nullable availability ranges and encrypted token metadata. The final 0008 schema removes -the old min/max kholle hour bounds in favor of exact subject commitments. +including nullable availability ranges and encrypted token metadata. The cleaned 0007 baseline +omits legacy min/max kholle hour bounds; 0008 adds exact subject commitments. Recurrences and exceptions remain compact JSON documents; shared teachers require no separate table. This baseline is intended for fresh databases (`alembic upgrade head`), not for upgrading databases diff --git a/docs/decisions/0003-backend-authentication.md b/docs/decisions/0003-backend-authentication.md index 8c91481..7be6abf 100644 --- a/docs/decisions/0003-backend-authentication.md +++ b/docs/decisions/0003-backend-authentication.md @@ -8,8 +8,8 @@ ## Decision Use local Argon2id credentials, PostgreSQL-backed opaque cookie sessions, and single-use 48-hour -administrator invitations. The original design exposed seven authentication/account routes under -`/api/v1`; the current API and SvelteKit BFF have since expanded (see the authentication guide). +administrator invitations. See the [authentication guide](../authentication.md) for current API +and SvelteKit BFF contracts. Use reusable FastAPI `Annotated` dependencies for active-account and explicit role requirements; administrators do not implicitly inherit other roles. @@ -33,8 +33,8 @@ Compose gates API startup on database health and a successful one-shot migration service, without granting DDL credentials to the API. Authentication and installation state belong to the initial migration. The release baseline -targets fresh databases; existing incompatible schemas require a separate transition. A guarded -compatibility operation supports the old empty baseline. Never automatically reset stored data. +targets fresh databases; existing incompatible schemas require a separate transition. +Never automatically reset stored data. Published migrations are immutable. The authentication schema includes temporary login leases and nonnegative failure counters. Login quotas are twenty failures per IP and five per IP/supplied @@ -49,5 +49,6 @@ Operators must protect and back up identity keys separately. Exact identity look substring search and plaintext SQL sorting are not. Key/index rotation requires maintenance in this initial implementation. SMTP is optional and replaceable; failed delivery is explicit, without a plaintext-token outbox. Login statistics record successful authentication rather than human presence. -Retention must be selected before collecting production history. MFA, public registration, recovery, -analytics endpoints and a frontend activation page remain separate work. +Retention must be selected before collecting production history. MFA and public registration +are outside this design. Invitations, password reset and activation are documented in the +[authentication guide](../authentication.md). diff --git a/docs/decisions/0004-accounts-promotions-activity.md b/docs/decisions/0004-accounts-promotions-activity.md index 07e9d2d..a16b38c 100644 --- a/docs/decisions/0004-accounts-promotions-activity.md +++ b/docs/decisions/0004-accounts-promotions-activity.md @@ -32,7 +32,7 @@ derive presentation text separately. Preserve the journal through runtime SELECT The current baseline places accounts/authentication/permissions and activity in `0001_authentication`, configuration in `0002_configuration`, and promotions in `0003_promotions`. -[ADR 0005](0005-release-baseline-and-configuration.md) records the seven-revision release baseline +[ADR 0005](0005-release-baseline-and-configuration.md) records the installation baseline and compatibility limits. Future published migrations remain immutable. ## Consequences diff --git a/docs/decisions/0005-release-baseline-and-configuration.md b/docs/decisions/0005-release-baseline-and-configuration.md index cb6de54..b7a6075 100644 --- a/docs/decisions/0005-release-baseline-and-configuration.md +++ b/docs/decisions/0005-release-baseline-and-configuration.md @@ -2,12 +2,11 @@ - **Status:** Accepted - **Date:** 2026-10-30 -- **Sources:** `backend/alembic/versions/0001_authentication.py` through `0007_timetable.py`, - especially `0002_configuration.py`; `app/services/releases.py`. +- **Sources:** [configuration migration](../../backend/alembic/versions/0002_configuration.py), + [release service](../../backend/app/services/releases.py). ## Context and decision -The release baseline contains seven ordered feature revisions, with `0007_timetable` as the only head. Configuration includes the singleton release-check cache. This is a fresh installation baseline, not an upgrade path for any database that used an earlier amended history. Do not use `stamp` to make such a database appear compatible. Published revisions become immutable. @@ -25,7 +24,6 @@ lookup sends no credentials or student data. Outages preserve the last success. `alembic upgrade head` creates the full installation in dependency order. Downgrading configuration removes settings and these measurements/cache; it is not a way to undo only the release check. -Keeping a separate 0008 would preserve the old chain but obscure this pre-release consolidation. The migration-stage integration test checks the cache is absent at 0001 and seeded at 0002; round-trip and metadata checks validate the full PostgreSQL schema. The runtime cannot access Alembic's version table and never receives the migration password. diff --git a/docs/decisions/0006-teaching-catalogues-and-courses.md b/docs/decisions/0006-teaching-catalogues-and-courses.md index 6cd969c..e72beb7 100644 --- a/docs/decisions/0006-teaching-catalogues-and-courses.md +++ b/docs/decisions/0006-teaching-catalogues-and-courses.md @@ -2,7 +2,9 @@ - **Status:** Accepted - **Date:** 2026-10-30 -- **Sources:** `0003_promotions.py`, `0004_subjects.py`, `0005_lessons.py` and their backend services. +- **Sources:** [promotions](../../backend/alembic/versions/0003_promotions.py), + [subjects](../../backend/alembic/versions/0004_subjects.py), + [courses](../../backend/alembic/versions/0005_lessons.py). ## Context and decision diff --git a/docs/decisions/0007-private-course-documents.md b/docs/decisions/0007-private-course-documents.md index be9b096..a6b25b8 100644 --- a/docs/decisions/0007-private-course-documents.md +++ b/docs/decisions/0007-private-course-documents.md @@ -2,8 +2,10 @@ - **Status:** Accepted - **Date:** 2026-10-30 -- **Sources:** `0005_lessons.py`, `app/services/document_storage.py`, `file_validation.py`, - `lesson_documents.py` and `compose.yaml`. +- **Sources:** [course migration](../../backend/alembic/versions/0005_lessons.py), + [storage](../../backend/app/services/document_storage.py), + [file validation](../../backend/app/services/file_validation.py), + [document service](../../backend/app/services/lesson_documents.py), [Compose](../../compose.yaml). ## Context and decision diff --git a/docs/decisions/0008-groups-timetables-and-calendar-feeds.md b/docs/decisions/0008-groups-timetables-and-calendar-feeds.md index 5f0da76..1d6f6ad 100644 --- a/docs/decisions/0008-groups-timetables-and-calendar-feeds.md +++ b/docs/decisions/0008-groups-timetables-and-calendar-feeds.md @@ -2,7 +2,8 @@ - **Status:** Accepted - **Date:** 2026-10-30 -- **Sources:** `0006_promotion_groups.py`, `0007_timetable.py` and timetable/group services. +- **Sources:** [group migration](../../backend/alembic/versions/0006_promotion_groups.py), + [timetable migration](../../backend/alembic/versions/0007_timetable.py). ## Context and decision @@ -14,8 +15,8 @@ Named custom groups extend audiences in 0007 without overloading standard partit Timetables separate calendars, school years, rooms, yearly settings, teacher availability and compact JSONB recurrence/exception series. Relational references protect teacher/subject/room integrity; services validate recurrence content, overlaps, audiences and publication permissions. A partial unique -index permits only one non-archived calendar per promotion. Availability ranges may be null; kholle -bounds remain ordered and nonnegative. Revision tokens prevent silent concurrent overwrites. +index permits only one non-archived calendar per promotion. Availability ranges may be null. +Revision tokens prevent silent concurrent overwrites. Personal ICS subscriptions use hashed tokens for lookup and encrypted recoverable tokens for display. Tokens are credentials: requests recheck account/subscription status; links are revocable and excluded @@ -34,5 +35,5 @@ See [timetable behavior and feeds](../timetable.md), authorization integration t frontend recurrence/occupancy tests. [ADR 0010](0010-kholloscope-drafts-and-revisions.md) extends this design with private kholloscope -generation and dated revisions. Its consolidated 0008 migration replaces the legacy availability -hour bounds with exact subject commitments; the final schema no longer retains those bounds. +generation and dated revisions. Exact subject commitments are stored separately from weekly +availability patterns. diff --git a/docs/decisions/0009-compose-and-bff-trust-boundary.md b/docs/decisions/0009-compose-and-bff-trust-boundary.md index 467af4b..d7f58ae 100644 --- a/docs/decisions/0009-compose-and-bff-trust-boundary.md +++ b/docs/decisions/0009-compose-and-bff-trust-boundary.md @@ -2,8 +2,8 @@ - **Status:** Accepted - **Date:** 2026-10-30 -- **Sources:** `compose.yaml`, `compose.local.yaml`, `infra/postgres/init/001_roles.sql`, - `infra/nginx.conf`, backend proxy middleware and frontend server helpers. +- **Sources:** [Compose base](../../compose.yaml), [local overlay](../../compose.local.yaml), + [database roles](../../infra/postgres/init/001_roles.sql), [host proxy](../../infra/nginx.conf). ## Context and decision diff --git a/docs/decisions/0010-kholloscope-drafts-and-revisions.md b/docs/decisions/0010-kholloscope-drafts-and-revisions.md index 5e04287..d208a09 100644 --- a/docs/decisions/0010-kholloscope-drafts-and-revisions.md +++ b/docs/decisions/0010-kholloscope-drafts-and-revisions.md @@ -2,7 +2,9 @@ - **Status:** Accepted - **Date:** 2026-11-09 -- **Sources:** `0008_kholloscope.py`, kholloscope API, services, worker and PostgreSQL tests. +- **Sources:** [migration](../../backend/alembic/versions/0008_kholloscope.py), + [API](../../backend/app/api/v1/kholloscope.py), + [publication revisions](../../backend/app/services/kholloscope_revision.py). - **Extends:** [ADR 0008](0008-groups-timetables-and-calendar-feeds.md). ## Context and decision @@ -37,11 +39,9 @@ scope. Only administrators receive the initial grants; no new role or teacher ac Named PDF rosters additionally require `users.read`. All browser writes retain the existing CSRF policy, and drafts/snapshots are excluded from public feeds and search indexing. -Consolidate the unreleased feature revisions 0008–0014 into `0008_kholloscope` with the project -owner's explicit authorization. Leave revisions 0001–0007 unchanged. Remove legacy availability -min/max hour columns: exact staff/subject commitments and their recorded reference cycles replace -them. A downgrade restores zero bounds, not discarded values, and removes private drafts while -preserving published timetable series. +Exact staff/subject commitments and their recorded reference cycles provide the kholle contract, +independently of weekly availability. A downgrade removes private drafts while preserving +published timetable series. ## Consequences and alternatives @@ -55,10 +55,6 @@ event model. SQL constraints protect relational identities, commitment bounds, r active-job uniqueness; services validate the JSON content and scheduling rules. No speculative JSONB indexes are added. Future query or retention requirements may justify a separate decision. -The consolidated migration is suitable for a fresh database or one still at 0007. A database -stamped with replaced revisions needs a reviewed transition even if its application rows are empty. -Published migrations become immutable after this release. - -See [kholloscope behavior](../kholloscope-generation.md), [schema inventory](../database.md#migrations) -and [release security review](../security-review.md). Tests cover real CP-SAT behavior, authorization, +See [kholloscope behavior](../kholloscope-generation.md) and [schema inventory](../database.md#migrations) +for operational contracts and migration compatibility. Tests cover real CP-SAT behavior, authorization, source invalidation, PostgreSQL constraints, upgrade/downgrade and transactional publication/rollback. diff --git a/docs/decisions/0011-curricula-and-competency-graphs.md b/docs/decisions/0011-curricula-and-competency-graphs.md new file mode 100644 index 0000000..33f444e --- /dev/null +++ b/docs/decisions/0011-curricula-and-competency-graphs.md @@ -0,0 +1,72 @@ +# ADR 0011: Shared curricula, competency graphs and portable subject files + +- **Status:** Accepted +- **Date:** 2026-11-13 +- **Sources:** [migration](../../backend/alembic/versions/0009_curricula.py), + [service](../../backend/app/services/curricula.py), [JSON contracts](../../backend/app/schemas/curricula.py). +- **Extends:** [ADR 0006](0006-teaching-catalogues-and-courses.md), + [ADR 0009](0009-compose-and-bff-trust-boundary.md). + +## Context and decision + +CPGE programmes describe competencies across two years, sometimes with several hierarchical +levels and shared descendants. Other subjects need a simpler structure. Teachers enter the current +official programme; the application does not enforce a particular ministry document structure. + +Represent the pathway and reference programme by one `curricula` entity with administrator-selected +existing subjects. Promotions may reference a curriculum, but their free names, years and calendar +identities remain independent. Keep an optional external official PDF link without server-side +fetching or uploading. Updates take effect immediately; do not introduce draft publication or +historical official-programme editions in this feature. + +Store competencies as a subject-scoped directed acyclic graph, not a recursive JSON tree. Composite +foreign keys constrain both link endpoints to the same curriculum and subject. Allow several parents +without duplicating the competency or its notes. Services reject cycles iteratively under a curriculum +row lock. Deleting a competency removes its links and preserves its children. + +Generate one code per identity from the first shortest ordered path. Alternate uppercase letters, +numbers and lowercase letters (`A`, `A.1`, `A.1.a`, `A.1.a.1`); recompute after detachments and edits. +Codes are derived response fields, not editable database columns. Keep `position` for sibling order +and nullable colors for branch inheritance. + +Grant all permanent administrators, teachers and kholleurs reading access through `curricula.read`. +Metadata management requires `curricula.manage`; competency writes require either that capability +or `curricula.edit` plus a current assignment to an active subject. Services recheck live permissions +and serialize with the existing account/assignment lifecycle lock. UI visibility is not authorization. + +Keep `curricula.version`: it is an optimistic concurrency counter used by metadata, graph edits, +imports and undo, not an official programme edition. Persist at most twenty inverse operations per +actor/curriculum in JSONB. Undo rechecks current subject rights and the exact intervening revision; +it restores identities/links or removes one imported batch atomically. Old node IDs in undo have no +competency foreign key because deleted identities must be restorable; batch records use a sentinel +and explicit created IDs. Journal successful changes with bounded human-readable references. + +Use versioned JSON files per subject: a flat node list with file-local IDs and parent IDs preserves +shared descendants. Import appends with fresh identities, retains existing data, and can be undone +as one action. Export names the download after its subject using a safe portable basename. The server +validates the original JSON text, rejects ambiguous/unknown fields, invalid links, cycles and excessive +size/depth, and never evaluates file content. Existing CSRF/session controls and narrow bounded-body +exceptions remain in force; do not raise the ordinary request limit globally. + +Use Three.js for the desktop graph and existing HTML controls, modals, subject badges and file +dropzone. Recalculate visible branches on concentric rings when nodes open/close. Direct clipped +links and particles connect block borders. A compact indented outline is always available, and is +the only view at widths up to 650 px; no WebGL context is created there. Renderer resources are +released when switching to mobile and recreated on returning to desktop. Keep this layout independent +from persisted pedagogical data. + +## Consequences and alternatives + +A single parent column would be simpler but could not express shared competencies. Persisting one +recursive JSON document would weaken relational integrity and complicate scoped edits. Persisted +manual codes would drift after graph changes. Version-free writes would overwrite concurrent edits +and make inverse operations unsafe. Server-side programme PDF fetching is unnecessary for a link and +would introduce an additional network trust boundary. + +The graph has one canonical displayed identity for shared nodes; extra cross-links can still cross. +Undo is short operational recovery, not programme versioning or a full audit snapshot. Reimporting +the same file appends duplicates by design. Limits and current API/UI behavior are documented in +[curricula](../curricula.md), including migration compatibility and downgrade behavior. +Verification covers the Alembic chain, repeated upgrade/downgrade, +schema/metadata equivalence, existing-row preservation, authorization, revisions, codes, file +validation and browser desktop/mobile interactions. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 5246aa5..131f556 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -4,24 +4,27 @@ This directory contains Architecture Decision Records (ADRs) documenting signifi ## Accepted decisions -| ADR | Responsibility / migration sources | +| ADR | Decision | | --- | --- | | [0001](0001-technology-stack.md) | Stack and component separation | | [0002](0002-postgresql-infrastructure.md) | SQLAlchemy, PostgreSQL roles and Alembic | | [0003](0003-backend-authentication.md) | Original authentication design, amended by 0004/0005 | | [0004](0004-accounts-promotions-activity.md) | Accounts, capabilities and activity; 0001/0003 | -| [0005](0005-release-baseline-and-configuration.md) | Seven-revision baseline and configuration/cache; 0002 | +| [0005](0005-release-baseline-and-configuration.md) | Installation baseline, configuration and release cache | | [0006](0006-teaching-catalogues-and-courses.md) | Promotions, subjects and courses; 0003 through 0005 | | [0007](0007-private-course-documents.md) | Private storage and document trust; 0005 | | [0008](0008-groups-timetables-and-calendar-feeds.md) | Groups, timetables and ICS; 0006/0007 | | [0009](0009-compose-and-bff-trust-boundary.md) | Two Compose files and proxy trust | +| [0010](0010-kholloscope-drafts-and-revisions.md) | Private kholloscope jobs, publication and dated revisions | +| [0011](0011-curricula-and-competency-graphs.md) | Shared curricula, competency graphs and portable subject files | -ADR numbers identify decisions, not migrations. The migration head is `0007_timetable`; -there is no Alembic revision 0008. See [the inventory](../database.md#migrations). +ADR numbers identify decisions, not migrations. The migration head is `0009_curricula`. +See [the migration inventory](../database.md#migrations). ## What is an ADR? An ADR records: + - The context and problem behind a decision. - The options considered. - The decision made. diff --git a/docs/environment.md b/docs/environment.md index e64222d..da08c1a 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -101,6 +101,11 @@ password hashing concurrency. Native hashing settings and validation bounds are [authentication configuration](authentication.md#keys-and-configuration); settings not forwarded by Compose cannot be overridden merely by adding them to `.env`. +Curriculum JSON files are limited to 4 MiB. The exact backend curriculum-import route and frontend +`/curricula/transfer` route use an 8 MiB + 4 KiB request-envelope exception for the original escaped +file text, with the existing body-read deadline and authentication/CSRF policy. This does not change +`AUTH_REQUEST_MAX_BYTES` or the separate binary document upload limit. See [curricula](curricula.md). + ## Private document storage All sizes below are bytes; 1 MiB = 1048576 bytes and 1 GiB = 1073741824 bytes. diff --git a/docs/frontend-bff.md b/docs/frontend-bff.md index 69ebe51..58244c9 100644 --- a/docs/frontend-bff.md +++ b/docs/frontend-bff.md @@ -60,6 +60,31 @@ can be retried without creating another account. ## Responsive workspace +### Curriculum workspace + +`/curricula` and its header link require `curricula.read`; server loads and backend services both +enforce this. Administrators manage metadata, while current subject assignments scope teacher +competency/import actions. Kholleurs receive a read-only view. Promotions may reference a curriculum +without changing their free name or calendar identity. + +The desktop graph uses Three.js and existing subject badges/modals. Concentric rings are recalculated +for visible branches; direct links join block borders. The compact parent-first outline is the only +view at widths up to 650 px, with no WebGL initialization there. Returning to desktop recreates the +canvas/context. Subject headings add a root competency only when authorized. Other editors retain +keyboard handling, inherited colors, fullscreen toggling and reduced-motion behavior. + +`POST /curricula/data` relays allowlisted metadata, graph, node and undo commands. The dedicated +`POST /curricula/transfer` accepts only import/export commands with positive numeric IDs. The latter +alone has an 8 MiB + 4 KiB bounded-body guard for escaped original JSON file text; ordinary JSON +writes retain 16 KiB. Backend parsing and live permissions remain authoritative. Exports use the +chosen subject name as a safe `.json` basename; imports append atomically and can be undone as a lot. +The file modal reuses the course document dropzone. No uploaded file or teaching text is executed. + +See [curriculum behavior and limits](curricula.md) and +[ADR 0011](decisions/0011-curricula-and-competency-graphs.md). + +### Administration workspace + The administrator overview shows a half-doughnut of active, pending-activation and archived accounts, the total and active promotion counts, promotion shortcuts and a journal of 15 events per page. Journal entries use newest timestamps first with ID tie-breaking; arrows navigate opaque cursors. @@ -164,8 +189,7 @@ the displayed token; reopen the existing account to generate a replacement. Activation reads `#token=…` in the browser, removes the fragment from the current history entry, and submits the token in a form body through the BFF. Pasting a token manually also works without JavaScript. The token is single-use, expires, and is replaced by explicit regeneration. Manual -delivery does not verify the email. Under explicit owner authorization, the existing 0001 migration -includes archive dates and invitation purposes; no migration was added for this draft. +delivery does not verify the email. ## Code and verification diff --git a/docs/kholloscope-generation.md b/docs/kholloscope-generation.md index b32794a..bad7343 100644 --- a/docs/kholloscope-generation.md +++ b/docs/kholloscope-generation.md @@ -426,5 +426,4 @@ A PostgreSQL integration test migrates and exercises the real durable queue, ass publication and rights. Browser tests cover live progress, correction, group assignment and explicit application. Use the existing project pytest and frontend verification commands. -Revision subjects are selected with keyboard-accessible toggle buttons. For release verification -and known dependency findings, see the [security review](security-review.md). +Revision subjects are selected with keyboard-accessible toggle buttons. diff --git a/docs/lessons.md b/docs/lessons.md index a2787c6..f866108 100644 --- a/docs/lessons.md +++ b/docs/lessons.md @@ -330,8 +330,8 @@ valuable course data to bypass that guard. ### Verification -`tests/test_document_storage.py` checks actual supported file structures, hostile archives, -streaming/hash limits and actual subprocess validation/publication. `tests/test_lesson_documents_postgres.py` +[Document storage tests](../backend/tests/unit/lessons/test_document_storage.py) check supported file structures, hostile archives, +streaming/hash limits and subprocess validation/publication. [Document integration tests](../backend/tests/integration/lessons/test_lesson_documents_postgres.py) checks real disk operations, PostgreSQL cascades, free table labels, independent cells, staff-only subtrees, live dates/access, replacements, stale uploads, storage failures, integrity errors and durable deletion retry. Parsing, database and filesystem operations remain real. diff --git a/docs/timetable.md b/docs/timetable.md index 40cb5df..5476fe6 100644 --- a/docs/timetable.md +++ b/docs/timetable.md @@ -353,10 +353,10 @@ Default availability is 08:00–19:00 Monday–Friday and 08:00–12:00 Saturday An absent pattern means that entire grid is available; an explicit empty pattern means unavailable. Saving null restores the default. Patterns belong only to their chosen year and are never copied. Availability editing stores only weekly ranges. Khôlle commitments are managed exclusively -in `/timetable/kholloscope`; migration `0008_kholloscope` removes the former min/max columns. -Existing availability ranges and revisions are preserved. Legacy bounds are discarded without -conversion because they do not define an exact commitment per subject; downgrade restores zero -bounds and cannot recover their previous values. Earlier baseline migrations remain unchanged. +in `/timetable/kholloscope`. The cleaned `0007_timetable` baseline never creates legacy min/max +columns, and `0008_kholloscope` neither removes nor restores them. Availability ranges and revisions +are preserved when applying or rolling back `0008`. Databases that applied the former `0007` +with legacy bounds need a reviewed transition; these amended files do not clean an existing schema. Overlapping/touching ranges merge. Out-of-grid submissions, including Saturday afternoon, are refused. The Saturday column remains visible in the staff workspace regardless of promotion settings. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index a890162..1f07f52 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,18 +1,19 @@ { "name": "frontend", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "frontend", - "version": "0.2.0", + "version": "0.3.0", "dependencies": { "@event-calendar/core": "^5.18.1", "@fortawesome/free-solid-svg-icons": "^7.3.1", "@sveltejs/kit": "^3.0.0", "bulma": "^1.0.4", "svelte": "^5.57.3", + "three": "^0.187.0", "vite": "^8.3.5" }, "devDependencies": { @@ -21,6 +22,7 @@ "@sveltejs/adapter-node": "^6.0.0", "@sveltejs/vite-plugin-svelte": "^7.2.0", "@types/node": "^24", + "@types/three": "^0.187.0", "eslint": "^10.4.1", "eslint-config-prettier": "^10.1.8", "eslint-plugin-svelte": "^3.19.0", @@ -57,6 +59,13 @@ "keyv": "^5.6.0" } }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.10.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", @@ -737,6 +746,13 @@ "vite": "^8.0.0-beta.7 || ^8.0.0" } }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/esrecurse": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", @@ -767,6 +783,35 @@ "undici-types": ">=7.24.0 <7.24.7" } }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.187.0.tgz", + "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "fflate": "~0.8.3", + "meshoptimizer": "~1.1.1" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.72.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz", @@ -1504,6 +1549,13 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "11.1.5", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", @@ -2016,6 +2068,13 @@ "@jridgewell/sourcemap-codec": "^1.6.0" } }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "dev": true, + "license": "MIT" + }, "node_modules/minimatch": { "version": "11.0.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.5.tgz", @@ -2678,6 +2737,12 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz", + "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==", + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", diff --git a/frontend/package.json b/frontend/package.json index 8b70236..c749b91 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.2.0", + "version": "0.3.0", "type": "module", "scripts": { "dev": "vite dev", @@ -20,6 +20,7 @@ "@sveltejs/kit": "^3.0.0", "bulma": "^1.0.4", "svelte": "^5.57.3", + "three": "^0.187.0", "vite": "^8.3.5" }, "devDependencies": { @@ -28,6 +29,7 @@ "@sveltejs/adapter-node": "^6.0.0", "@sveltejs/vite-plugin-svelte": "^7.2.0", "@types/node": "^24", + "@types/three": "^0.187.0", "eslint": "^10.4.1", "eslint-config-prettier": "^10.1.8", "eslint-plugin-svelte": "^3.19.0", diff --git a/frontend/src/hooks.server.ts b/frontend/src/hooks.server.ts index 21e2cfd..682d2c4 100644 --- a/frontend/src/hooks.server.ts +++ b/frontend/src/hooks.server.ts @@ -22,7 +22,8 @@ export const handle: Handle = async ({ event, resolve }) => { event.url.pathname !== '/lessons/upload' ) { const length = event.request.headers.get('content-length'); - const bodyLimit = 16384; + const bodyLimit = + event.url.pathname === '/curricula/transfer' ? 8 * 1024 * 1024 + 4096 : 16384; if (length && (!/^\d{1,8}$/.test(length) || Number(length) > bodyLimit)) throw new BackendError(413, 'Demande trop volumineuse.'); let size = 0; diff --git a/frontend/src/lib/activity.ts b/frontend/src/lib/activity.ts index e340636..a55fb29 100644 --- a/frontend/src/lib/activity.ts +++ b/frontend/src/lib/activity.ts @@ -40,6 +40,13 @@ export function roleTransitionLabel(name: string, roles: string[]): string { } const fieldLabels: Record = { + parent_ids: 'Compétences parentes', + source_url: 'Programme officiel', + is_active: 'État', + knowledge: 'Connaissances associées', + semester: 'Semestre', + position: 'Ordre', + subject_ids: 'Matières', audience: 'Visibilité', table_structure: 'Lignes et colonnes du tableau', first_name: 'Prénom', @@ -101,6 +108,32 @@ export function eventSubjects(value: unknown): ActivitySubject[] { /** Explain recorded facts without copying private profile values or invitation secrets. */ export function eventDetails(event: ActivityEvent): string[] { const data = event.data; + if (event.event_type === 'curriculum.changed') { + const labels: Record = { + referential_created: 'Référentiel créé', + referential_updated: 'Référentiel modifié', + referential_archived: 'Référentiel archivé', + referential_saved: 'Référentiel enregistré', + competency_created: 'Compétence ajoutée', + competency_updated: 'Compétence modifiée', + competency_deleted: 'Compétence supprimée', + competencies_imported: 'Compétences importées', + action_undone: 'Action annulée' + }; + return [ + labels[String(data.action)] ?? 'Programme modifié', + typeof data.imported_count === 'number' && data.imported_count > 0 + ? `${data.imported_count} compétence(s) ajoutée(s)` + : '', + typeof data.curriculum_title === 'string' ? `Référentiel : ${data.curriculum_title}` : '', + typeof data.subject_name === 'string' ? `Matière : ${data.subject_name}` : '', + typeof data.competency_name === 'string' ? `Compétence : ${data.competency_name}` : '', + Array.isArray(data.changed_fields) && data.changed_fields.length + ? `Champs : ${data.changed_fields.map((field) => fieldLabels[String(field)] ?? String(field)).join(', ')}` + : '', + data.competency_name ? `${data.parent_count} parent(s) · ${data.child_count} enfant(s)` : '' + ].filter(Boolean); + } if ( event.event_type.startsWith('timetable.') || event.event_type === 'user.availability_updated' diff --git a/frontend/src/lib/components/Header.svelte b/frontend/src/lib/components/Header.svelte index 25eaada..c2fbc9a 100644 --- a/frontend/src/lib/components/Header.svelte +++ b/frontend/src/lib/components/Header.svelte @@ -1,7 +1,7 @@  + + + + {subject.name} + + + diff --git a/frontend/src/lib/components/curricula/CompetencyCanvas.svelte b/frontend/src/lib/components/curricula/CompetencyCanvas.svelte new file mode 100644 index 0000000..9885996 --- /dev/null +++ b/frontend/src/lib/components/curricula/CompetencyCanvas.svelte @@ -0,0 +1,1193 @@ + + + +
+ {#each subjects as subject (subject.id)}
+ +
{/each} + {#if hiddenSubjects.size}{/if} +
+ +{#if webglError}

{webglError}

{/if} +{#if fullscreenError}

+ {fullscreenError} +

{/if} +
+ {#key mobile}{/key} +
+ + {#if query.trim()}
+ {#each matches as node (node.id)}{:else}Aucun résultat{/each} +
{/if} +
+
+ +
+ {#each layout as point (point.id)}{@const node = nodes.get(point.id)!}{@const subject = + point.id < 0 + ? subjects.find((s) => s.id === -point.id)! + : subjects.find((s) => s.id === ownership.get(point.id))!}{@const childCount = + sceneGraph.edges.filter((edge) => edge.parent_id === point.id).length} +
+ {#if point.id < 0} + {:else}{/if} +
+ + {#if point.id < 0 && pending.includes(-point.id)}{/if} + {#if point.id > 0}{/if} + {#if active && subject.can_edit && subject.is_active}{/if} +
+
+ {/each} +
+ Molette : zoom · Glisser : déplacer · Relâcher un nœud : retour en douceur +
+
+{#if showText}
+ {#if !mobile}{/if}{#each visibleSubjects as subject (subject.id)}
+

+ {#if active && subject.can_edit && subject.is_active} + {:else}{/if} +

+
+
    + {#each graphs[subject.id] ? competencyOutline(graphs[subject.id], subject.color) : [] as entry (entry.node.id)}{@const node = + entry.node} +
  1. + +
  2. {/each} +
{/each} +
{/if} + + diff --git a/frontend/src/lib/components/curricula/CompetencyEditor.svelte b/frontend/src/lib/components/curricula/CompetencyEditor.svelte new file mode 100644 index 0000000..1195f2b --- /dev/null +++ b/frontend/src/lib/components/curricula/CompetencyEditor.svelte @@ -0,0 +1,260 @@ + + + + {#if message}{/if} +
{ + event.preventDefault(); + void submit(); + }} + > +
+
+ +
+
+ Semestre +
+
+ +
+ +
+
+
+
+
+ Connaissances et commentaire +
+ +
+
+ +
+
+
+ Relations +
+ Compétences parentes +

+ Aucun parent : compétence racine. Décochez un parent pour détacher cette compétence. +

+ {#each graph.nodes.filter((n) => !forbidden.has(n.id)) as candidate (candidate.id)}{/each} +
+
+ +
+
+
+ Présentation + + {#if !inherit}{/if} +
+
+ {#if editable} + {#if confirmDelete}
+

+ Supprimer cette compétence de ses {graph.edges.filter( + (e) => e.child_id === original?.id + ).length} rattachement(s) ? Ses enfants seront conservés et deviendront des racines s’ils + n’ont plus de parent. +

+ +
{/if} + {/if} +
+ {#if editable} + {#if original} + + {/if}{/if} + {#if editable}{/if} +
+
+
+ + diff --git a/frontend/src/lib/components/curricula/CompetencyTransfer.svelte b/frontend/src/lib/components/curricula/CompetencyTransfer.svelte new file mode 100644 index 0000000..def81cb --- /dev/null +++ b/frontend/src/lib/components/curricula/CompetencyTransfer.svelte @@ -0,0 +1,165 @@ + + + + {#if message}{/if} +
{ + event.preventDefault(); + void transfer(); + }} + > +
+ +
+ +
+ {#if mode === 'import'} +

+ Les compétences seront ajoutées à la matière choisie. Les compétences existantes seront + conservées. +

+

Fichier JSON (4 Mo maximum)

+ void selectFile(file)} + /> + {#if document}

+ {count} compétence(s) à importer. Le serveur vérifiera les champs et les relations avant l’ajout. +

{/if} + {:else}

+ Toutes les compétences de cette matière seront exportées, avec leurs relations, semestres, + connaissances, commentaires et couleurs. +

{/if} +
+
+ +
+
+
diff --git a/frontend/src/lib/components/curricula/CurriculumEditor.svelte b/frontend/src/lib/components/curricula/CurriculumEditor.svelte new file mode 100644 index 0000000..cade939 --- /dev/null +++ b/frontend/src/lib/components/curricula/CurriculumEditor.svelte @@ -0,0 +1,157 @@ + + + + {#if message}{/if} +
+
+
+ +
+
+ +
+
+ +

Lien facultatif vers le PDF ou sa page officielle.

+
+
+ Matières du référentiel +
+ {#each catalog.subjects.filter((s) => s.is_active || subjects.includes(s.id)) as subject (subject.id)}{/each} +
+
+ {#if original}{/if} +
+ +
+
+
+
+ + diff --git a/frontend/src/lib/components/dashboard/PromotionEditor.svelte b/frontend/src/lib/components/dashboard/PromotionEditor.svelte index 186062e..51d4c89 100644 --- a/frontend/src/lib/components/dashboard/PromotionEditor.svelte +++ b/frontend/src/lib/components/dashboard/PromotionEditor.svelte @@ -1,5 +1,6 @@ + + + +Référentiels — {data.establishmentName} + +
+
+
+ +

Référentiels

+
+ {#if catalog.curricula.length}
+ +
{/if} + {#if curriculum?.source_url} + + PDF officiel + + {/if} +
+ {#if curriculum} + {#if curriculum.is_active && subjects.some((s) => s.can_edit && s.is_active)}{/if}{/if} + + {#if catalog.can_manage}{#if curriculum}{/if}{/if} +
+
+ {#if curriculum?.description}

+ {curriculum.description} +

{/if} + {#if message}{/if} + {#if curriculum} + {#key curriculumId} { + void loadSubject(id); + }} + onopen={(subjectId, node) => (editor = { subjectId, node })} + onadd={(subjectId, parentId) => { + void add(subjectId, parentId); + }} + />{/key} + {:else}
+ +

Un référentiel, toutes ses matières.

+

+ {catalog.can_manage + ? 'Créez directement votre référentiel et choisissez les matières de son programme.' + : 'Les référentiels apparaîtront ici dès leur création par un administrateur.'} +

+ {#if catalog.can_manage}{/if} +
{/if} +
+{#if settings} (settings = null)} + onsaved={(result) => { + void saved(result); + }} + />{/if} +{#if editor && editingGraph}{#key `${editor.subjectId}-${editor.node?.id ?? 'new'}-${editor.parentId ?? ''}`} (editor = null)} + onsaved={acceptEdit} + onchild={(parentId) => { + if (editor) editor = { subjectId: editor.subjectId, parentId }; + }} + />{/key}{/if} + +{#if transferMode && curriculum}{#key curriculumId} s.can_edit && s.is_active) + : subjects} + onclose={() => (transferMode = null)} + onsaved={acceptEdit} + />{/key}{/if} + + diff --git a/frontend/src/routes/curricula/data/+server.ts b/frontend/src/routes/curricula/data/+server.ts new file mode 100644 index 0000000..a4fd9ef --- /dev/null +++ b/frontend/src/routes/curricula/data/+server.ts @@ -0,0 +1,66 @@ +import { error, json } from '@sveltejs/kit'; +import { hasPermission } from '#lib/access'; +import { api } from '#lib/server/api'; +import { BackendError } from '#lib/server/backend'; +import type { RequestHandler } from './$types'; + +function id(value: unknown): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) + error(422, 'Identifiant invalide.'); + return value; +} + +export const POST: RequestHandler = async (event) => { + if (!event.locals.user) return json({ message: 'Votre session a expiré.' }, { status: 401 }); + if (!hasPermission(event.locals.user, 'curricula.read')) error(403, 'Accès refusé.'); + let raw: unknown; + try { + raw = await event.request.json(); + } catch { + error(422, 'Demande invalide.'); + } + if (!raw || typeof raw !== 'object') error(422, 'Demande invalide.'); + const input = raw as Record; + try { + if (input.command === 'catalog') return json(await api(event, '/curricula/catalog')); + if (input.command === 'undo') + return json( + await api(event, `/curricula/${id(input.curriculum_id)}/undo`, 'POST', input.data) + ); + if (input.command === 'graph') + return json( + await api(event, `/curricula/${id(input.curriculum_id)}/subjects/${id(input.subject_id)}`) + ); + if (input.command === 'saveNode' || input.command === 'deleteNode') { + const path = `/curricula/${id(input.curriculum_id)}/subjects/${id(input.subject_id)}/nodes`; + if (input.command === 'deleteNode') + return json(await api(event, `${path}/${id(input.id)}`, 'DELETE', input.data)); + return json( + await api( + event, + input.id ? `${path}/${id(input.id)}` : path, + input.id ? 'PUT' : 'POST', + input.data + ) + ); + } + if (!hasPermission(event.locals.user, 'curricula.manage')) + error(403, 'Accès réservé aux administrateurs.'); + if (input.command === 'saveCurriculum') { + const path = '/curricula'; + return json( + await api( + event, + input.id ? `${path}/${id(input.id)}` : path, + input.id ? 'PUT' : 'POST', + input.data + ) + ); + } + error(404, 'Action inconnue.'); + } catch (cause) { + if (cause instanceof BackendError) + return json({ message: cause.message }, { status: cause.status }); + throw cause; + } +}; diff --git a/frontend/src/routes/curricula/transfer/+server.ts b/frontend/src/routes/curricula/transfer/+server.ts new file mode 100644 index 0000000..872f743 --- /dev/null +++ b/frontend/src/routes/curricula/transfer/+server.ts @@ -0,0 +1,45 @@ +import { error, json } from '@sveltejs/kit'; +import { hasPermission } from '#lib/access'; +import { api } from '#lib/server/api'; +import { BackendError } from '#lib/server/backend'; +import type { RequestHandler } from './$types'; + +export const POST: RequestHandler = async (event) => { + if (!hasPermission(event.locals.user, 'curricula.read')) error(403, 'Accès refusé.'); + let raw: unknown; + try { + raw = await event.request.json(); + } catch { + error(422, 'JSON invalide.'); + } + if (!raw || typeof raw !== 'object') error(422, 'Demande invalide.'); + const input = raw as Record; + if ( + typeof input.command !== 'string' || + !['import', 'export'].includes(input.command) || + typeof input.curriculum_id !== 'number' || + !Number.isSafeInteger(input.curriculum_id) || + input.curriculum_id <= 0 || + typeof input.subject_id !== 'number' || + !Number.isSafeInteger(input.subject_id) || + input.subject_id <= 0 + ) + error(422, 'Demande invalide.'); + const path = `/curricula/${input.curriculum_id}/subjects/${input.subject_id}/${input.command}`; + try { + return json( + await api( + event, + path, + input.command === 'export' ? 'GET' : 'POST', + input.command === 'export' + ? undefined + : { expected_version: input.expected_version, document: input.document } + ) + ); + } catch (cause) { + if (cause instanceof BackendError) + return json({ message: cause.message }, { status: cause.status }); + throw cause; + } +}; diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelte index 4f892ad..bb9ce7c 100644 --- a/frontend/src/routes/dashboard/+page.svelte +++ b/frontend/src/routes/dashboard/+page.svelte @@ -62,8 +62,8 @@ ? [ { id: 'overview', name: 'Vue d’ensemble', icon: 'overview' as const }, { id: 'promotions', name: 'Promotions', icon: 'promotions' as const }, - { id: 'accounts', name: 'Comptes', icon: 'accounts' as const }, { id: 'subjects', name: 'Matières', icon: 'book' as const }, + { id: 'accounts', name: 'Comptes', icon: 'accounts' as const }, { id: 'team', name: 'Équipe enseignante', icon: 'teacher' as const }, { id: 'configuration', name: 'Configuration', icon: 'edit' as const } ] diff --git a/frontend/tests/access.test.ts b/frontend/tests/access.test.ts index b9a87de..fc63137 100644 --- a/frontend/tests/access.test.ts +++ b/frontend/tests/access.test.ts @@ -7,8 +7,8 @@ function user(roles: string[]): User { return { id: 1, username: 'member', - first_name: 'Valentin', - last_name: 'Burgaud', + first_name: 'Exemple', + last_name: 'Fictif', email: null, status: 'active', roles, diff --git a/frontend/tests/activity.test.ts b/frontend/tests/activity.test.ts index 770b62a..cf3c551 100644 --- a/frontend/tests/activity.test.ts +++ b/frontend/tests/activity.test.ts @@ -10,6 +10,24 @@ import { } from '../src/lib/activity.ts'; import type { ActivityEvent } from '../src/lib/types.ts'; +test('programme journal identifies the action, subject, competency and relationship counts', () => { + const details = eventDetails( + event('curriculum.changed', { + action: 'competency_created', + curriculum_title: 'PTSI/PT', + subject_name: 'SII', + competency_name: 'Analyser', + changed_fields: ['parent_ids'], + parent_count: 1, + child_count: 0 + }) + ); + assert.ok(details.includes('Compétence ajoutée')); + assert.ok(details.includes('Matière : SII')); + assert.ok(details.includes('Compétence : Analyser')); + assert.ok(details.includes('Champs : Compétences parentes')); +}); + function event(event_type: string, data: Record): ActivityEvent { return { id: 1, @@ -22,8 +40,8 @@ function event(event_type: string, data: Record): ActivityEvent subject_role: 'user', actor_profile_available: true, subject_profile_available: true, - actor_label: 'Val Burgaud', - subject_label: 'Marie Tidj', + actor_label: 'Exemple Fictif', + subject_label: 'Modele Tidj', resource_type: null, resource_id: null, promotion_snapshot: null, @@ -85,12 +103,12 @@ test('combined role changes stay explicit even when their highest role remains a assert.deepEqual(eventRoles(['kholleur', 'forged']), ['kholleur']); assert.equal(highestRole([]), null); assert.equal( - roleTransitionLabel('Marie', ['teacher', 'admin']), - 'Marie · Enseignant + Administrateur' + roleTransitionLabel('Modele', ['teacher', 'admin']), + 'Modele · Enseignant + Administrateur' ); assert.notEqual( - roleTransitionLabel('Marie', ['admin']), - roleTransitionLabel('Marie', ['teacher', 'admin']) + roleTransitionLabel('Modele', ['admin']), + roleTransitionLabel('Modele', ['teacher', 'admin']) ); }); diff --git a/frontend/tests/backend.test.ts b/frontend/tests/backend.test.ts index 65fe1f8..c906d62 100644 --- a/frontend/tests/backend.test.ts +++ b/frontend/tests/backend.test.ts @@ -21,6 +21,10 @@ test('the bridge permits course roots and element operations while refusing arbi for (const [path, method] of [ ['/lessons?q=maths', 'GET'], ['/lessons', 'POST'], + ['/curricula/catalog', 'GET'], + ['/curricula/tracks', 'POST'], + ['/curricula/12/subjects/3', 'GET'], + ['/curricula/12/subjects/3/nodes/4', 'PUT'], ['/lessons/12', 'PUT'], ['/lessons/12/elements/34', 'DELETE'], ['/lessons/12/elements/34/move', 'POST'], @@ -43,6 +47,7 @@ test('the bridge permits course roots and element operations while refusing arbi } for (const path of [ '/lessons/../admin/users', + '/curricula/../admin/users', '//evil.example', '/lessons/12#secret', '/unknown/path', @@ -265,11 +270,11 @@ test('bridge supports typed mutations and encoded directory queries without perm await requestBackend( event(null, 'GET').input, config, - '/teaching/users/search?q=du%20sejour&limit=20', + '/teaching/users/search?q=du%20test&limit=20', 'GET', undefined, async (url) => { - assert.equal(url, 'http://backend:8000/api/v1/teaching/users/search?q=du%20sejour&limit=20'); + assert.equal(url, 'http://backend:8000/api/v1/teaching/users/search?q=du%20test&limit=20'); return Response.json([]); } ); diff --git a/frontend/tests/browser.mjs b/frontend/tests/browser.mjs index 2e4b48a..e5bec52 100644 --- a/frontend/tests/browser.mjs +++ b/frontend/tests/browser.mjs @@ -183,7 +183,7 @@ export async function courseBrowserJourney({ await page.getByRole('button', { name: 'Accès et collaborateurs', exact: true }).click(); await dialog .getByLabel('Ajouter un enseignant ou un khôlleur', { exact: true }) - .fill('Camille'); + .fill('Compte'); await dialog .locator('#collaborator-candidates') .getByRole('button', { name: /^Ajouter / }) @@ -441,7 +441,7 @@ export async function browserJourney({ body: JSON.stringify({ command: 'createUser', data: { - first_name: 'Camille', + first_name: 'Compte', last_name: 'Colleur', email: 'browser-kholleur@example.org', roles: ['kholleur'] @@ -513,8 +513,8 @@ export async function browserJourney({ .uncheck(); await creationRoles.getByRole('checkbox', { name: 'Khôlleur', exact: true }).uncheck(); await creationRoles.getByRole('checkbox', { name: 'Élève', exact: true }).check(); - await dialog.getByLabel('Prénom', { exact: true }).fill('Élodie'); - await dialog.getByLabel('Nom', { exact: true }).fill('Roy'); + await dialog.getByLabel('Prénom', { exact: true }).fill('Échantillon'); + await dialog.getByLabel('Nom', { exact: true }).fill('Test'); await dialog.getByLabel('Adresse email', { exact: true }).fill('browser@example.org'); await dialog.getByRole('button', { name: 'Créer le compte', exact: true }).click(); await dialog.getByRole('heading', { name: 'Compte créé', exact: true }).waitFor(); @@ -528,9 +528,9 @@ export async function browserJourney({ .getByRole('textbox', { name: 'Rechercher un compte', exact: true }) .fill(student.username); await page.locator('.account-row').filter({ hasText: student.username }).click(); - await dialog.getByRole('heading', { name: 'Valentin Burgaud', exact: true }).waitFor(); + await dialog.getByRole('heading', { name: 'Exemple Fictif', exact: true }).waitFor(); await dialog.getByRole('link', { name: 'Voir la fiche complète', exact: true }).click(); - await page.getByRole('heading', { name: 'Valentin Burgaud', exact: true }).waitFor(); + await page.getByRole('heading', { name: 'Exemple Fictif', exact: true }).waitFor(); await page.getByLabel('Ville et code postal', { exact: true }).fill('Nant'); await page.getByRole('button', { name: 'Nantes 44000', exact: true }).click(); assert.equal( @@ -548,8 +548,8 @@ export async function browserJourney({ await page.getByRole('button', { name: 'Ajouter une option', exact: true }).click(); await page.getByLabel('Option 1', { exact: true }).fill('Mathématiques'); await page.getByLabel('Note /20', { exact: true }).fill('0'); - await page.getByLabel('Prénom du référent', { exact: true }).fill('Marie'); - await page.getByLabel('Nom du référent', { exact: true }).fill('Roy'); + await page.getByLabel('Prénom du référent', { exact: true }).fill('Modele'); + await page.getByLabel('Nom du référent', { exact: true }).fill('Test'); await page.getByLabel('Téléphone du référent', { exact: true }).fill('01 23 45 67 89'); await page.getByRole('link', { name: 'Retour aux comptes', exact: true }).click(); await dialog @@ -588,7 +588,7 @@ export async function browserJourney({ assert.ok( (await dialog.getByRole('alert').textContent()) .replace(/\s+/g, ' ') - .includes('Valentin Burgaud') + .includes('Exemple Fictif') ); await dialog.getByRole('button', { name: 'Annuler', exact: true }).click(); await dialog.waitFor({ state: 'hidden' }); @@ -707,10 +707,10 @@ export async function browserJourney({ const teamSubject = page .locator('.team-subject') .filter({ has: page.getByRole('heading', { name: 'Matière corrigée', exact: true }) }); - await teamSubject.getByRole('link', { name: 'Marie Dupont', exact: true }).waitFor(); + await teamSubject.getByRole('link', { name: 'Modele Temoin', exact: true }).waitFor(); assert.equal(await teamSubject.locator('a.role-teacher').count(), 1); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); - await teamSubject.getByRole('link', { name: 'Marie Dupont', exact: true }).click(); + await teamSubject.getByRole('link', { name: 'Modele Temoin', exact: true }).click(); await assignedSubjects .getByRole('checkbox', { name: 'Matière corrigée', exact: true }) .waitFor(); @@ -810,7 +810,7 @@ export async function browserJourney({ ); await page.getByRole('button', { name: 'Mes élèves', exact: true }).click(); await page.locator('.account-row').filter({ hasText: student.username }).click(); - await dialog.getByRole('heading', { name: 'Valentin Burgaud', exact: true }).waitFor(); + await dialog.getByRole('heading', { name: 'Exemple Fictif', exact: true }).waitFor(); assert.equal( await dialog.getByRole('button', { name: /Archiver|Réinitialiser|invitation/ }).count(), 0 @@ -820,7 +820,7 @@ export async function browserJourney({ 0 ); await dialog.getByRole('link', { name: 'Voir la fiche complète', exact: true }).click(); - await page.getByRole('heading', { name: 'Valentin Burgaud', exact: true }).waitFor(); + await page.getByRole('heading', { name: 'Exemple Fictif', exact: true }).waitFor(); assert.ok(await page.getByLabel('Email', { exact: true }).isDisabled()); assert.equal( await page.getByRole('group', { name: 'Rôles du compte', exact: true }).count(), diff --git a/frontend/tests/curricula-browser.mjs b/frontend/tests/curricula-browser.mjs new file mode 100644 index 0000000..e0706da --- /dev/null +++ b/frontend/tests/curricula-browser.mjs @@ -0,0 +1,674 @@ +/** Browser interactions against synthetic HTTP fixtures; API rights have PostgreSQL tests. */ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import { createServer as createViteServer } from 'vite'; +import { chromium } from 'playwright'; + +const colors = ['#4361EE', '#8B5CF6', '#0891B2', '#D97706', '#DB2777', '#059669', '#E05252']; +const names = [ + 'Analyser', + 'Modéliser', + 'Résoudre', + 'Expérimenter', + 'Communiquer', + 'Concevoir', + 'Réaliser' +]; +let sequence = 1; +function node(name, code, color = null) { + return { + id: sequence++, + name, + code, + color, + semester: null, + knowledge: null, + comment: null, + position: sequence + }; +} +const roots = names.map((name, i) => node(name, String.fromCharCode(65 + i), colors[i])); +const graph = { curriculum_id: 1, subject_id: 1, version: 0, nodes: [...roots], edges: [] }; +for (const root of roots) { + for (let i = 1; i <= 2; i++) { + const child = node(`${root.name} : compétence attendue ${i}`, `${root.code}${i}`); + const leaf = node(`Mettre en œuvre une démarche pour ${root.name.toLowerCase()}`, null); + leaf.semester = i; + leaf.knowledge = 'Connaissances associées au programme officiel.'; + graph.nodes.push(child, leaf); + graph.edges.push( + { parent_id: root.id, child_id: child.id }, + { parent_id: child.id, child_id: leaf.id } + ); + } +} +graph.edges.push({ parent_id: roots[1].id, child_id: graph.nodes[8].id }); +const catalog = { + can_manage: true, + curricula: [ + { + id: 1, + title: 'Programme PTSI / PT', + is_active: true, + version: 0, + source_url: 'https://education.gouv.fr/programme.pdf', + subject_ids: [1, 2, 3, 4] + }, + { + id: 2, + title: 'Autre référentiel', + is_active: true, + version: 0, + source_url: null, + subject_ids: [2] + } + ], + subjects: [ + { + id: 1, + name: 'Sciences industrielles de l’ingénieur', + icon: 'engineering', + color: colors[0], + is_active: true, + can_edit: true + }, + { + id: 2, + name: 'Mathématiques', + icon: 'calculator', + color: colors[1], + is_active: true, + can_edit: true + }, + { + id: 3, + name: 'Physique', + icon: 'engineering', + color: colors[2], + is_active: true, + can_edit: true + }, + { + id: 4, + name: 'Chimie', + icon: 'engineering', + color: colors[3], + is_active: true, + can_edit: true + } + ] +}; +const user = { + id: 1, + username: 'preview', + first_name: 'Camille', + last_name: 'Exemple', + roles: ['admin'], + permissions: ['users.manage', 'users.read', 'curricula.read', 'curricula.manage'], + is_bootstrap: false +}; +const errors = []; +const undoStack = []; +const backend = createServer(async (request, response) => { + response.setHeader('Content-Type', 'application/json'); + const path = request.url; + let result; + if (path === '/api/v1/auth/me') result = user; + else if (path === '/api/v1/site') + result = { + settings: { name: 'Sophikron', home_text: '', text_color: colors[0], version: 0 } + }; + else if (path === '/api/v1/curricula/catalog') result = catalog; + else if (path === '/api/v1/curricula' && request.method === 'POST') { + let body = ''; + for await (const chunk of request) body += chunk; + const input = JSON.parse(body); + assert.ok(!('track_id' in input)); + result = { id: 3, version: 0, ...input }; + catalog.curricula.push(result); + } else if (path === '/api/v1/curricula/1/subjects/1') result = graph; + else if (/^\/api\/v1\/curricula\/[123]\/subjects\/2$/.test(path)) + result = { + curriculum_id: Number(path.split('/')[4]), + subject_id: 2, + version: 0, + nodes: [node('Raisonner et démontrer', 'M')], + edges: [] + }; + else if (/^\/api\/v1\/curricula\/1\/subjects\/[34]$/.test(path)) + result = { + curriculum_id: 1, + subject_id: Number(path.split('/').at(-1)), + version: graph.version, + nodes: [], + edges: [] + }; + else if (request.method === 'POST' && /\/nodes$/.test(path)) { + undoStack.push(structuredClone(graph)); + let body = ''; + for await (const chunk of request) body += chunk; + const data = JSON.parse(body); + assert.ok(!('code' in data)); + const created = { ...node(data.name, 'A.3'), ...data }; + graph.nodes.push(created); + graph.edges.push(...data.parent_ids.map((id) => ({ parent_id: id, child_id: created.id }))); + graph.version++; + graph.can_undo = true; + result = graph; + } else if (request.method === 'PUT' && /\/nodes\/\d+$/.test(path)) { + undoStack.push(structuredClone(graph)); + let body = ''; + for await (const chunk of request) body += chunk; + const data = JSON.parse(body); + const target = graph.nodes.find((n) => n.id === Number(path.split('/').at(-1))); + Object.assign(target, data); + graph.edges = [ + ...graph.edges.filter((e) => e.child_id !== target.id), + ...data.parent_ids.map((id) => ({ parent_id: id, child_id: target.id })) + ]; + graph.version++; + graph.can_undo = true; + result = graph; + } else if (path === '/api/v1/curricula/1/undo') { + const previous = undoStack.pop(), + version = graph.version + 1; + Object.assign(graph, previous); + graph.version = version; + graph.can_undo = undoStack.length > 0; + result = graph; + } else if (path === '/api/v1/curricula/1/subjects/1/export') { + result = { + format: 'sophikron.competencies', + version: 1, + subject_name: catalog.subjects[0].name, + nodes: graph.nodes.map((item) => ({ + id: item.id, + name: item.name, + semester: item.semester, + knowledge: item.knowledge, + comment: item.comment ?? null, + color: item.color, + position: item.position, + parent_ids: graph.edges + .filter((edge) => edge.child_id === item.id) + .map((edge) => edge.parent_id) + })) + }; + } else if (path === '/api/v1/curricula/1/subjects/1/import') { + let body = ''; + for await (const chunk of request) body += chunk; + const input = JSON.parse(body), + document = JSON.parse(input.document); + assert.equal(input.expected_version, graph.version); + undoStack.push(structuredClone(graph)); + const mapped = new Map(document.nodes.map((item) => [item.id, sequence++])); + for (const item of document.nodes) { + graph.nodes.push({ ...item, id: mapped.get(item.id), code: 'Imported' }); + graph.edges.push( + ...item.parent_ids.map((parent) => ({ + parent_id: mapped.get(parent), + child_id: mapped.get(item.id) + })) + ); + } + graph.version++; + graph.can_undo = true; + result = graph; + } else { + response.statusCode = 404; + result = { detail: `Unknown fixture: ${path}` }; + } + response.end(JSON.stringify(result)); +}); +backend.listen(0, '127.0.0.1'); +await once(backend, 'listening'); +process.env.BACKEND_ORIGIN = `http://127.0.0.1:${backend.address().port}`; +const vite = await createViteServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'error' }); +await vite.listen(); +const origin = `http://127.0.0.1:${vite.httpServer.address().port}`; +process.env.ORIGIN = origin; +let browser; +try { + browser = await chromium.launch({ + headless: true, + ...(process.env.PLAYWRIGHT_CHANNEL ? { channel: process.env.PLAYWRIGHT_CHANNEL } : {}) + }); + const context = await browser.newContext({ viewport: { width: 1440, height: 1100 } }); + await context.addCookies([ + { name: 'sophikron_session_dev', value: 'a'.repeat(43), url: origin } + ]); + const page = await context.newPage(); + async function clickButton(locator) { + await locator.waitFor(); + if (!(await locator.evaluate((element) => !!element.closest('.graph-label')))) { + await locator.click(); + return; + } + await page.waitForTimeout(500); + let box = await locator.boundingBox(); + for (let attempt = 0; attempt < 25; attempt++) { + await page.waitForTimeout(80); + const next = await locator.boundingBox(); + assert.ok(box && next); + const settled = Math.abs(next.x - box.x) + Math.abs(next.y - box.y) < 0.6; + box = next; + if (settled) break; + } + assert.ok(box); + const unobstructed = await locator.evaluate((element) => { + const rect = element.getBoundingClientRect(); + return element.contains( + document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2) + ); + }); + if (!unobstructed) { + await locator.focus(); + await locator.press('Enter'); + return; + } + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + } + + page.on('pageerror', (error) => { + errors.push(error.message); + console.error(error.message); + }); + await page.goto(`${origin}/curricula`); + await page.locator('.master-title').first().waitFor(); + await page.waitForTimeout(800); + assert.equal(await page.locator('.master-title').count(), 4); + await page.waitForFunction( + (count) => + document.querySelector( + '[aria-label="Déplier Sciences industrielles de l’ingénieur"] span' + )?.textContent === String(count), + roots.length + ); + await clickButton( + page.getByRole('button', { name: 'Sciences industrielles de l’ingénieur', exact: true }) + ); + await page.waitForTimeout(900); + await page.locator('.node-title').first().waitFor(); + assert.equal(await page.locator('.node-title').count(), 7); + assert.deepEqual( + await page.locator('.graph-label').evaluateAll((labels) => + labels + .filter((label) => { + const outer = label.getBoundingClientRect(); + return [...label.querySelectorAll('.node-actions button')].some( + (button) => button.getBoundingClientRect().bottom > outer.bottom + 0.5 + ); + }) + .map((label) => label.dataset.nodeId) + ), + [], + 'Graph action buttons must stay within their frame.' + ); + await page.getByRole('button', { name: 'Plein écran', exact: true }).click(); + await page.waitForFunction(() => !!document.fullscreenElement); + await page.getByRole('button', { name: 'Quitter le plein écran', exact: true }).click(); + await page.waitForFunction(() => !document.fullscreenElement); + await page.getByRole('button', { name: 'Plein écran', exact: true }).click(); + await page.waitForFunction(() => !!document.fullscreenElement); + await page.evaluate(() => document.exitFullscreen()); + await page.getByRole('button', { name: 'Plein écran', exact: true }).waitFor(); + await clickButton(page.getByRole('button', { name: 'Vue textuelle', exact: true })); + const summary = page.getByRole('list', { + name: 'Sommaire de Sciences industrielles de l’ingénieur' + }); + assert.equal(await summary.locator('.text-node').count(), graph.nodes.length); + const summaryRows = await summary.locator('li').evaluateAll((items) => + items.slice(0, 2).map((item) => ({ + depth: Number(item.dataset.depth), + x: item.querySelector('button').getBoundingClientRect().x, + height: item.querySelector('button').getBoundingClientRect().height, + color: getComputedStyle(item.querySelector('button')).borderLeftColor + })) + ); + assert.equal(summaryRows[0].depth, 0); + assert.equal(summaryRows[1].depth, 1); + assert.ok(summaryRows[1].x > summaryRows[0].x); + assert.equal(summaryRows[1].color, summaryRows[0].color); + assert.ok(summaryRows.every((row) => row.height < 35)); + await clickButton(page.getByRole('button', { name: 'Vue graphique', exact: true })); + await clickButton(page.getByRole('button', { name: 'Déplier Analyser', exact: true })); + assert.equal(await page.locator('.node-title').count(), 9); + await clickButton( + page.getByRole('button', { name: 'Déplier Analyser : compétence attendue 1', exact: true }) + ); + assert.equal(await page.locator('.node-title').count(), 10); + const hierarchyStyles = await page.locator('.graph-label[data-depth]').evaluateAll((elements) => + elements.map((element) => ({ + depth: Number(element.dataset.depth), + scale: new DOMMatrix(getComputedStyle(element).transform).a, + filter: getComputedStyle(element).filter + })) + ); + const parentStyle = hierarchyStyles.find((item) => item.depth === 1); + const childStyle = hierarchyStyles.find((item) => item.depth === 2); + assert.ok( + childStyle.filter !== parentStyle.filter, + 'Descendants should use a quieter palette.' + ); + await clickButton( + page.getByRole('button', { name: 'Replier Analyser : compétence attendue 1', exact: true }) + ); + await page.waitForTimeout(500); + assert.equal(await page.locator('.node-title').count(), 9); + const viewport = await page.locator('.graph-space').boundingBox(); + await page.getByLabel('Rechercher une compétence').fill('Analyser : compétence attendue 1'); + assert.ok(await page.locator('.search-results .result-dot').count()); + assert.ok( + (await page.locator('.search-results small').first().textContent()).includes( + 'Sciences industrielles' + ) + ); + await page.locator('.search-results button').first().click(); + await page.waitForTimeout(500); + assert.ok((await page.locator('.graph-label.highlighted').count()) >= 3); + await page.waitForTimeout(10100); + assert.equal(await page.locator('.graph-label.highlighted').count(), 0); + await page.mouse.move(viewport.x + 70, viewport.y + 200); + const zoomBefore = Number(await page.locator('.graph-space').getAttribute('data-zoom')); + await page.mouse.wheel(0, -350); + await page.waitForFunction( + (z) => Number(document.querySelector('.graph-space').dataset.zoom) > z + 0.1, + zoomBefore + ); + const panBefore = Number(await page.locator('.graph-space').getAttribute('data-pan-x')); + await page.mouse.down(); + await page.mouse.move(viewport.x + 190, viewport.y + 250, { steps: 8 }); + await page.mouse.up(); + await page.waitForFunction( + (x) => Number(document.querySelector('.graph-space').dataset.panX) > x + 60, + panBefore + ); + await clickButton(page.getByRole('button', { name: 'Replier Analyser', exact: true })); + await clickButton(page.getByRole('button', { name: 'Déplier Analyser', exact: true })); + await page.waitForTimeout(900); + const automaticPan = Number(await page.locator('.graph-space').getAttribute('data-pan-x')); + const automaticZoom = Number(await page.locator('.graph-space').getAttribute('data-zoom')); + await clickButton(page.getByRole('button', { name: 'Recentrer', exact: true })); + await page.waitForTimeout(500); + assert.ok( + Math.abs( + Number(await page.locator('.graph-space').getAttribute('data-pan-x')) - automaticPan + ) < 2 + ); + assert.ok( + Math.abs( + Number(await page.locator('.graph-space').getAttribute('data-zoom')) - automaticZoom + ) < 0.01 + ); + await page.keyboard.press('Space'); + await page.waitForTimeout(700); + const centeredPan = Number(await page.locator('.graph-space').getAttribute('data-pan-x')); + await clickButton(page.getByRole('button', { name: 'Recentrer', exact: true })); + await page.waitForTimeout(700); + assert.ok( + Math.abs( + Number(await page.locator('.graph-space').getAttribute('data-pan-x')) - centeredPan + ) < 2 + ); + const label = page.locator('[data-node-id="1"]'); + const rest = await label.boundingBox(); + const title = await label.locator('.node-title').boundingBox(); + await page.mouse.move(title.x + title.width / 2, title.y + 5); + await page.mouse.down(); + await page.mouse.move(title.x + title.width / 2 + 110, title.y + 65, { steps: 10 }); + const displaced = await label.boundingBox(); + assert.ok(displaced.x > rest.x + 60, 'Node should follow the pointer while dragged.'); + await page.mouse.up(); + await page.waitForTimeout(2500); + const returned = await label.boundingBox(); + assert.ok( + Math.abs(returned.x - rest.x) < 25, + 'Released node should return towards its resting position.' + ); + await clickButton(page.getByRole('button', { name: 'Détails de Analyser', exact: true })); + assert.equal( + await page + .locator('details') + .filter({ has: page.locator('summary', { hasText: /^Semestre$/ }) }) + .getAttribute('open'), + null + ); + await page.getByText('Présentation', { exact: true }).click(); + const hex = page.getByLabel('Code couleur hexadécimal'); + await hex.fill('#aabbcc'); + assert.equal(await page.locator('#competency-color').inputValue(), '#aabbcc'); + await page.locator('#competency-color').fill('#112233'); + assert.equal(await hex.inputValue(), '#112233'); + const actionRows = await page + .locator('.competency-actions .button') + .evaluateAll((buttons) => + buttons.map((button) => Math.round(button.getBoundingClientRect().y)) + ); + assert.equal(new Set(actionRows).size, 1); + const actions = await page.locator('.competency-actions').evaluate((element) => ({ + left: element.getBoundingClientRect().left, + right: element.getBoundingClientRect().right, + buttons: [...element.querySelectorAll('button')].map((button) => ({ + left: button.getBoundingClientRect().left, + right: button.getBoundingClientRect().right + })) + })); + assert.ok(Math.abs(actions.buttons[0].left - actions.left) < 2); + assert.ok(Math.abs(actions.buttons.at(-1).right - actions.right) < 2); + assert.ok(actions.buttons[2].left - actions.buttons[1].right > 8); + await page.getByLabel('Nom', { exact: true }).fill('Analyser un système'); + await clickButton(page.getByRole('button', { name: 'Enregistrer', exact: true })); + await page.getByRole('dialog').waitFor({ state: 'detached' }); + assert.equal(graph.nodes[0].name, 'Analyser un système'); + await clickButton( + page.getByRole('button', { name: 'Ajouter sous Analyser un système', exact: true }) + ); + assert.equal(await page.getByLabel('Connaissances associées').isVisible(), false); + assert.equal(await page.getByLabel('Code facultatif').count(), 0); + await page.getByLabel('Nom', { exact: true }).fill('Créée avec Entrée'); + await page.getByLabel('Nom', { exact: true }).press('Enter'); + await page.getByRole('dialog').waitFor({ state: 'detached' }); + assert.ok(graph.nodes.some((node) => node.name === 'Créée avec Entrée')); + await page.getByRole('button', { name: 'Déplier Créée avec Entrée', exact: true }).waitFor(); + assert.equal( + await page.getByRole('button', { name: 'A.3 Créée avec Entrée', exact: true }).count(), + 1 + ); + await page.keyboard.press('Control+z'); + await page.waitForTimeout(600); + assert.ok(!graph.nodes.some((node) => node.name === 'Créée avec Entrée')); + await page.getByRole('button', { name: 'Annuler l’action (Ctrl+Z)', exact: true }).click(); + await page.waitForTimeout(500); + assert.equal(graph.nodes[0].name, 'Analyser'); + await page + .getByRole('button', { name: 'Isoler Sciences industrielles de l’ingénieur', exact: true }) + .click(); + await page.waitForTimeout(500); + assert.equal(await page.locator('.master-title').count(), 1); + await page.getByRole('button', { name: 'Tout afficher', exact: true }).click(); + await page.waitForTimeout(500); + assert.equal(await page.locator('.master-title').count(), 4); + async function assertVisibleLabels() { + assert.deepEqual( + await page + .locator('.graph-label') + .evaluateAll((elements) => + elements + .filter((element) => Number(getComputedStyle(element).opacity) < 0.99) + .map((element) => element.dataset.nodeId) + ), + [], + 'Every restored label must remain opaque after its transition.' + ); + } + await assertVisibleLabels(); + for (let i = 0; i < 3; i++) { + await page + .getByRole('button', { + name: 'Isoler Sciences industrielles de l’ingénieur', + exact: true + }) + .click(); + await page.waitForTimeout(60); + await page.getByRole('button', { name: 'Tout afficher', exact: true }).click(); + } + await page.waitForTimeout(900); + await assertVisibleLabels(); + await page.getByRole('button', { name: 'Masquer Physique', exact: true }).click(); + await page.waitForTimeout(40); + await page.getByRole('button', { name: 'Afficher Physique', exact: true }).click(); + await page.waitForTimeout(900); + await assertVisibleLabels(); + assert.equal(await page.locator('.master-title').count(), 4); + const sizes = await page + .locator('.graph-label') + .evaluateAll((elements) => + elements.map((element) => element.getBoundingClientRect().width) + ); + assert.ok( + Math.min(...sizes) > 40, + 'Four subjects and an expanded branch should remain readable.' + ); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.getByRole('button', { name: 'Isoler Chimie', exact: true }).click(); + await page.waitForTimeout(50); + await page.getByRole('button', { name: 'Tout afficher', exact: true }).click(); + await page.waitForTimeout(100); + await assertVisibleLabels(); + assert.equal(await page.locator('.master-title').count(), 4); + await page.emulateMedia({ reducedMotion: 'no-preference' }); + if (process.env.CURRICULA_SCREENSHOT) { + await clickButton(page.getByRole('button', { name: 'B Modéliser', exact: true })); + await page.waitForTimeout(2500); + await page.screenshot({ path: process.env.CURRICULA_SCREENSHOT, fullPage: true }); + } + await clickButton(page.getByRole('button', { name: 'Mathématiques', exact: true })); + await page.getByRole('button', { name: 'M Raisonner et démontrer', exact: true }).waitFor(); + assert.equal(await page.locator('.master-title').count(), 4); + await page.getByRole('button', { name: 'Exporter les compétences', exact: true }).click(); + const downloadPromise = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Télécharger', exact: true }).click(); + const download = await downloadPromise; + assert.equal(download.suggestedFilename(), `${catalog.subjects[0].name}.json`); + const stream = await download.createReadStream(); + const chunks = []; + for await (const chunk of stream) chunks.push(chunk); + const exported = JSON.parse(Buffer.concat(chunks).toString('utf8')); + assert.equal(exported.nodes.length, graph.nodes.length); + assert.equal(exported.format, 'sophikron.competencies'); + await page.getByRole('button', { name: 'Importer des compétences', exact: true }).click(); + await page + .getByRole('dialog') + .locator('input[type=file]') + .setInputFiles({ + name: 'bad.json', + mimeType: 'application/json', + buffer: Buffer.from('not json') + }); + assert.ok(await page.getByRole('alert').isVisible()); + assert.ok(await page.getByRole('button', { name: 'Importer', exact: true }).isDisabled()); + exported.nodes[0].comment = 'n'.repeat(10000); + exported.nodes[1].comment = 'n'.repeat(10000); + await page.getByRole('group', { name: 'Dépôt de document' }).evaluate((element, content) => { + const transfer = new DataTransfer(); + transfer.items.add(new File([content], 'competences.json', { type: 'application/json' })); + element.dispatchEvent( + new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: transfer }) + ); + }, JSON.stringify(exported)); + await page.getByText('competences.json', { exact: true }).waitFor(); + const initialCount = graph.nodes.length; + await page.getByRole('button', { name: 'Importer', exact: true }).click(); + await page.getByRole('dialog').waitFor({ state: 'detached' }); + assert.equal(graph.nodes.length, initialCount * 2); + await page.getByRole('button', { name: 'Annuler l’action (Ctrl+Z)', exact: true }).click(); + await page.waitForTimeout(600); + assert.equal(graph.nodes.length, initialCount); + await page.getByLabel('Référentiel', { exact: true }).selectOption('2'); + await clickButton(page.getByRole('button', { name: 'Mathématiques', exact: true })); + await page.getByRole('button', { name: 'M Raisonner et démontrer', exact: true }).waitFor(); + assert.equal(await page.locator('.node-title').count(), 1); + await page.setViewportSize({ width: 390, height: 844 }); + await page.locator('.text-node').waitFor({ state: 'visible' }); + assert.equal(await page.locator('.text-node').count(), 1); + assert.equal(await page.getByRole('button', { name: 'Vue graphique', exact: true }).count(), 0); + assert.ok(!(await page.locator('.graph-space').isVisible())); + assert.equal( + await page.getByRole('button', { name: 'Ajouter une compétence', exact: true }).count(), + 0 + ); + await page.locator('.text-subject button').click(); + await page.getByRole('dialog').waitFor(); + assert.equal(await page.getByLabel('Nom', { exact: true }).inputValue(), ''); + await page.getByRole('button', { name: 'Annuler', exact: true }).click(); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.setViewportSize({ width: 1440, height: 1100 }); + await page.getByRole('button', { name: 'M Raisonner et démontrer', exact: true }).waitFor(); + await page.locator('.graph-space canvas').waitFor({ state: 'visible' }); + const mobilePage = await context.newPage(); + mobilePage.on('pageerror', (error) => errors.push(error.message)); + await mobilePage.setViewportSize({ width: 390, height: 844 }); + await mobilePage.addInitScript(() => { + window.__curriculumGlCalls = 0; + const original = HTMLCanvasElement.prototype.getContext; + HTMLCanvasElement.prototype.getContext = function (kind, ...options) { + if (kind === 'webgl2' || kind === 'webgl') { + window.__curriculumGlCalls++; + return null; + } + return original.call(this, kind, ...options); + }; + }); + await mobilePage.goto(`${origin}/curricula`); + await mobilePage.locator('.text-node').first().waitFor(); + assert.equal(await mobilePage.evaluate(() => window.__curriculumGlCalls), 0); + assert.equal( + await mobilePage.getByRole('button', { name: 'Vue graphique', exact: true }).count(), + 0 + ); + await mobilePage.close(); + await page.getByRole('button', { name: 'Nouveau référentiel', exact: true }).click(); + assert.equal(await page.getByLabel('Filière', { exact: true }).count(), 0); + await page.getByLabel('Nom du référentiel').fill('PCSI / PC'); + await page.getByLabel('Description', { exact: true }).fill('Programme de deux années'); + await page.locator('.subject-choice').filter({ hasText: 'Mathématiques' }).click(); + await page.getByRole('button', { name: 'Enregistrer', exact: true }).click(); + await page.getByRole('dialog').waitFor({ state: 'detached' }); + await page.waitForFunction( + () => document.querySelector('[aria-label="Référentiel"]').value === '3' + ); + assert.equal(catalog.curricula.at(-1).description, 'Programme de deux années'); + // Exercise the reader UI and a device without WebGL using the same synthetic catalogue. + user.roles = ['kholleur']; + user.permissions = ['kholleur.access', 'curricula.read']; + catalog.can_manage = false; + catalog.subjects.forEach((subject) => (subject.can_edit = false)); + const reader = await context.newPage(); + reader.on('pageerror', (error) => errors.push(error.message)); + await reader.addInitScript(() => { + const original = HTMLCanvasElement.prototype.getContext; + HTMLCanvasElement.prototype.getContext = function (kind, ...options) { + return kind === 'webgl2' || kind === 'webgl' + ? null + : original.call(this, kind, ...options); + }; + }); + await reader.goto(`${origin}/curricula`); + await reader.locator('.text-subject h3').first().waitFor(); + assert.equal(await reader.locator('.text-subject button').count(), 0); + await reader.locator('.text-node').first().waitFor(); + assert.equal(await reader.getByRole('button', { name: 'Nouveau référentiel' }).count(), 0); + assert.equal(await reader.getByRole('button', { name: 'Compétence racine' }).count(), 0); + await reader.locator('.text-node').first().click(); + assert.ok(await reader.getByLabel('Nom', { exact: true }).isDisabled()); + assert.deepEqual(errors, []); + console.log( + 'Browser: expansion, editing, subject/programme switching, mobile and reduced motion passed.' + ); +} finally { + await browser?.close(); + await vite.close(); + await new Promise((resolve) => backend.close(resolve)); +} diff --git a/frontend/tests/curricula.test.ts b/frontend/tests/curricula.test.ts new file mode 100644 index 0000000..4e1f4d5 --- /dev/null +++ b/frontend/tests/curricula.test.ts @@ -0,0 +1,451 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + ancestors, + descendants, + compareCodes, + competencyAppearance, + competencyFileName, + competencyOutline, + competencyLinkPath, + competencyColors, + layoutGraph, + type GraphPoint, + type CompetencyGraph, + type Competency +} from '../src/lib/curricula.ts'; + +function node(id: number): Competency { + return { + id, + name: String(id), + code: null, + semester: null, + knowledge: null, + comment: null, + color: null, + position: id + }; +} +const graph: CompetencyGraph = { + curriculum_id: 1, + subject_id: 1, + version: 0, + nodes: [node(1), node(2), node(3), node(4)], + edges: [ + { parent_id: 1, child_id: 3 }, + { parent_id: 2, child_id: 3 }, + { parent_id: 3, child_id: 4 } + ] +}; + +test('JSON downloads use the subject name with safe portable filename characters', () => { + assert.equal(competencyFileName('Mathématiques'), 'Mathématiques.json'); + assert.equal(competencyFileName('SII / PTSI:PT'), 'SII _ PTSI_PT.json'); + assert.equal(competencyFileName('CON'), '_CON.json'); + assert.equal(competencyFileName(' ... '), 'competences.json'); + assert.equal(competencyFileName('SII\\PT\u0000'), 'SII_PT_.json'); +}); + +test('collapse hides descendants and shared competencies are rendered only once', () => { + assert.deepEqual( + new Set(layoutGraph(graph, new Set(), '#4361EE').map((p) => p.id)), + new Set([1, 2]) + ); + const points = layoutGraph(graph, new Set([1, 2, 3]), '#4361EE'); + assert.equal(points.length, 4); + assert.equal(points.filter((p) => p.id === 3).length, 1); + assert.ok(points.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))); +}); +test('search reveals every ancestor path of a shared node', () => { + assert.deepEqual(ancestors(4, graph.edges), new Set([1, 2, 3, 4])); + assert.deepEqual(descendants(1, graph.edges), new Set([1, 3, 4])); +}); + +test('automatic codes sort by hierarchy instead of lexical string order', () => { + assert.deepEqual(['AA', 'A.10', 'A.2', 'Z', 'B', 'A.1.a'].sort(compareCodes), [ + 'A.1.a', + 'A.2', + 'A.10', + 'B', + 'Z', + 'AA' + ]); +}); +test('explicit colors override inherited branch and subject colors', () => { + const colored = { + ...graph, + nodes: graph.nodes.map((n) => ({ ...n, color: n.id === 1 ? '#FF0000' : null })) + }; + const points = layoutGraph(colored, new Set([1]), '#0000FF'); + assert.equal(points.find((p) => p.id === 3)?.color, '#FF0000'); + assert.equal(points.find((p) => p.id === 2)?.color, '#0000FF'); + const colors = competencyColors(colored, '#0000FF'); + assert.equal(colors.get(3), '#FF0000'); + assert.equal(colors.get(4), '#FF0000'); + assert.equal(colors.get(2), '#0000FF'); +}); + +function dimensions(point: GraphPoint): { width: number; height: number } { + const scale = competencyAppearance(point.depth).scale; + return point.id < 0 ? { width: 205, height: 80 } : { width: 142 * scale, height: 60 * scale }; +} + +const fourSubjects: CompetencyGraph = { + ...graph, + nodes: [-1, -2, -3, -4, ...Array.from({ length: 10 }, (_, i) => i + 1)].map(node), + edges: [ + ...Array.from({ length: 7 }, (_, i) => ({ parent_id: -1, child_id: i + 1 })), + { parent_id: 1, child_id: 8 }, + { parent_id: 1, child_id: 9 }, + { parent_id: 8, child_id: 10 } + ] +}; + +test('four subjects pack compactly around one expanded graph without overlapping blocks', () => { + const points = layoutGraph(fourSubjects, new Set([-1, 1, 8]), '#4361EE'); + assert.equal(points.length, 14); + const width = + Math.max(...points.map((p) => p.x + dimensions(p).width / 2)) - + Math.min(...points.map((p) => p.x - dimensions(p).width / 2)); + const height = + Math.max(...points.map((p) => p.y + dimensions(p).height / 2)) - + Math.min(...points.map((p) => p.y - dimensions(p).height / 2)); + assert.ok(width < 1400 && height < 1000, `Compact layout expected, got ${width} by ${height}.`); + for (let i = 0; i < points.length; i++) + for (let j = 0; j < i; j++) { + const a = points[i], + b = points[j]; + assert.ok( + Math.abs(a.x - b.x) >= (dimensions(a).width + dimensions(b).width) / 2 + 4 || + Math.abs(a.y - b.y) >= (dimensions(a).height + dimensions(b).height) / 2 + 4, + `Blocks ${a.id} and ${b.id} overlap.` + ); + } +}); + +test('subject packing follows the viewport and restoring a hidden subject is deterministic', () => { + const collapsed = { + ...fourSubjects, + nodes: fourSubjects.nodes.filter((n) => n.id < 0), + edges: [] + }; + const landscape = layoutGraph(collapsed, new Set(), '#4361EE', 2.5); + const portrait = layoutGraph(collapsed, new Set(), '#4361EE', 0.5); + const range = (points: GraphPoint[], axis: 'x' | 'y'): number => + Math.max(...points.map((p) => p[axis])) - Math.min(...points.map((p) => p[axis])); + assert.ok(range(landscape, 'x') > range(portrait, 'x')); + assert.ok(range(landscape, 'y') < range(portrait, 'y')); + const full = layoutGraph(fourSubjects, new Set([-1, 1]), '#4361EE'); + layoutGraph( + { ...fourSubjects, nodes: fourSubjects.nodes.filter((n) => n.id !== -2) }, + new Set([-1, 1]), + '#4361EE' + ); + assert.deepEqual(layoutGraph(fourSubjects, new Set([-1, 1]), '#4361EE'), full); +}); + +test('deep levels stay smaller, quieter and slightly further apart with bounded styling', () => { + const root = competencyAppearance(1), + child = competencyAppearance(2), + leaf = competencyAppearance(3), + deep = competencyAppearance(100); + assert.ok(root.scale > child.scale && child.scale > leaf.scale); + assert.ok(root.saturation > child.saturation && child.saturation > leaf.saturation); + assert.ok(child.spacing > root.spacing && leaf.spacing > child.spacing); + assert.ok(deep.scale >= 0.8 && deep.saturation >= 0.6 && deep.spacing <= 30); +}); + +const balancedTree: CompetencyGraph = { + ...graph, + nodes: [ + node(-1), + ...Array.from({ length: 7 }, (_, i) => ({ ...node(i + 1), code: String.fromCharCode(65 + i) })), + ...Array.from({ length: 35 }, (_, i) => ({ + ...node(100 + i), + code: String.fromCharCode(65 + Math.floor(i / 5)) + '.' + ((i % 5) + 1) + })) + ], + edges: [ + ...Array.from({ length: 7 }, (_, i) => ({ parent_id: -1, child_id: i + 1 })), + ...Array.from({ length: 35 }, (_, i) => ({ + parent_id: Math.floor(i / 5) + 1, + child_id: 100 + i + })) + ] +}; +test('seven expanded families keep ordered siblings, disjoint blocks and uncrossed tree links', () => { + const points = layoutGraph(balancedTree, new Set([-1, 1, 2, 3, 4, 5, 6, 7]), '#4361EE'); + const byId = new Map(points.map((p) => [p.id, p])); + + for (let id = 1; id <= 7; id++) { + const kids = Array.from({ length: 5 }, (_, i) => byId.get(100 + (id - 1) * 5 + i)!); + for (let i = 1; i < kids.length; i++) + assert.ok( + kids[i].angle! > kids[i - 1].angle!, + 'Siblings keep their code order around their ring.' + ); + assert.ok(kids.every((p) => Math.abs(p.radius! - kids[0].radius!) < 0.001)); + } + + for (let i = 0; i < points.length; i++) + for (let j = 0; j < i; j++) { + const a = points[i], + b = points[j]; + assert.ok( + Math.abs(a.x - b.x) >= (dimensions(a).width + dimensions(b).width) / 2 + 4 || + Math.abs(a.y - b.y) >= (dimensions(a).height + dimensions(b).height) / 2 + 4, + 'Reserved regions must keep blocks apart.' + ); + } + + const intersects = ( + a: { x: number; y: number }, + b: { x: number; y: number }, + node: GraphPoint + ): boolean => { + const box = dimensions(node); + let lo = 0, + hi = 1; + for (const axis of ['x', 'y'] as const) { + const half = (axis === 'x' ? box.width : box.height) / 2 - 1, + d = b[axis] - a[axis], + start = a[axis] - node[axis]; + if (Math.abs(d) < 1e-9) { + if (Math.abs(start) >= half) return false; + continue; + } + const v = (-half - start) / d, + w = (half - start) / d; + lo = Math.max(lo, Math.min(v, w)); + hi = Math.min(hi, Math.max(v, w)); + if (lo >= hi) return false; + } + return true; + }; + for (const edge of balancedTree.edges) { + const path = competencyLinkPath(byId.get(edge.parent_id)!, byId.get(edge.child_id)!); + for (let i = 1; i < path.length; i++) + for (const block of points) { + if (block.id === edge.parent_id || block.id === edge.child_id) continue; + assert.ok( + !intersects(path[i - 1], path[i], block), + 'Links must avoid other families and siblings.' + ); + } + } + + const width = Math.max(...points.map((p) => p.x)) - Math.min(...points.map((p) => p.x)) + 205; + const paths = balancedTree.edges.map((edge) => ({ + edge, + path: competencyLinkPath(byId.get(edge.parent_id)!, byId.get(edge.child_id)!) + })); + const side = ( + a: { x: number; y: number }, + b: { x: number; y: number }, + c: { x: number; y: number } + ): number => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + for (let i = 0; i < paths.length; i++) + for (let j = 0; j < i; j++) { + const a = paths[i], + b = paths[j]; + if ( + [a.edge.parent_id, a.edge.child_id].some( + (id) => id === b.edge.parent_id || id === b.edge.child_id + ) + ) + continue; + for (let x = 1; x < a.path.length; x++) + for (let y = 1; y < b.path.length; y++) { + const p = a.path[x - 1], + q = a.path[x], + r = b.path[y - 1], + s = b.path[y]; + assert.ok( + !(side(p, q, r) * side(p, q, s) < -0.001 && side(r, s, p) * side(r, s, q) < -0.001), + 'Links belonging to separate families must not cross.' + ); + } + } + const height = Math.max(...points.map((p) => p.y)) - Math.min(...points.map((p) => p.y)) + 80; + assert.ok(width * height < 2200000, 'The seven-by-five tree must remain compact.'); +}); +test('expanding more branches rebalances existing anchors regardless of expansion history', () => { + const partial = layoutGraph(balancedTree, new Set([-1, 1]), '#4361EE'); + const full = layoutGraph(balancedTree, new Set([-1, 1, 2, 3, 4, 5, 6, 7]), '#4361EE'); + assert.ok( + partial.some((p) => { + const q = full.find((q) => q.id === p.id)!; + return Math.hypot(q.x - p.x, q.y - p.y) > 2; + }) + ); + assert.deepEqual(layoutGraph(balancedTree, new Set([7, 6, 5, 4, 3, 2, 1, -1]), '#4361EE'), full); +}); + +test('deep chains and wide families have bounded spacing and ignore hidden descendants', () => { + const deep = { + ...graph, + nodes: Array.from({ length: 50 }, (_, i) => node(i + 1)), + edges: Array.from({ length: 49 }, (_, i) => ({ parent_id: i + 1, child_id: i + 2 })) + }; + const initial = layoutGraph(deep, new Set([1]), '#4361EE'); + assert.equal(initial.length, 2); + assert.ok(Math.hypot(initial[1].x - initial[0].x, initial[1].y - initial[0].y) < 300); + const expanded = layoutGraph(deep, new Set(deep.nodes.map((n) => n.id)), '#4361EE'); + assert.ok(expanded.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))); + for (const p of expanded) + if (p.parentId) { + const parent = expanded.find((q) => q.id === p.parentId)!; + assert.ok(Math.hypot(p.x - parent.x, p.y - parent.y) < 300); + } +}); + +test('seven roots form a circle and opening a second family reflows the first one', () => { + const initial = layoutGraph(balancedTree, new Set([-1]), '#4361EE'); + const root = initial.find((p) => p.id === -1)!; + const roots = initial.filter((p) => p.id > 0); + assert.equal(roots.length, 7); + const distances = roots.map((p) => Math.hypot(p.x - root.x, p.y - root.y)); + assert.ok(Math.max(...distances) - Math.min(...distances) < 0.001); + assert.ok( + roots.some((p) => p.x > root.x + 100) && + roots.some((p) => p.x < root.x - 100) && + roots.some((p) => p.y > root.y + 100) && + roots.some((p) => p.y < root.y - 100) + ); + const first = layoutGraph(balancedTree, new Set([-1, 1]), '#4361EE'), + second = layoutGraph(balancedTree, new Set([-1, 1, 2]), '#4361EE'); + assert.ok( + first + .filter((p) => p.parentId === 1) + .some((p) => { + const other = second.find((q) => q.id === p.id)!; + return Math.abs(p.angle! - other.angle!) > 0.01; + }), + 'The first open family must share space with the newly opened family.' + ); + for (const layout of [first, second]) + for (let i = 0; i < layout.length; i++) + for (let j = 0; j < i; j++) { + const a = layout[i], + b = layout[j]; + assert.ok( + Math.abs(a.x - b.x) >= (dimensions(a).width + dimensions(b).width) / 2 + 4 || + Math.abs(a.y - b.y) >= (dimensions(a).height + dimensions(b).height) / 2 + 4 + ); + } + for (const point of second.filter((p) => p.depth > 1)) { + const parent = second.find((p) => p.id === point.parentId)!; + assert.ok(point.radius! > parent.radius!); + assert.ok(point.radius! - parent.radius! <= 231); + } +}); + +test('opening a grandchild redistributes space with another already-open family and collapse restores it', () => { + const deep = { + ...balancedTree, + nodes: [...balancedTree.nodes, ...Array.from({ length: 5 }, (_, i) => node(200 + i))], + edges: [ + ...balancedTree.edges, + ...Array.from({ length: 5 }, (_, i) => ({ parent_id: 100, child_id: 200 + i })) + ] + }; + const before = layoutGraph(deep, new Set([-1, 1, 2]), '#4361EE'), + after = layoutGraph(deep, new Set([-1, 1, 2, 100]), '#4361EE'); + assert.ok( + before + .filter((p) => p.parentId === 2) + .some((p) => Math.abs(p.angle! - after.find((q) => q.id === p.id)!.angle!) > 0.001) + ); + assert.ok( + after + .filter((p) => p.id >= 200) + .every((p) => p.radius! > after.find((q) => q.id === 100)!.radius!) + ); + for (let i = 0; i < after.length; i++) + for (let j = 0; j < i; j++) { + const a = after[i], + b = after[j]; + assert.ok( + Math.abs(a.x - b.x) >= (dimensions(a).width + dimensions(b).width) / 2 + 4 || + Math.abs(a.y - b.y) >= (dimensions(a).height + dimensions(b).height) / 2 + 4 + ); + } + assert.deepEqual(layoutGraph(deep, new Set([-1, 1, 2]), '#4361EE'), before); +}); + +test('links connect block borders directly even when the blocks occupy different ring angles', () => { + const parent: GraphPoint = { + id: 1, + x: 250, + y: 0, + radius: 250, + orbitX: 0, + orbitY: 0, + depth: 1, + color: '#4361EE' + }; + const child: GraphPoint = { + id: 2, + parentId: 1, + x: 440 * Math.cos(0.6), + y: 440 * Math.sin(0.6), + radius: 440, + orbitX: 0, + orbitY: 0, + depth: 2, + color: '#4361EE' + }; + const path = competencyLinkPath(parent, child); + assert.equal(path.length, 2); + for (const point of path) + assert.ok( + Math.abs( + (point.x - parent.x) * (child.y - parent.y) - (point.y - parent.y) * (child.x - parent.x) + ) < 1e-6 + ); + for (const [index, node] of [parent, child].entries()) { + const box = dimensions(node), + point = path[index]; + assert.ok( + Math.abs( + Math.max( + Math.abs(point.x - node.x) / (box.width / 2), + Math.abs(point.y - node.y) / (box.height / 2) + ) - 1 + ) < 1e-6 + ); + } + assert.ok( + Math.hypot(path[1].x - path[0].x, path[1].y - path[0].y) < + Math.hypot(child.x - parent.x, child.y - parent.y) + ); +}); + +test('the text outline groups descendants immediately under their parent and inherits branch colors', () => { + const input = { + ...graph, + nodes: [ + { ...node(4), code: 'B' }, + { ...node(3), code: 'A.1.a' }, + { ...node(2), code: 'A.1' }, + { ...node(1), code: 'A', color: '#aa2244' } + ], + edges: [ + { parent_id: 1, child_id: 2 }, + { parent_id: 2, child_id: 3 } + ] + }; + const rows = competencyOutline(input, '#4361EE'); + assert.deepEqual( + rows.map((row) => row.node.id), + [1, 2, 3, 4] + ); + assert.deepEqual( + rows.map((row) => row.depth), + [0, 1, 2, 0] + ); + assert.equal(rows[2].color, '#aa2244'); + assert.equal(rows[2].parentColor, '#aa2244'); + assert.equal(competencyOutline(graph, '#4361EE').filter((row) => row.node.id === 3).length, 1); +}); diff --git a/frontend/tests/curriculum-motion.test.ts b/frontend/tests/curriculum-motion.test.ts new file mode 100644 index 0000000..7d04490 --- /dev/null +++ b/frontend/tests/curriculum-motion.test.ts @@ -0,0 +1,113 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { resolveCollisions, stepFloatingNode } from '../src/lib/curriculumMotion.ts'; +import { + programmeScene, + layoutGraph, + type CurriculumSubject, + type CompetencyGraph +} from '../src/lib/curricula.ts'; + +test('dragged nodes stay pinned and return gently towards their anchor after release', () => { + const node = { x: 180, y: 90, vx: 0, vy: 0, pinned: true }; + const anchor = { id: 1, x: 0, y: 0 }; + stepFloatingNode(node, anchor, 0, 1 / 60, false); + assert.equal(node.x, 180); + node.pinned = false; + stepFloatingNode(node, anchor, 0, 1 / 60, false); + assert.ok(node.x < 180 && node.x > 170); + for (let i = 1; i < 300; i++) stepFloatingNode(node, anchor, i / 60, 1 / 60, false); + assert.ok(Math.hypot(node.x, node.y) < 8); + stepFloatingNode(node, anchor, 8, 1 / 60, true); + assert.equal(node.x, 0); + assert.equal(node.y, 0); +}); + +test('collisions push neighbours away without moving the dragged node', () => { + const pinned = { x: 0, y: 0, vx: 0, vy: 0, pinned: true }; + const neighbour = { x: 15, y: 0, vx: 0, vy: 0, pinned: false }; + resolveCollisions([ + { id: 1, state: pinned, width: 140, height: 60 }, + { id: 2, state: neighbour, width: 140, height: 60 } + ]); + assert.equal(pinned.x, 0); + assert.equal(pinned.y, 0); + assert.equal(neighbour.x, 15); + assert.ok(neighbour.vx > 25, 'A nearby block should receive a noticeable magnetic impulse.'); + for (let i = 0; i < 600; i++) { + resolveCollisions( + [ + { id: 1, state: pinned, width: 140, height: 60 }, + { id: 2, state: neighbour, width: 140, height: 60 } + ], + Math.exp((-i / 60) * 2.5) + ); + stepFloatingNode(neighbour, { id: 2, x: -180, y: 0 }, i / 60, 1 / 60, false); + } + assert.ok(Math.abs(neighbour.x + 180) < 8); +}); + +test('an isolated subject spreads its children around a circle', () => { + const scene = { + curriculum_id: 1, + subject_id: 1, + version: 0, + nodes: [-1, 1, 2, 3, 4].map((id) => ({ + id, + name: String(id), + code: null, + color: null, + semester: null, + knowledge: null, + comment: null, + position: id + })), + edges: [1, 2, 3, 4].map((id) => ({ parent_id: -1, child_id: id })) + }; + const points = layoutGraph(scene, new Set([-1]), '#4361EE'); + assert.equal(points.length, 5); + assert.ok(points.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))); + const root = points.find((p) => p.id === -1)!; + const children = points.filter((p) => p.id > 0); + const distances = children.map((p) => Math.hypot(p.x - root.x, p.y - root.y)); + assert.ok(Math.max(...distances) - Math.min(...distances) < 0.001); + assert.ok(children.some((p) => p.x > root.x + 100) && children.some((p) => p.x < root.x - 100)); +}); + +test('subjects are master nodes and their competency roots appear only after expansion', () => { + const subject: CurriculumSubject = { + id: 1, + name: 'SII', + icon: 'engineering', + color: '#4361EE', + is_active: true, + can_edit: true + }; + const graph: CompetencyGraph = { + curriculum_id: 1, + subject_id: 1, + version: 0, + nodes: [ + { + id: 7, + name: 'Analyser', + code: 'A', + color: null, + semester: null, + comment: null, + knowledge: null, + position: 0 + } + ], + edges: [] + }; + const scene = programmeScene([subject], { 1: graph }); + assert.deepEqual( + layoutGraph(scene, new Set(), '#4361EE').map((p) => p.id), + [-1] + ); + assert.deepEqual( + new Set(layoutGraph(scene, new Set([-1]), '#4361EE').map((p) => p.id)), + new Set([-1, 7]) + ); +}); diff --git a/frontend/tests/establishment.mjs b/frontend/tests/establishment.mjs index 48cd963..311a8fc 100644 --- a/frontend/tests/establishment.mjs +++ b/frontend/tests/establishment.mjs @@ -85,7 +85,7 @@ test('one production build renders different runtime names and escapes HTML in t for (const [configured, expected] of [ [undefined, 'Sophikron'], [' \t ', 'Sophikron'], - [' Lycée Jean Moulin ', 'Lycée Jean Moulin'], + [' Lycée Exemple ', 'Lycée Exemple'], [ 'École d’Art & "Sciences" ', 'École d’Art & "Sciences" ' diff --git a/frontend/tests/fixtures/DirectoryHarness.svelte b/frontend/tests/fixtures/DirectoryHarness.svelte index 5d44732..38ae248 100644 --- a/frontend/tests/fixtures/DirectoryHarness.svelte +++ b/frontend/tests/fixtures/DirectoryHarness.svelte @@ -16,10 +16,10 @@ const profile: FullProfile = { activity: { created_at: '2026-01-01T00:00:00Z', last_login_at: null, login_count: 0 }, id: 3, - username: 'alice123', - first_name: 'Alice', - last_name: 'Martin', - email: 'martin.alice@test.fr', + username: 'alpha123', + first_name: 'Alpha', + last_name: 'Specimen', + email: 'specimen.alpha@example.org', roles: [memberRole], status: archived ? 'disabled' : 'active', profile_version: 0, diff --git a/frontend/tests/fixtures/HeaderHarness.svelte b/frontend/tests/fixtures/HeaderHarness.svelte index 1a45845..a0e2577 100644 --- a/frontend/tests/fixtures/HeaderHarness.svelte +++ b/frontend/tests/fixtures/HeaderHarness.svelte @@ -9,9 +9,9 @@ ? null : { id: 1, - username: 'valentin123', - first_name: 'Valentin', - last_name: 'Burgaud', + username: 'exemple123', + first_name: 'Exemple', + last_name: 'Fictif', email: null, status: 'active', roles: role === 'admin' ? ['admin', 'teacher'] : [role], diff --git a/frontend/tests/fixtures/LessonHarness.svelte b/frontend/tests/fixtures/LessonHarness.svelte index c635279..ffe6efd 100644 --- a/frontend/tests/fixtures/LessonHarness.svelte +++ b/frontend/tests/fixtures/LessonHarness.svelte @@ -70,10 +70,10 @@ icon: 'calculator', color: '#244bc1', creator: { id: 99, label: 'Créateur historique', role: 'teacher', can_edit: false }, - responsible: { id: 1, label: 'Camille Martin', role: 'teacher', can_edit: true }, + responsible: { id: 1, label: 'Compte Specimen', role: 'teacher', can_edit: true }, collaborators: [ - { id: 2, label: 'Alice Durand', role: 'teacher', can_edit: true }, - { id: 3, label: 'Zoé Bernard', role: 'kholleur', can_edit: false } + { id: 2, label: 'Alpha Fictice', role: 'teacher', can_edit: true }, + { id: 3, label: 'Zêta Temoin', role: 'kholleur', can_edit: false } ], can_open: true, can_edit: true, diff --git a/frontend/tests/journey.mjs b/frontend/tests/journey.mjs index eec3008..4123b33 100644 --- a/frontend/tests/journey.mjs +++ b/frontend/tests/journey.mjs @@ -79,8 +79,8 @@ for (const suppliedOrigin of [null, 'https://evil.example']) { expectRedirect(await login('verification_setup', bootstrap), '/'); expectRedirect(await request('/admin/users/new'), '/setup'); const setup = await request('/setup', { - first_name: 'Alice', - last_name: 'Martin', + first_name: 'Alpha', + last_name: 'Specimen', email: 'owner@example.org', password, confirmation: password @@ -104,7 +104,7 @@ expectRedirect(await request('/login?next=https%3A%2F%2Fevil.example'), '/'); assert.equal((await request('/dashboard')).status, 200); expectRedirect(await request('/admin'), '/dashboard'); expectRedirect(await request('/admin/users/new'), '/dashboard?tab=accounts&create=account'); -assert.ok((await (await request('/me')).text()).includes('Alice')); +assert.ok((await (await request('/me')).text()).includes('Alpha')); const promotion = await command('createPromotion', { data: { year: 2026, identifier: 'PTSI', color: '#5566CC' } }); @@ -118,17 +118,17 @@ const create = (first, last, email, roles, promotionIds = []) => promotion_ids: promotionIds } }); -const student = await create( - 'Valentin', - 'Burgaud', - 'student@example.org', - ['user'], +const student = await create('Exemple', 'Fictif', 'student@example.org', ['user'], [promotion.id]); +const teacher = await create( + 'Modele', + 'Temoin', + 'teacher@example.org', + ['teacher'], [promotion.id] ); -const teacher = await create('Marie', 'Dupont', 'teacher@example.org', ['teacher'], [promotion.id]); -const outsider = await create('Paul', 'Petit', 'outsider@example.org', ['user']); +const outsider = await create('Profil', 'Petit', 'outsider@example.org', ['user']); assert.equal(typeof student.id, 'number'); -assert.match(student.username, /^vburg\d{3}$/); +assert.match(student.username, /^efict\d{3}$/); const old = await command('invitation', { id: student.id }); const invitation = await command('invitation', { id: student.id }); assert.equal(invitation.delivery, 'manual'); @@ -150,9 +150,9 @@ assert.equal( ); const me = await (await request('/me')).text(); assert.ok( - me.includes('Valentin') && - me.includes('BURGAUD') === false && - me.includes('Burgaud') && + me.includes('Exemple') && + me.includes('FICTIF') === false && + me.includes('Fictif') && me.includes('PTSI') ); assert.equal( @@ -206,7 +206,7 @@ const teacherSession = jar.get('sophikron_session_dev'); assert.equal((await request('/dashboard')).status, 200); assert.equal((await data('users')).items[0].status, 'disabled'); assert.deepEqual( - (await data('search', { q: 'burgo' })).map((item) => item.id), + (await data('search', { q: 'ficto' })).map((item) => item.id), [student.id] ); assert.equal((await request(`/dashboard/data?resource=user&id=${outsider.id}`)).status, 404); @@ -264,7 +264,7 @@ if (process.env.BFF_BROWSER_INTEGRATION === '1') { // Course checks follow the dashboard assertions so their audit totals stay independent. jar.set('sophikron_session_dev', adminSession); await command('archiveAccount', { id: student.id, data: { archived: false } }); -const collaborator = await create('Camille', 'Durand', 'collaborator@example.org', ['teacher']); +const collaborator = await create('Compte', 'Fictice', 'collaborator@example.org', ['teacher']); const subject = await command('createSubject', { data: { name: 'Sciences', icon: 'science', color: '#32735B' } }); @@ -333,7 +333,7 @@ await courseEdit('grantPromotion', { await courseEdit('addCollaborator', { userId: collaborator.id, data: {} }); const catalogueHtml = await (await request('/lessons?q=unused-filter')).text(); assert.ok( - catalogueHtml.includes('Sciences et découvertes') && catalogueHtml.includes('Camille Durand') + catalogueHtml.includes('Sciences et découvertes') && catalogueHtml.includes('Compte Fictice') ); assert.ok(catalogueHtml.includes('role-teacher')); assert.ok(!catalogueHtml.includes('course-search') && !catalogueHtml.includes('name="q"')); diff --git a/frontend/tests/kholleWishes.test.ts b/frontend/tests/kholleWishes.test.ts index bd48528..f4fffb2 100644 --- a/frontend/tests/kholleWishes.test.ts +++ b/frontend/tests/kholleWishes.test.ts @@ -297,11 +297,11 @@ test('teachers precede kholleurs with French alphabetical ordering and dual role roles: ('teacher' | 'kholleur')[] ) => ({ id, last_name, first_name, roles }); const people = [ - person(1, 'Aaron', 'Paul', ['kholleur']), - person(2, 'Zola', 'Zoé', ['teacher']), - person(3, 'Émile', 'Alice', ['teacher', 'kholleur']), - person(4, 'Zola', 'Alice', ['teacher']), - person(5, 'Bernard', 'Paul', ['kholleur']) + person(1, 'Aaron', 'Profil', ['kholleur']), + person(2, 'Zeta', 'Zêta', ['teacher']), + person(3, 'Étalon', 'Alpha', ['teacher', 'kholleur']), + person(4, 'Zeta', 'Alpha', ['teacher']), + person(5, 'Temoin', 'Profil', ['kholleur']) ]; assert.deepEqual( [...people].sort(compareWishPeople).map((person) => person.id), @@ -322,8 +322,8 @@ test('only subjects with allocated kholles appear, including when wishes are sti staff: [ { id: 10, - name: 'Marie Test', - first_name: 'Marie', + name: 'Modele Test', + first_name: 'Modele', last_name: 'Test', roles: ['teacher'], sessions: id === 2 ? 4 : null diff --git a/frontend/tests/lessons.test.ts b/frontend/tests/lessons.test.ts index e1ed860..cf55601 100644 --- a/frontend/tests/lessons.test.ts +++ b/frontend/tests/lessons.test.ts @@ -17,12 +17,12 @@ test('course teams group the responsible teacher and collaborators without dupli role, can_edit: role === 'teacher' }); - const responsible = person(1, 'Zoé Responsable', 'teacher'); + const responsible = person(1, 'Zêta Responsable', 'teacher'); const team = lessonTeam({ responsible, collaborators: [ - person(2, 'Zoé Collègue', 'teacher'), - person(3, 'Alice Collègue', 'teacher'), + person(2, 'Zêta Collègue', 'teacher'), + person(3, 'Alpha Collègue', 'teacher'), person(4, 'Khôlleur', 'kholleur'), responsible ] @@ -49,7 +49,7 @@ test('document labels hide the actual extension and preserve author titles and i test('section headings preserve multiline formatting and leave HTML as literal text', () => { const blocks = formattedBlocks( - '# **Section**\n## ==Sous-section==\n**première\nseconde**\n' + '# **Section**\n## ==Sous-section==\n**pdemoère\nseconde**\n' ); assert.equal(blocks[0].level, 1); assert.equal(blocks[0].parts[0].text, 'Section'); diff --git a/frontend/tests/roles.test.ts b/frontend/tests/roles.test.ts index 03a3520..ec06a02 100644 --- a/frontend/tests/roles.test.ts +++ b/frontend/tests/roles.test.ts @@ -35,11 +35,11 @@ test('pupil exclusivity, a nonempty selection and known unique roles are require test('subject staff appear once for each teaching role, with contextual badges and sorted names', () => { const members = [ - { id: 1, first_name: 'Val', last_name: 'Zulu', roles: ['admin', 'teacher'] }, - { id: 2, first_name: 'Zoé', last_name: 'Éclair', roles: ['teacher', 'kholleur', 'admin'] }, - { id: 3, first_name: 'Alice', last_name: 'Alpha', roles: ['kholleur'] }, - { id: 4, first_name: 'Bob', last_name: 'Eclair', roles: ['teacher'] }, - { id: 5, first_name: 'Sam', last_name: 'Admin', roles: ['admin'] } + { id: 1, first_name: 'Exemple', last_name: 'Zulu', roles: ['admin', 'teacher'] }, + { id: 2, first_name: 'Zêta', last_name: 'Éclair', roles: ['teacher', 'kholleur', 'admin'] }, + { id: 3, first_name: 'Alpha', last_name: 'Alpha', roles: ['kholleur'] }, + { id: 4, first_name: 'Bravo', last_name: 'Eclair', roles: ['teacher'] }, + { id: 5, first_name: 'Sujet', last_name: 'Admin', roles: ['admin'] } ]; assert.deepEqual( teachingRoleEntries(members).map(({ member, role }) => [member.id, role]), @@ -78,24 +78,24 @@ test('promotion teaching candidates use one server union filter for listing and id: 1, roles: ['teacher'], username: 'teacher', - first_name: 'Camille', - last_name: 'Martin', + first_name: 'Compte', + last_name: 'Specimen', status: 'active' }, { id: 2, roles: ['kholleur'], username: 'kholleur', - first_name: 'Camille', - last_name: 'Martin', + first_name: 'Compte', + last_name: 'Specimen', status: 'active' }, { id: 3, roles: ['admin', 'teacher', 'kholleur'], username: 'both', - first_name: 'Camille', - last_name: 'Martin', + first_name: 'Compte', + last_name: 'Specimen', status: 'active' } ]; @@ -111,14 +111,14 @@ test('promotion teaching candidates use one server union filter for listing and url.searchParams.get('resource') === 'users' ? { items: candidates } : candidates ); }); - for (const query of ['', ' Camille ']) + for (const query of ['', ' Compte ']) assert.deepEqual(await promotionCandidates('teaching', query, controller.signal), candidates); assert.equal(requests.length, 2); assert.deepEqual( requests.map((url) => url.searchParams.get('resource')), ['users', 'search'] ); - assert.equal(requests[1].searchParams.get('q'), 'Camille'); + assert.equal(requests[1].searchParams.get('q'), 'Compte'); }); test('promotion pupil category requests only pupils and waits for two search characters', async (t) => { @@ -133,7 +133,7 @@ test('promotion pupil category requests only pupils and waits for two search cha assert.deepEqual(await promotionCandidates('user', 'C'), []); assert.equal(requests.length, 0); await promotionCandidates('user', ''); - await promotionCandidates('user', 'Camille'); + await promotionCandidates('user', 'Compte'); assert.equal(requests.length, 2); }); @@ -165,7 +165,7 @@ test('both promotion candidate categories exclude existing members in listing an return Response.json(url.searchParams.get('resource') === 'users' ? { items: [] } : []); }); for (const category of ['user', 'teaching'] as const) { - for (const query of ['', 'Camille']) { + for (const query of ['', 'Compte']) { await promotionCandidates(category, query, undefined, 42); assert.equal(requests.at(-1)?.searchParams.get('role'), category); } diff --git a/frontend/tests/timetable-browser.mjs b/frontend/tests/timetable-browser.mjs index bc6b249..2ecf0c1 100644 --- a/frontend/tests/timetable-browser.mjs +++ b/frontend/tests/timetable-browser.mjs @@ -260,16 +260,16 @@ test('live annual management, recurrence confirmations, hours, archival and annu staff: [ { id: 2, - name: 'Marie Test', - first_name: 'Marie', + name: 'Modele Test', + first_name: 'Modele', last_name: 'Test', roles: ['teacher'], sessions: wishesByYear.get(year) ?? 0 }, { id: 4, - name: 'Paul Kholleur', - first_name: 'Paul', + name: 'Profil Kholleur', + first_name: 'Profil', last_name: 'Kholleur', roles: ['kholleur'], sessions: 1 @@ -312,8 +312,8 @@ test('live annual management, recurrence confirmations, hours, archival and annu staff: [ { id: 2, - name: 'Marie Test', - first_name: 'Marie', + name: 'Modele Test', + first_name: 'Modele', last_name: 'Test', roles: ['teacher', 'kholleur'], sessions: wishesByYear.get(year) ?? null @@ -328,8 +328,8 @@ test('live annual management, recurrence confirmations, hours, archival and annu staff: [ { id: 99, - name: 'Paul Exemple', - first_name: 'Paul', + name: 'Profil Exemple', + first_name: 'Profil', last_name: 'Exemple', roles: ['teacher'], sessions: 4 @@ -694,7 +694,7 @@ test('live annual management, recurrence confirmations, hours, archival and annu return reply({ id: 1, username: 'test', - first_name: 'Camille', + first_name: 'Compte', last_name: 'Test', is_bootstrap: false, status: 'active', @@ -1212,7 +1212,7 @@ test('live annual management, recurrence confirmations, hours, archival and annu 0 ); assert.equal( - await page.locator('.wishes').getByText('Paul Exemple', { exact: true }).count(), + await page.locator('.wishes').getByText('Profil Exemple', { exact: true }).count(), 0 ); const wishInput = page.getByRole('spinbutton', { name: /Séances sur deux semaines/ }); @@ -1296,17 +1296,20 @@ test('live annual management, recurrence confirmations, hours, archival and annu 0 ); assert.equal( - await page.locator('.service-panel tbody tr').filter({ hasText: 'Marie Test' }).count(), + await page + .locator('.service-panel tbody tr') + .filter({ hasText: 'Modele Test' }) + .count(), 1 ); await page.getByRole('checkbox', { name: 'C106' }).check(); await page.getByRole('checkbox', { name: 'C105' }).check(); await assertUntouchedSteps(['Génération du calendrier', 'Affectation des groupes']); const preferenceSwitch = page.getByRole('switch', { - name: /Priorité à sa promotion — Marie Test/ + name: /Priorité à sa promotion — Modele Test/ }); const kholleurPreference = page.getByRole('switch', { - name: /Priorité à ses promotions — Paul Kholleur/ + name: /Priorité à ses promotions — Profil Kholleur/ }); assert.equal(await kholleurPreference.isEnabled(), true); assert.equal(await kholleurPreference.isChecked(), true); diff --git a/frontend/tests/timetable.test.ts b/frontend/tests/timetable.test.ts index b0a76af..8c019fd 100644 --- a/frontend/tests/timetable.test.ts +++ b/frontend/tests/timetable.test.ts @@ -132,15 +132,19 @@ test('odd PT cycles give a group 12 or 13 sessions, while even PTSI cycles give test('simultaneous blocks retain subject and teacher order across weeks and database order', () => { const blocks = [ - conflictEvent({ id: '1', title: 'Physique', teacher: 'Albert' }), - conflictEvent({ id: '2', title: 'Mathématiques', teacher: 'Zoé' }), - conflictEvent({ id: '3', title: 'Mathématiques', teacher: 'Émile' }) + conflictEvent({ id: '1', title: 'Physique', teacher: 'Alpha' }), + conflictEvent({ id: '2', title: 'Mathématiques', teacher: 'Zêta' }), + conflictEvent({ id: '3', title: 'Mathématiques', teacher: 'Étalon' }) ]; const labels = (events: TimetableEvent[]): string[] => events .toSorted(compareTimetableDisplayEvents) .map((event) => `${event.title}/${event.teacher}`); - assert.deepEqual(labels(blocks), ['Mathématiques/Émile', 'Mathématiques/Zoé', 'Physique/Albert']); + assert.deepEqual(labels(blocks), [ + 'Mathématiques/Étalon', + 'Mathématiques/Zêta', + 'Physique/Alpha' + ]); const nextWeek = blocks.toReversed().map((event, index) => ({ ...event, id: `new-${index}`, @@ -157,11 +161,11 @@ test('calendar ordering uses the first assigned teacher then room and numeric gr ...base, teacher_ids: [7, 8], teachers: [ - { id: 8, name: 'Zoé', available: true }, - { id: 7, name: 'Alice', available: true } + { id: 8, name: 'Zêta', available: true }, + { id: 7, name: 'Alpha', available: true } ] }; - assert.ok(compareTimetableDisplayEvents(alpha, { ...base, teacher: 'Bernard' }) < 0); + assert.ok(compareTimetableDisplayEvents(alpha, { ...base, teacher: 'Temoin' }) < 0); assert.ok(compareTimetableDisplayEvents({ ...base, room: 'B2' }, { ...base, room: 'B10' }) < 0); assert.ok( compareTimetableDisplayEvents({ ...base, target_number: 2 }, { ...base, target_number: 10 }) < 0 @@ -488,10 +492,10 @@ test('resizing either border preserves the other boundary across recess-split se test('subject specialists precede other teachers and each group stays alphabetically ordered', () => { const teachers = [ - { id: 1, name: 'Zoé', subject_ids: [1] }, - { id: 2, name: 'Alice', subject_ids: [2] }, - { id: 3, name: 'Émile', subject_ids: [1, 2] }, - { id: 4, name: 'Benoît' } + { id: 1, name: 'Zêta', subject_ids: [1] }, + { id: 2, name: 'Alpha', subject_ids: [2] }, + { id: 3, name: 'Étalon', subject_ids: [1, 2] }, + { id: 4, name: 'Bêta' } ]; assert.deepEqual( orderedTimetableTeachers(teachers, 1).map((teacher) => teacher.id), diff --git a/frontend/tests/timetableWarnings.test.ts b/frontend/tests/timetableWarnings.test.ts index 8a89868..3184e82 100644 --- a/frontend/tests/timetableWarnings.test.ts +++ b/frontend/tests/timetableWarnings.test.ts @@ -251,7 +251,7 @@ test('external teacher conflicts are critical in both calendars and deduplicate assert.equal( crossCalendarTeacherConflicts( [reverse], - [{ ...booking, calendar_id: 1, calendar_label: 'Première année' }], + [{ ...booking, calendar_id: 1, calendar_label: 'Pdemoère année' }], '2026-09-07' ).length, 1 diff --git a/frontend/tests/visual-picker.mjs b/frontend/tests/visual-picker.mjs index 89d6fa9..bb04d95 100644 --- a/frontend/tests/visual-picker.mjs +++ b/frontend/tests/visual-picker.mjs @@ -477,7 +477,7 @@ test('header navigation and colored account menu work on desktop, mobile and key await page.emulateMedia({ colorScheme }); await page.goto(`${server.resolvedUrls.local[0]}__picker?header`); const trigger = page.getByRole('button', { - name: 'Menu du compte de Valentin Burgaud', + name: 'Menu du compte de Exemple Fictif', exact: true }); await trigger.waitFor(); @@ -615,9 +615,9 @@ test('journal menus and account pickers stay compact, styled and usable on mobil const users = [ { id: 9, - first_name: 'Alice', - last_name: 'Martin', - username: 'alice123', + first_name: 'Alpha', + last_name: 'Specimen', + username: 'alpha123', status: 'disabled', roles: ['teacher', 'kholleur'], promotions: [ @@ -722,7 +722,7 @@ test('journal menus and account pickers stay compact, styled and usable on mobil assert.equal(await dialog.locator('.role-teacher').count(), 1); assert.equal(await dialog.locator('.role-kholleur').count(), 1); assert.equal(await dialog.locator('.promotion-tag').count(), 1); - await dialog.getByLabel('Rechercher un compte', { exact: true }).fill('Alice'); + await dialog.getByLabel('Rechercher un compte', { exact: true }).fill('Alpha'); await dialog.getByLabel('Rôle du compte', { exact: true }).selectOption('teacher'); await page.waitForResponse( (response) => @@ -736,7 +736,7 @@ test('journal menus and account pickers stay compact, styled and usable on mobil response.url().includes('resource=events') && response.url().includes('user_id=9') ); - await page.getByRole('button', { name: 'Alice Martin', exact: true }).click(); + await page.getByRole('button', { name: 'Alpha Specimen', exact: true }).click(); await dialog .getByRole('button', { name: 'Effacer la sélection', exact: true }) .click(); @@ -955,10 +955,10 @@ test('saved group tags appear in promotion rosters, popup cards and full profile ]; const student = { id: 3, - username: 'alice123', - first_name: 'Alice', - last_name: 'Martin', - email: 'martin.alice@test.fr', + username: 'alpha123', + first_name: 'Alpha', + last_name: 'Specimen', + email: 'specimen.alpha@example.org', roles: ['user'], status: archived ? 'disabled' : 'active', created_at: '2026-01-01T00:00:00Z', @@ -979,7 +979,7 @@ test('saved group tags appear in promotion rosters, popup cards and full profile json = { items: [ student, - { ...student, id: 4, first_name: 'Benoît', group_assignments: [] } + { ...student, id: 4, first_name: 'Bêta', group_assignments: [] } ], total: 2 }; @@ -989,7 +989,7 @@ test('saved group tags appear in promotion rosters, popup cards and full profile await page.goto( `${server.resolvedUrls.local[0]}__picker?directory${teacher ? '&teacher' : ''}${archived ? '&archived' : ''}` ); - const row = page.locator('.account-row').filter({ hasText: 'Alice Martin' }); + const row = page.locator('.account-row').filter({ hasText: 'Alpha Specimen' }); await row.waitFor(); assert.equal( await row.evaluate((element) => element.classList.contains('archived-account')), @@ -1006,7 +1006,7 @@ test('saved group tags appear in promotion rosters, popup cards and full profile assert.equal( await page .locator('.account-row') - .filter({ hasText: 'Benoît Martin' }) + .filter({ hasText: 'Bêta Specimen' }) .locator('.group-tags') .count(), 0 @@ -1022,7 +1022,7 @@ test('saved group tags appear in promotion rosters, popup cards and full profile ); assert.equal(await full.locator('.membership-row').count(), teacher ? 1 : 2); const search = page.getByRole('textbox', { name: 'Rechercher un compte', exact: true }); - await search.fill('Alice'); + await search.fill('Alpha'); await page.waitForResponse((response) => response.url().includes('resource=search')); await row.waitFor(); assert.deepEqual(await row.locator('.group-tags .tag').allTextContents(), [ @@ -1081,11 +1081,11 @@ test('archived pupils stay grey and movable outside effective khôlle sizes', as const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } }); const errors = []; page.on('pageerror', (error) => errors.push(error.message)); - const students = ['Alice', 'Benoît', 'Camille', 'Diane', 'Émile', 'Farah'].map( + const students = ['Alpha', 'Bêta', 'Compte', 'Delta', 'Étalon', 'Foxtrot'].map( (name, index) => ({ id: index + 1, first_name: name, - last_name: 'Martin', + last_name: 'Specimen', status: index === 5 ? 'disabled' : 'active' }) ); @@ -1115,7 +1115,7 @@ test('archived pupils stay grey and movable outside effective khôlle sizes', as await archivedGroup.waitFor(); assert.equal(await archivedGroup.locator('.bubble-handle .tag').textContent(), '0'); const archivedStudent = page.getByRole('button', { - name: 'Farah Martin · Archivé', + name: 'Foxtrot Specimen · Archivé', exact: true }); assert.equal( @@ -1170,10 +1170,10 @@ test('newcomers join existing groups in both views and khôlles can be paired an const page = await browser.newPage({ viewport: { width: 1280, height: 1100 } }); const errors = []; page.on('pageerror', (error) => errors.push(error.message)); - const students = ['Alice', 'Benoît', 'Camille', 'Diane'].map((name, index) => ({ + const students = ['Alpha', 'Bêta', 'Compte', 'Delta'].map((name, index) => ({ id: index + 1, first_name: name, - last_name: 'Martin', + last_name: 'Specimen', status: 'active' })); const partition = { @@ -1197,17 +1197,17 @@ test('newcomers join existing groups in both views and khôlles can be paired an await page.goto(`${server.resolvedUrls.local[0]}__picker?groups`); await page.getByRole('button', { name: 'Groupes de khôlle', exact: true }).click(); const bubble = (name) => page.getByRole('region', { name, exact: true }); - const pupil = (name) => page.getByRole('button', { name: `${name} Martin`, exact: true }); + const pupil = (name) => page.getByRole('button', { name: `${name} Specimen`, exact: true }); const save = page.getByRole('button', { name: 'Enregistrer', exact: true }); await page.getByRole('button', { name: 'Affecter ces élèves', exact: true }).click(); assert.equal(await save.isDisabled(), true); - await pupil('Diane').dragTo(bubble('Groupe 02').locator('.bubble-members')); + await pupil('Delta').dragTo(bubble('Groupe 02').locator('.bubble-members')); assert.equal(await save.isEnabled(), true); assert.equal(await bubble('Groupe 01').locator('.student-chip').count(), 2); await page.getByRole('button', { name: 'Annuler', exact: true }).click(); await page.getByRole('button', { name: 'Vue liste', exact: true }).click(); await page.getByRole('button', { name: 'Affecter ces élèves', exact: true }).click(); - await pupil('Diane').focus(); + await pupil('Delta').focus(); await page.keyboard.press('Enter'); await bubble('Groupe 02') .getByRole('button', { name: 'Déplacer ici', exact: true }) @@ -1225,38 +1225,38 @@ test('newcomers join existing groups in both views and khôlles can be paired an assert.equal(writes.length, 1); await page.getByRole('button', { name: 'Vue bulles', exact: true }).click(); await page.getByRole('button', { name: 'Modifier les groupes', exact: true }).click(); - await pupil('Alice').dragTo(pupil('Camille')); + await pupil('Alpha').dragTo(pupil('Compte')); assert.equal(await bubble('Groupe 03').locator('.student-chip').count(), 2); assert.equal( await bubble('Groupe 01').locator('.student-chip').textContent(), - 'Benoît Martin' + 'Bêta Specimen' ); assert.equal( await bubble('Groupe 02').locator('.student-chip').textContent(), - 'Diane Martin' + 'Delta Specimen' ); assert.equal(await save.isDisabled(), true); - await pupil('Alice').dragTo(page.locator('.group-board'), { + await pupil('Alpha').dragTo(page.locator('.group-board'), { targetPosition: { x: 650, y: 320 } }); assert.equal(await page.locator('.group-bubble').count(), 4); assert.equal( await bubble('Groupe 03').locator('.student-chip').textContent(), - 'Camille Martin' + 'Compte Specimen' ); assert.equal( await bubble('Groupe 04').locator('.student-chip').textContent(), - 'Alice Martin' + 'Alpha Specimen' ); assert.equal(await save.isDisabled(), true); - await pupil('Alice').click(); + await pupil('Alpha').click(); await bubble('Groupe 03') .getByRole('button', { name: 'Déplacer ici', exact: true }) .click(); await bubble('Groupe 04') .getByRole('button', { name: 'Retirer ce groupe vide', exact: true }) .click(); - await pupil('Diane').click(); + await pupil('Delta').click(); await bubble('Groupe 01') .getByRole('button', { name: 'Déplacer ici', exact: true }) .click(); @@ -1282,8 +1282,8 @@ test('custom group editing preserves archived pupils and lets them be removed an browser = await chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || undefined }); const page = await browser.newPage({ viewport: { width: 1280, height: 1100 } }); const students = [ - { id: 1, first_name: 'Alice', last_name: 'Martin', status: 'active' }, - { id: 2, first_name: 'Farah', last_name: 'Martin', status: 'disabled' } + { id: 1, first_name: 'Alpha', last_name: 'Specimen', status: 'active' }, + { id: 2, first_name: 'Foxtrot', last_name: 'Specimen', status: 'disabled' } ]; let groups = [ { @@ -1314,7 +1314,7 @@ test('custom group editing preserves archived pupils and lets them be removed an const custom = page.getByRole('region', { name: 'Allemand', exact: true }); const source = page.getByRole('region', { name: 'Classe entière', exact: true }); const archived = (region) => - region.getByRole('button', { name: 'Farah Martin · Archivé', exact: true }); + region.getByRole('button', { name: 'Foxtrot Specimen · Archivé', exact: true }); await custom.getByRole('button', { name: 'Modifier', exact: true }).click(); assert.equal(await archived(custom).isEnabled(), true); await page.getByRole('button', { name: 'Enregistrer', exact: true }).click(); @@ -1346,8 +1346,8 @@ test('promotion groups support bubble movement, transfers, saved drafts and inde const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } }); const errors = []; page.on('pageerror', (error) => errors.push(error.message)); - const students = ['Alice', 'Benoît', 'Camille', 'Diane', 'Émile', 'Farah'].map( - (name, index) => ({ id: index + 1, first_name: name, last_name: 'Martin' }) + const students = ['Alpha', 'Bêta', 'Compte', 'Delta', 'Étalon', 'Foxtrot'].map( + (name, index) => ({ id: index + 1, first_name: name, last_name: 'Specimen' }) ); const initial = [ { number: 1, x: 20, y: 20, student_ids: [1, 2, 3] }, @@ -1434,14 +1434,14 @@ test('promotion groups support bubble movement, transfers, saved drafts and inde await page.setViewportSize({ width: 1280, height: 1000 }); await bubbles .first() - .getByRole('button', { name: 'Alice Martin', exact: true }) + .getByRole('button', { name: 'Alpha Specimen', exact: true }) .dragTo(bubbles.nth(1).locator('.bubble-members')); assert.equal(await bubbles.nth(1).locator('.student-chip').count(), 4); assert.equal( await page.getByRole('button', { name: 'Enregistrer', exact: true }).isDisabled(), true ); - await bubbles.nth(1).getByRole('button', { name: 'Diane Martin', exact: true }).click(); + await bubbles.nth(1).getByRole('button', { name: 'Delta Specimen', exact: true }).click(); await bubbles.first().getByRole('button', { name: 'Déplacer ici', exact: true }).click(); assert.equal( await page.getByRole('button', { name: 'Enregistrer', exact: true }).isEnabled(), @@ -1473,13 +1473,13 @@ test('promotion groups support bubble movement, transfers, saved drafts and inde assert.equal(await bubbles.count(), 0); await page.getByRole('button', { name: 'Groupes de khôlle', exact: true }).click(); await page.getByRole('button', { name: 'Modifier les groupes', exact: true }).click(); - await bubbles.nth(1).getByRole('button', { name: 'Diane Martin', exact: true }).click(); + await bubbles.nth(1).getByRole('button', { name: 'Delta Specimen', exact: true }).click(); await bubbles.first().getByRole('button', { name: 'Déplacer ici', exact: true }).click(); assert.equal( await page.getByRole('button', { name: 'Enregistrer', exact: true }).isDisabled(), true ); - await bubbles.nth(1).getByRole('button', { name: 'Émile Martin', exact: true }).click(); + await bubbles.nth(1).getByRole('button', { name: 'Étalon Specimen', exact: true }).click(); await bubbles.first().getByRole('button', { name: 'Déplacer ici', exact: true }).click(); assert.equal(await bubbles.first().locator('.student-chip').count(), 5); assert.equal(await bubbles.nth(1).locator('.student-chip').count(), 1); @@ -1919,7 +1919,7 @@ test('course cards, folded sections, locked resources and file drop forms stay u .locator('.team-line') .allTextContents() .then((lines) => lines.map((line) => line.replace(/\s+/g, ' ').trim())), - ['Camille Martin Alice Durand', 'Zoé Bernard'] + ['Compte Specimen Alpha Fictice', 'Zêta Temoin'] ); assert.ok((await page.locator('.course-card').boundingBox()).height < 300); const arrow = await page.locator('.course-open').boundingBox(); @@ -2061,7 +2061,7 @@ test('collaborator suggestions open immediately, search each letter and refill a page.on('pageerror', (error) => errors.push(error.message)); const people = Array.from({ length: 7 }, (_, index) => ({ id: 20 + index, - label: `Alex Martin ${index + 1}`, + label: `Avatar Specimen ${index + 1}`, role: index % 2 ? 'kholleur' : 'teacher', can_edit: index % 2 === 0 })); @@ -2115,10 +2115,14 @@ test('collaborator suggestions open immediately, search each letter and refill a .waitFor(); await query.fill(''); await list.locator('.candidate-row').nth(4).waitFor(); - await list.getByRole('button', { name: 'Ajouter Alex Martin 1', exact: true }).click(); - await list.getByRole('button', { name: 'Ajouter Alex Martin 6', exact: true }).waitFor(); + await list.getByRole('button', { name: 'Ajouter Avatar Specimen 1', exact: true }).click(); + await list + .getByRole('button', { name: 'Ajouter Avatar Specimen 6', exact: true }) + .waitFor(); assert.equal( - await list.getByRole('button', { name: 'Ajouter Alex Martin 1', exact: true }).count(), + await list + .getByRole('button', { name: 'Ajouter Avatar Specimen 1', exact: true }) + .count(), 0 ); assert.equal(await list.locator('.candidate-row').count(), 5);