mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add tooling: Makefile, level validation, build, Pyodide vendoring, tests, docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,9 @@ backend/staticfiles/
|
||||
backend/.venv/
|
||||
backend/venv/
|
||||
|
||||
# Environnement virtuel Python de développement
|
||||
.venv/
|
||||
|
||||
# Dépendances JS (si un outillage de build/test est ajouté plus tard)
|
||||
node_modules/
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Contribuer à PyQuest / Contributing to PyQuest
|
||||
|
||||
Français d'abord, English below.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Code, identifiants, noms de fichiers et messages de commit en **anglais** ; commentaires en
|
||||
**français**.
|
||||
- Indentation de **4 espaces** partout (sauf les tabulations imposées par `make`).
|
||||
- JavaScript : classes ES2022 et modules ES natifs, pas de framework sans justification écrite.
|
||||
- Python : typé, compatible `pyright` (`make typecheck`).
|
||||
- Interface et contenus pédagogiques **bilingues fr/en** (fr par défaut).
|
||||
- `make test` doit passer avant toute demande de fusion.
|
||||
|
||||
## Ajouter un niveau
|
||||
|
||||
1. **Créer le dossier** `levels/NN-slug/` (ex. `levels/03-input/`) avec un fichier `level.yaml`.
|
||||
L'`id` doit être identique au nom du dossier (`^[0-9]{2}-[a-z0-9-]+$`).
|
||||
2. **Écrire le contenu** en suivant le schéma [`levels/schema/level.schema.json`](levels/schema/level.schema.json).
|
||||
Prenez `levels/01-hello/level.yaml` comme modèle :
|
||||
- une seule notion nouvelle par étape, phrases courtes, ton encourageant ;
|
||||
- alternez étapes `explain` et `code` ;
|
||||
- chaque étape `code` : un `starter` exécutable tel quel, une `instruction`, des `tests`,
|
||||
idéalement des `hints` (du plus vague au plus précis) et une `solution` ;
|
||||
- une `mission` finale motivante, avec `reward_sound`.
|
||||
3. **Fournir le français et l'anglais** pour chaque texte (`fr` et `en`).
|
||||
4. **Référencer le niveau** dans `levels/manifest.json` (ordre et `requires`).
|
||||
5. **Valider** : `make validate-levels` vérifie le schéma, le manifeste, la présence des
|
||||
traductions `en` et que le code de départ compile.
|
||||
|
||||
### Tests déclaratifs disponibles
|
||||
|
||||
| `kind` | Champs | Sens |
|
||||
|---|---|---|
|
||||
| `no_syntax_error` | — | pas d'erreur de syntaxe |
|
||||
| `stdout_equals` | `value` | sortie exactement égale (retour à la ligne final inclus) |
|
||||
| `stdout_contains` | `value` | sous-chaîne présente dans la sortie |
|
||||
| `stdout_matches_regex` | `value` | la sortie complète correspond à l'expression régulière |
|
||||
| `var_equals` | `name`, `value` | variable égale à la valeur |
|
||||
| `var_type_is` | `name`, `value` | type de la variable (`str`, `int`, `float`…) |
|
||||
|
||||
Un niveau ne contient **jamais de code exécutable** autre que le code de départ et la solution
|
||||
affichés à l'apprenant : toute nouvelle sorte de validation passe par le moteur
|
||||
(`app/js/core/ValidationEngine.js`), pas par un fichier de niveau.
|
||||
|
||||
### Accessibilité
|
||||
|
||||
Aucune information ne doit passer uniquement par la couleur ou le son. Les images décoratives
|
||||
ont un `alt` vide ; une illustration porteuse de sens doit être décrite dans le texte.
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
- Code, identifiers, file names and commit messages in **English**; comments in **French**.
|
||||
- **4-space** indentation everywhere (except tabs required by `make`).
|
||||
- JavaScript: ES2022 classes and native ES modules, no framework without a written justification.
|
||||
- Python: typed, `pyright`-clean (`make typecheck`).
|
||||
- UI and teaching content are **bilingual fr/en**.
|
||||
- `make test` must pass before a merge request.
|
||||
|
||||
### Adding a level
|
||||
|
||||
1. Create `levels/NN-slug/level.yaml`; the `id` must equal the folder name.
|
||||
2. Follow [`levels/schema/level.schema.json`](levels/schema/level.schema.json) and use
|
||||
`levels/01-hello/level.yaml` as a model (one new notion per step, short sentences, encouraging
|
||||
tone, runnable `starter`, `tests`, graduated `hints`, `solution`, motivating `mission`).
|
||||
3. Provide both `fr` and `en` for every text.
|
||||
4. List the level in `levels/manifest.json`.
|
||||
5. Run `make validate-levels`.
|
||||
|
||||
Levels never contain executable code other than the starter and solution shown to the learner:
|
||||
new kinds of validation are added to the engine, not to level files.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 PyQuest contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,45 @@
|
||||
# PyQuest — tâches courantes. Les recettes doivent être indentées par des tabulations (exigence de make).
|
||||
|
||||
PYTHON ?= python3
|
||||
VENV := .venv
|
||||
VENV_PY := $(VENV)/bin/python
|
||||
PORT ?= 8000
|
||||
|
||||
.PHONY: help install vendor-pyodide dev validate-levels build test test-js test-python typecheck clean
|
||||
|
||||
help: ## Affiche cette aide
|
||||
@grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}'
|
||||
|
||||
install: $(VENV)/.installed vendor-pyodide ## Installe les outils de dev et Pyodide
|
||||
|
||||
$(VENV)/.installed: requirements-dev.txt
|
||||
$(PYTHON) -m venv $(VENV)
|
||||
$(VENV_PY) -m pip install --quiet -r requirements-dev.txt
|
||||
touch $@
|
||||
|
||||
vendor-pyodide: ## Télécharge Pyodide (version épinglée) dans vendor/pyodide
|
||||
./scripts/vendor_pyodide.sh
|
||||
|
||||
dev: ## Serveur de développement avec en-têtes COOP/COEP (PORT=8000)
|
||||
$(PYTHON) scripts/dev_server.py --port $(PORT)
|
||||
|
||||
validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, traductions)
|
||||
$(VENV_PY) scripts/validate_levels.py
|
||||
|
||||
build: $(VENV)/.installed ## Construit dist/ pour la production
|
||||
$(VENV_PY) scripts/build.py
|
||||
|
||||
test: test-js test-python validate-levels ## Lance tous les tests
|
||||
|
||||
test-js: ## Tests JavaScript (node:test, aucune dépendance)
|
||||
node --test tests/js/*.test.mjs
|
||||
|
||||
test-python: ## Tests Python du runner
|
||||
$(PYTHON) -m unittest discover -s tests/python -v
|
||||
|
||||
typecheck: $(VENV)/.installed ## Vérifie les types Python avec pyright
|
||||
$(VENV)/bin/pyright
|
||||
|
||||
clean: ## Supprime dist/, caches et environnement virtuel
|
||||
rm -rf dist $(VENV)
|
||||
find . -name __pycache__ -type d -prune -exec rm -rf {} +
|
||||
@@ -0,0 +1,55 @@
|
||||
# PyQuest
|
||||
|
||||
Learn Python by doing, **right in the browser**: nothing to install, works offline (PWA), for
|
||||
beginners and advanced learners alike.
|
||||
|
||||
- Real Python (CPython compiled to WebAssembly through [Pyodide](https://pyodide.org)) running in
|
||||
a Web Worker: genuine error messages, translated into plain language.
|
||||
- Notebook-style cells, progressive hints, automatic exercise validation.
|
||||
- Declarative levels (YAML): adding a level requires no code change.
|
||||
- XP, badges, daily streaks, optional sounds and voice, French/English interface.
|
||||
- Accessibility target: WCAG 2.2 AA (full keyboard use, light/dark themes, adjustable text size).
|
||||
|
||||
> Version française : [README.md](README.md)
|
||||
|
||||
## Quick start
|
||||
|
||||
Requirements: Python 3.12+, Node.js 20+, `make`, `curl`.
|
||||
|
||||
```bash
|
||||
make install # dev tools + pinned Pyodide in vendor/pyodide
|
||||
make dev # http://127.0.0.1:8000/
|
||||
make test # JS tests, Python tests, level validation
|
||||
make build # produces dist/ (static app to serve over HTTPS)
|
||||
```
|
||||
|
||||
`make help` lists every target.
|
||||
|
||||
## Layout
|
||||
|
||||
| Folder | Content |
|
||||
|---|---|
|
||||
| `app/` | Static application (ES modules JS, no framework) |
|
||||
| `levels/` | Levels (`level.yaml`), manifest and JSON Schema |
|
||||
| `scripts/` | Dev server, level validation, build, Pyodide download |
|
||||
| `tests/` | JS (`node:test`) and Python (`unittest`) tests |
|
||||
| `nginx/` | Example vhost with the COOP/COEP headers |
|
||||
| `docs/design/` | Architecture decisions and rationale (in French) |
|
||||
|
||||
## Deployment
|
||||
|
||||
The site must be served **over HTTPS**, at the root of a domain, with the headers
|
||||
`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`
|
||||
(see [nginx/pyquest.conf.example](nginx/pyquest.conf.example)). They allow an infinite loop to be
|
||||
interrupted cleanly. Without them the app still works but must restart its Python engine to stop
|
||||
a cell.
|
||||
|
||||
Pyodide is served from the same domain (never from a CDN): this is a COEP requirement.
|
||||
|
||||
## Contributing
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md), in particular to add a level.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE). Pyodide (MPL-2.0) and js-yaml (MIT) keep their own licenses.
|
||||
@@ -0,0 +1,55 @@
|
||||
# PyQuest
|
||||
|
||||
Apprendre Python par la pratique, **directement dans le navigateur** : aucune installation,
|
||||
fonctionne hors ligne (PWA), pour les débutants comme pour les plus avancés.
|
||||
|
||||
- Python réel (CPython compilé en WebAssembly via [Pyodide](https://pyodide.org)), exécuté dans un
|
||||
Web Worker : les vrais messages d'erreur, traduits en langage simple.
|
||||
- Console à cellules façon notebook, indices progressifs, validation automatique des exercices.
|
||||
- Niveaux déclaratifs (YAML) : ajouter un niveau ne demande aucune modification du code.
|
||||
- XP, badges, séries de jours, sons et voix optionnels, interface fr/en.
|
||||
- Accessibilité visée : WCAG 2.2 AA (clavier complet, thèmes clair/sombre, taille de texte réglable).
|
||||
|
||||
> English version: [README-EN.md](README-EN.md)
|
||||
|
||||
## Démarrage rapide
|
||||
|
||||
Prérequis : Python 3.12+, Node.js 20+, `make`, `curl`.
|
||||
|
||||
```bash
|
||||
make install # outils de développement + Pyodide épinglé dans vendor/pyodide
|
||||
make dev # http://127.0.0.1:8000/
|
||||
make test # tests JS, tests Python, validation des niveaux
|
||||
make build # produit dist/ (application statique à servir en HTTPS)
|
||||
```
|
||||
|
||||
`make help` liste toutes les cibles.
|
||||
|
||||
## Organisation
|
||||
|
||||
| Dossier | Contenu |
|
||||
|---|---|
|
||||
| `app/` | Application statique (JS ES modules, sans framework) |
|
||||
| `levels/` | Niveaux (`level.yaml`), manifeste et schéma JSON |
|
||||
| `scripts/` | Serveur de dev, validation des niveaux, build, téléchargement de Pyodide |
|
||||
| `tests/` | Tests JS (`node:test`) et Python (`unittest`) |
|
||||
| `nginx/` | Exemple de vhost avec les en-têtes COOP/COEP |
|
||||
| `docs/design/` | Choix d'architecture et raisonnement |
|
||||
|
||||
## Déploiement
|
||||
|
||||
Le site doit être servi **en HTTPS**, à la racine d'un domaine, avec les en-têtes
|
||||
`Cross-Origin-Opener-Policy: same-origin` et `Cross-Origin-Embedder-Policy: require-corp`
|
||||
(voir [nginx/pyquest.conf.example](nginx/pyquest.conf.example)). Ils permettent d'interrompre
|
||||
proprement une boucle infinie. Sans eux, l'application fonctionne mais doit redémarrer son moteur
|
||||
Python pour arrêter une cellule.
|
||||
|
||||
Pyodide est servi depuis le même domaine (jamais depuis un CDN) : c'est une contrainte de COEP.
|
||||
|
||||
## Contribuer
|
||||
|
||||
Voir [CONTRIBUTING.md](CONTRIBUTING.md), notamment pour ajouter un niveau.
|
||||
|
||||
## Licence
|
||||
|
||||
[MIT](LICENSE). Pyodide (MPL-2.0) et js-yaml (MIT) conservent leurs propres licences.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Exemple de vhost PyQuest (à adapter : domaine, chemins, certificats).
|
||||
# Les en-têtes COOP/COEP sont indispensables à l'interruption propre des boucles infinies
|
||||
# (SharedArrayBuffer). HTTPS obligatoire (service worker + isolation cross-origin).
|
||||
# Voir docs/design/01-pyodide-choice.md.
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name pyquest.example.org;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/pyquest.example.org/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/pyquest.example.org/privkey.pem;
|
||||
|
||||
# Contenu produit par `make build`
|
||||
root /var/www/pyquest/dist;
|
||||
index index.html;
|
||||
|
||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
|
||||
types {
|
||||
text/javascript mjs;
|
||||
application/manifest+json webmanifest;
|
||||
application/wasm wasm;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
|
||||
# Le service worker ne doit jamais être mis en cache longtemps par le navigateur.
|
||||
location = /service-worker.js {
|
||||
add_header Cache-Control "no-cache" always;
|
||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
||||
}
|
||||
|
||||
# Pyodide est versionné et immuable.
|
||||
location /vendor/pyodide/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||
add_header Cross-Origin-Resource-Policy "same-origin" always;
|
||||
}
|
||||
|
||||
# API de synchronisation Django (optionnelle), sur le même domaine.
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"include": [
|
||||
"app/python",
|
||||
"scripts",
|
||||
"tests/python",
|
||||
"backend"
|
||||
],
|
||||
"exclude": [
|
||||
"**/node_modules",
|
||||
"**/__pycache__",
|
||||
"vendor",
|
||||
".venv",
|
||||
"dist"
|
||||
],
|
||||
"pythonVersion": "3.12",
|
||||
"typeCheckingMode": "standard",
|
||||
"venvPath": ".",
|
||||
"venv": ".venv",
|
||||
"extraPaths": [
|
||||
"app/python"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Outils de développement (validation des niveaux, typage)
|
||||
PyYAML>=6.0
|
||||
jsonschema>=4.21
|
||||
pyright>=1.1.380
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Construit dist/ : app + niveaux + Pyodide, avec liste de pré-cache du service worker à jour."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DIST = ROOT / "dist"
|
||||
PRECACHED_SUFFIXES = {".html", ".css", ".js", ".mjs", ".json", ".svg", ".webmanifest", ".py"}
|
||||
NOT_PRECACHED = {"service-worker.js"}
|
||||
|
||||
|
||||
def copy_tree(source: Path, target: Path) -> None:
|
||||
shutil.copytree(source, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.md"))
|
||||
|
||||
|
||||
def shell_files() -> list[str]:
|
||||
"""Fichiers de l'app à pré-cacher (chemins relatifs à la racine du site)."""
|
||||
files = [
|
||||
path.relative_to(DIST).as_posix()
|
||||
for path in sorted(DIST.rglob("*"))
|
||||
if path.is_file()
|
||||
and path.suffix in PRECACHED_SUFFIXES
|
||||
and path.name not in NOT_PRECACHED
|
||||
and not path.relative_to(DIST).parts[0] in {"vendor", "levels"}
|
||||
]
|
||||
return ["./", *files]
|
||||
|
||||
|
||||
def content_hash(paths: list[str]) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for relative in paths:
|
||||
if relative != "./":
|
||||
digest.update((DIST / relative).read_bytes())
|
||||
return digest.hexdigest()[:12]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
pyodide = ROOT / "vendor" / "pyodide"
|
||||
if not pyodide.exists():
|
||||
print("vendor/pyodide absent : lancez `make vendor-pyodide` d'abord.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if DIST.exists():
|
||||
shutil.rmtree(DIST)
|
||||
copy_tree(ROOT / "app", DIST)
|
||||
copy_tree(ROOT / "levels", DIST / "levels")
|
||||
shutil.copytree(pyodide, DIST / "vendor" / "pyodide")
|
||||
|
||||
precache = shell_files()
|
||||
worker = DIST / "service-worker.js"
|
||||
source = worker.read_text(encoding="utf-8")
|
||||
source, shell_count = re.subn(r"const SHELL = \[.*?\];", f"const SHELL = {json.dumps(precache)};", source, flags=re.S)
|
||||
source, version_count = re.subn(
|
||||
r"const CACHE_VERSION = '[^']*';", f"const CACHE_VERSION = 'pyquest-{content_hash(precache)}';", source
|
||||
)
|
||||
if shell_count != 1 or version_count != 1:
|
||||
print("service-worker.js : motifs SHELL/CACHE_VERSION introuvables.", file=sys.stderr)
|
||||
return 1
|
||||
worker.write_text(source, encoding="utf-8")
|
||||
print(f"dist/ prêt : {len(precache)} fichiers pré-cachés.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Valide les niveaux : schéma JSON, cohérence du manifeste, traductions et code de départ."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import jsonschema
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LEVELS_DIR = ROOT / "levels"
|
||||
SCHEMA_PATH = LEVELS_DIR / "schema" / "level.schema.json"
|
||||
|
||||
|
||||
def missing_english(node: Any, path: str = "") -> list[str]:
|
||||
"""Liste les chemins où une chaîne i18n {fr: ...} n'a pas de traduction `en`."""
|
||||
problems: list[str] = []
|
||||
if isinstance(node, dict):
|
||||
if "fr" in node and isinstance(node["fr"], (str, list)):
|
||||
if "en" not in node:
|
||||
problems.append(path or "<root>")
|
||||
for key, value in node.items():
|
||||
problems.extend(missing_english(value, f"{path}.{key}" if path else str(key)))
|
||||
elif isinstance(node, list):
|
||||
for index, value in enumerate(node):
|
||||
problems.extend(missing_english(value, f"{path}[{index}]"))
|
||||
return problems
|
||||
|
||||
|
||||
def code_snippets(level: dict[str, Any]) -> list[tuple[str, str]]:
|
||||
"""Extrait (chemin, code) pour chaque starter/solution du niveau."""
|
||||
snippets: list[tuple[str, str]] = []
|
||||
for index, step in enumerate(level.get("steps", [])):
|
||||
for field in ("starter", "solution"):
|
||||
if isinstance(step.get(field), str):
|
||||
snippets.append((f"steps[{index}].{field}", step[field]))
|
||||
starter = level.get("mission", {}).get("starter")
|
||||
if isinstance(starter, str):
|
||||
snippets.append(("mission.starter", starter))
|
||||
return snippets
|
||||
|
||||
|
||||
def validate_level(path: Path, schema: dict[str, Any], require_en: bool) -> list[str]:
|
||||
errors: list[str] = []
|
||||
try:
|
||||
level = yaml.safe_load(path.read_text(encoding="utf-8"))
|
||||
except yaml.YAMLError as exc:
|
||||
return [f"YAML invalide : {exc}"]
|
||||
|
||||
validator = jsonschema.Draft202012Validator(schema)
|
||||
for error in sorted(validator.iter_errors(level), key=lambda e: list(e.absolute_path)):
|
||||
location = ".".join(str(part) for part in error.absolute_path) or "<root>"
|
||||
errors.append(f"schéma : {location} : {error.message}")
|
||||
if errors:
|
||||
return errors
|
||||
|
||||
if level["id"] != path.parent.name:
|
||||
errors.append(f"id '{level['id']}' différent du dossier '{path.parent.name}'")
|
||||
if require_en:
|
||||
errors.extend(f"traduction `en` manquante : {where}" for where in missing_english(level))
|
||||
for where, code in code_snippets(level):
|
||||
try:
|
||||
compile(code, where, "exec")
|
||||
except SyntaxError as exc:
|
||||
errors.append(f"{where} : le code ne compile pas ({exc.msg}, ligne {exc.lineno})")
|
||||
return errors
|
||||
|
||||
|
||||
def validate_manifest(known_ids: set[str]) -> list[str]:
|
||||
manifest = json.loads((LEVELS_DIR / "manifest.json").read_text(encoding="utf-8"))
|
||||
errors: list[str] = []
|
||||
listed = [entry["id"] for entry in manifest["levels"]]
|
||||
for level_id in listed:
|
||||
if level_id not in known_ids:
|
||||
errors.append(f"manifest : '{level_id}' n'a pas de level.yaml")
|
||||
for level_id in sorted(known_ids - set(listed)):
|
||||
errors.append(f"manifest : '{level_id}' existe mais n'est pas référencé")
|
||||
for entry in manifest["levels"]:
|
||||
for required in entry.get("requires", []):
|
||||
if required not in listed:
|
||||
errors.append(f"manifest : '{entry['id']}' requiert '{required}' inconnu")
|
||||
return errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--allow-missing-en", action="store_true", help="n'exige pas les traductions en")
|
||||
args = parser.parse_args()
|
||||
|
||||
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
||||
jsonschema.Draft202012Validator.check_schema(schema)
|
||||
|
||||
files = sorted(LEVELS_DIR.glob("*/level.yaml"))
|
||||
failed = False
|
||||
for path in files:
|
||||
errors = validate_level(path, schema, require_en=not args.allow_missing_en)
|
||||
status = "OK " if not errors else "KO "
|
||||
print(f"{status} {path.parent.name}")
|
||||
for message in errors:
|
||||
print(f" - {message}")
|
||||
failed = failed or bool(errors)
|
||||
|
||||
for message in validate_manifest({path.parent.name for path in files}):
|
||||
print(f"KO {message}")
|
||||
failed = True
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env bash
|
||||
# Télécharge Pyodide (version épinglée) et l'installe dans vendor/pyodide/.
|
||||
# Pyodide doit être servi depuis le même domaine (COEP require-corp interdit le CDN cross-origin).
|
||||
set -euo pipefail
|
||||
|
||||
PYODIDE_VERSION="314.0.7"
|
||||
PYODIDE_SHA256="2abdcc2e35208af406e07724cffa85bc582ced97e9028383ecf5462541393f95"
|
||||
URL="https://github.com/pyodide/pyodide/releases/download/${PYODIDE_VERSION}/pyodide-core-${PYODIDE_VERSION}.tar.bz2"
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
TARGET="${ROOT}/vendor/pyodide"
|
||||
WORK="$(mktemp -d)"
|
||||
trap 'rm -rf "${WORK}"' EXIT
|
||||
|
||||
if [[ -f "${TARGET}/.version" && "$(cat "${TARGET}/.version")" == "${PYODIDE_VERSION}" ]]; then
|
||||
echo "Pyodide ${PYODIDE_VERSION} déjà installé dans ${TARGET}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Téléchargement de Pyodide ${PYODIDE_VERSION}..."
|
||||
curl --fail --location --silent --show-error --output "${WORK}/pyodide.tar.bz2" "${URL}"
|
||||
|
||||
echo "${PYODIDE_SHA256} ${WORK}/pyodide.tar.bz2" | sha256sum --check --status \
|
||||
|| { echo "Somme de contrôle invalide pour ${URL}" >&2; exit 1; }
|
||||
|
||||
mkdir -p "${WORK}/extract"
|
||||
tar --extract --bzip2 --file "${WORK}/pyodide.tar.bz2" --directory "${WORK}/extract"
|
||||
|
||||
rm -rf "${TARGET}"
|
||||
mkdir -p "${ROOT}/vendor"
|
||||
mv "${WORK}/extract/pyodide" "${TARGET}"
|
||||
echo "${PYODIDE_VERSION}" > "${TARGET}/.version"
|
||||
echo "Pyodide ${PYODIDE_VERSION} installé dans ${TARGET}"
|
||||
@@ -0,0 +1,25 @@
|
||||
import { AudioEngine } from '../../app/js/core/AudioEngine.js';
|
||||
import { VoiceEngine } from '../../app/js/core/VoiceEngine.js';
|
||||
import assert from 'node:assert';
|
||||
let osc = 0;
|
||||
const node = () => ({ connect: (n) => n, start() {}, stop() {}, frequency: {}, gain: { setValueAtTime() {}, linearRampToValueAtTime() {} } });
|
||||
const ctx = { state: 'suspended', currentTime: 0, destination: {}, resume: async function () { this.state = 'running'; }, createOscillator: () => { osc++; return node(); }, createGain: node };
|
||||
const a = new AudioEngine({ contextFactory: () => ctx });
|
||||
assert.equal(a.play('success_small'), false); // pas débloqué
|
||||
await a.unlock();
|
||||
assert.equal(a.play('success_small'), true); assert.equal(osc, 2);
|
||||
assert.equal(a.play('nope'), false);
|
||||
a.setEnabled(false); assert.equal(a.play('error'), false);
|
||||
a.setEnabled(true); a.setVolume(5); assert.equal(a.volume, 1);
|
||||
// Voix
|
||||
const spoken = [];
|
||||
class U { constructor(t) { this.text = t; } }
|
||||
const synth = { cancel() { spoken.push('cancel'); }, getVoices: () => [{ lang: 'en-GB' }, { lang: 'fr-CA' }, { lang: 'fr-FR' }],
|
||||
speak(u) { spoken.push(u); setTimeout(() => u.onend(), 0); } };
|
||||
const v = new VoiceEngine({ synth, Utterance: U });
|
||||
assert.equal(await v.speak('Utilise `print()` ici', 'fr'), true);
|
||||
const u = spoken.at(-1); assert.equal(u.text, 'Utilise print() ici'); assert.equal(u.voice.lang, 'fr-FR'); assert.equal(u.lang, 'fr-FR');
|
||||
v.setRate(9); assert.equal(v.rate, 2);
|
||||
v.setEnabled(false); assert.equal(await v.speak('x'), false);
|
||||
assert.equal(new VoiceEngine({ synth: null, Utterance: undefined }).supported, false);
|
||||
console.log('audio/voice ok');
|
||||
@@ -0,0 +1,26 @@
|
||||
import { ErrorTranslator } from '../../app/js/core/ErrorTranslator.js';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import assert from 'node:assert';
|
||||
const d = new URL('../../app/js/i18n/', import.meta.url).pathname;
|
||||
const fr = JSON.parse(readFileSync(d + 'errors.fr.json')), en = JSON.parse(readFileSync(d + 'errors.en.json'));
|
||||
assert.deepEqual(Object.keys(fr), Object.keys(en));
|
||||
for (const k of Object.keys(fr)) assert.deepEqual(Object.keys(fr[k]), ['title', 'explanation', 'tip']);
|
||||
const t = new ErrorTranslator({ fr, en });
|
||||
// Messages réels produits par CPython (version locale) pour valider les motifs.
|
||||
const cases = ['print(nom)', 'print("a', 'print("a"', 'if x\n pass', 'print "a"', '1+"a"', '"a"+1', '"a"()', 'int("abc")', 'float("x,y")', '[1][5]', '{}["k"]', '(1).foo', 'import nope', '1/0', 'if True:\npass', 'def f(a): pass\nf()', '2x', 'x = 1\ndef g():\n print(x)\n x = 2\ng()'];
|
||||
const py = execFileSync('python3', ['-I', '-c', `
|
||||
import json,sys
|
||||
out=[]
|
||||
for c in json.loads(sys.argv[1]):
|
||||
try: exec(compile(c,'<c>','exec'),{})
|
||||
except BaseException as e: out.append({'type':type(e).__name__,'message':str(e),'lineno':getattr(e,'lineno',None),'traceback':''})
|
||||
print(json.dumps(out))`, JSON.stringify(cases)]);
|
||||
for (const e of JSON.parse(py)) {
|
||||
const r = t.translate(e, 'fr');
|
||||
console.log(e.type.padEnd(20), '|', r.title);
|
||||
assert.ok(!/\{\w+\}/.test(r.title + r.explanation + r.tip), 'placeholder non résolu: ' + r.title);
|
||||
}
|
||||
assert.equal(t.translate({ type: 'NameError', message: "name 'nom' is not defined" }, 'en').title, 'Python doesn\'t know "nom"');
|
||||
assert.equal(t.translate({ type: 'Weird', message: 'boom' }).title, 'Une erreur est survenue : Weird');
|
||||
console.log('translator ok');
|
||||
@@ -0,0 +1,40 @@
|
||||
// Exécuté dans un worker_threads : émule l'environnement navigateur minimal attendu par
|
||||
// python-worker.js (self, fetch de file://) pour le tester sous Node avec le vrai Pyodide.
|
||||
import { parentPort, workerData } from 'node:worker_threads';
|
||||
import { readFile, copyFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const listeners = [];
|
||||
globalThis.self = {
|
||||
addEventListener: (type, listener) => listeners.push(listener),
|
||||
postMessage: (message) => parentPort.postMessage(message),
|
||||
};
|
||||
// Les messages reçus avant le chargement du worker sont mis en file puis rejoués.
|
||||
const queue = [];
|
||||
let loaded = false;
|
||||
parentPort.on('message', (data) => {
|
||||
if (loaded) {
|
||||
listeners.forEach((listener) => listener({ data }));
|
||||
} else {
|
||||
queue.push(data);
|
||||
}
|
||||
});
|
||||
|
||||
// Le runner Python est demandé par URL relative au worker : on le redirige vers le fichier réel.
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (input, ...rest) => {
|
||||
if (String(input).includes('pyquest_runner.py')) {
|
||||
const text = await readFile(workerData.runnerPath, 'utf8');
|
||||
return { ok: true, text: async () => text };
|
||||
}
|
||||
return realFetch(input, ...rest);
|
||||
};
|
||||
|
||||
// Node lit un .js sans package.json comme CommonJS : on charge une copie .mjs du worker.
|
||||
const copy = join(tmpdir(), `pyquest-worker-${process.pid}.mjs`);
|
||||
await copyFile(workerData.workerPath, copy);
|
||||
await import(pathToFileURL(copy).href);
|
||||
loaded = true;
|
||||
queue.splice(0).forEach((data) => listeners.forEach((listener) => listener({ data })));
|
||||
@@ -0,0 +1,15 @@
|
||||
import { LessonEngine } from '../../app/js/core/LessonEngine.js';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import assert from 'node:assert';
|
||||
const root = new URL('../../', import.meta.url).pathname.replace(/\/$/, '');
|
||||
const e = new LessonEngine({ levelsUrl: 'http://x/levels/', fetchFn: async (u) => {
|
||||
try { const t = await readFile(root + new URL(u).pathname, 'utf8'); return { ok: true, text: async () => t }; }
|
||||
catch { return { ok: false, status: 404 }; } } });
|
||||
assert.deepEqual((await e.listLevels()).map((l) => l.id), ['00-intro', '01-hello', '02-variables']);
|
||||
const s = await e.startLevel('02-variables', 'en');
|
||||
assert.equal(s.title, 'Variables and types'); assert.equal(s.stepCount, 7);
|
||||
assert.equal(s.step.type, 'explain');
|
||||
while (s.next()); assert.ok(s.onMission); assert.equal(s.mission.tests[0].message, 'tip must equal bill * rate.');
|
||||
const f = await e.startLevel('01-hello', 'fr'); f.next(); f.next(); assert.deepEqual(f.step.hints.length, 2);
|
||||
await assert.rejects(e.loadLevel('99-nope'));
|
||||
console.log('lesson ok');
|
||||
@@ -0,0 +1,25 @@
|
||||
import { ProgressStore } from '../../app/js/core/ProgressStore.js';
|
||||
import { MemoryKeyValueStore } from '../../app/js/core/KeyValueStores.js';
|
||||
import assert from 'node:assert';
|
||||
const d = (s) => new Date(s + 'T10:00:00');
|
||||
const kv = new MemoryKeyValueStore();
|
||||
const p = new ProgressStore(kv); await p.load();
|
||||
let r = await p.completeLevel('00-intro', 10, d('2026-10-14'));
|
||||
assert.deepEqual([r.xpGained, r.newBadges, r.streak.current], [10, ['first_level'], 1]);
|
||||
r = await p.completeLevel('00-intro', 10, d('2026-10-14'));
|
||||
assert.deepEqual([r.xpGained, r.alreadyCompleted], [0, true]);
|
||||
r = await p.completeLevel('01-hello', 20, d('2026-10-15'));
|
||||
assert.equal(r.streak.current, 2);
|
||||
r = await p.completeLevel('02-variables', 70, d('2026-10-17')); // jour manqué
|
||||
assert.deepEqual([r.streak.current, r.streak.best, r.newBadges.sort()], [1, 2, ['three_levels', 'xp_100']]);
|
||||
assert.equal(p.snapshot().xp, 100);
|
||||
// Persistance + export/import
|
||||
const p2 = new ProgressStore(kv); assert.equal((await p2.load()).xp, 100);
|
||||
const other = new ProgressStore(new MemoryKeyValueStore()); await other.load();
|
||||
await other.completeLevel('05-decide', 40, d('2026-10-20'));
|
||||
const merged = await p2.import(other.export());
|
||||
assert.equal(merged.xp, 140); assert.equal(Object.keys(merged.completedLevels).length, 4);
|
||||
assert.equal(merged.streak.lastDay, '2026-10-20');
|
||||
await assert.rejects(p2.import('{"version":99}'));
|
||||
await assert.rejects(new ProgressStore(kv).completeLevel('x', 1));
|
||||
console.log('progress ok');
|
||||
@@ -0,0 +1,62 @@
|
||||
// Test d'intégration : le vrai python-worker.js avec le vrai Pyodide (vendor/pyodide requis).
|
||||
// Ignoré si Pyodide n'est pas installé (make vendor-pyodide).
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert';
|
||||
|
||||
const root = new URL('../../', import.meta.url).pathname;
|
||||
const indexURL = `${root}vendor/pyodide/`;
|
||||
|
||||
test('worker Python sous Pyodide', { skip: !existsSync(`${indexURL}pyodide.mjs`) && 'vendor/pyodide absent' }, async () => {
|
||||
const worker = new Worker(new URL('./helpers/worker-shim.mjs', import.meta.url), {
|
||||
workerData: { workerPath: `${root}app/js/workers/python-worker.js`, runnerPath: `${root}app/python/pyquest_runner.py` },
|
||||
});
|
||||
const interruptBuffer = new SharedArrayBuffer(1);
|
||||
const waiters = new Map();
|
||||
const stdout = [];
|
||||
worker.on('message', (message) => {
|
||||
if (message.type === 'stdout') stdout.push(message.text);
|
||||
const key = message.type === 'result' ? message.id : 'init';
|
||||
if (['result', 'ready', 'init_error'].includes(message.type)) waiters.get(key)?.(message);
|
||||
});
|
||||
const wait = (key) =>
|
||||
new Promise((resolve, reject) => {
|
||||
waiters.set(key, resolve);
|
||||
worker.once('error', reject);
|
||||
});
|
||||
const run = (id, code, collect = []) => {
|
||||
const done = wait(id);
|
||||
worker.postMessage({ type: 'run_code', id, code, collect });
|
||||
return done;
|
||||
};
|
||||
|
||||
try {
|
||||
const init = wait('init');
|
||||
worker.postMessage({ type: 'init', indexURL, interruptBuffer });
|
||||
assert.deepEqual(await init, { type: 'ready', interruptible: true });
|
||||
|
||||
let result = await run(1, 'x = 10.0\nprint("hé")\nprint(x)', ['x']);
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(stdout.join(''), 'hé\n10.0\n');
|
||||
assert.deepEqual(result.variables.x, { type: 'float', repr: '10.0', value: 10 });
|
||||
|
||||
result = await run(2, 'print(nom)');
|
||||
assert.deepEqual([result.error.type, result.error.lineno], ['NameError', 1]);
|
||||
|
||||
result = await run(3, 'y = x + 1', ['y']); // l'espace de noms persiste
|
||||
assert.equal(result.variables.y.value, 11);
|
||||
|
||||
result = await run(4, 'input("?")');
|
||||
assert.equal(result.error.type, 'EOFError');
|
||||
|
||||
const looping = run(5, 'while True:\n pass');
|
||||
setTimeout(() => (new Uint8Array(interruptBuffer)[0] = 2), 500);
|
||||
assert.equal((await looping).error.type, 'KeyboardInterrupt');
|
||||
|
||||
result = await run(6, 'print("après")'); // le worker reste utilisable
|
||||
assert.equal(result.ok, true);
|
||||
} finally {
|
||||
await worker.terminate();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ValidationEngine } from '../../app/js/core/ValidationEngine.js';
|
||||
import assert from 'node:assert';
|
||||
const v = new ValidationEngine();
|
||||
const ok = { ok: true, error: null, variables: { total: { type: 'float', value: 10, repr: '10.0' } } };
|
||||
const tests = [
|
||||
{ kind: 'var_equals', name: 'total', value: 10.0 },
|
||||
{ kind: 'var_type_is', name: 'total', value: 'float' },
|
||||
{ kind: 'stdout_equals', value: '10.0\n' },
|
||||
{ kind: 'stdout_matches_regex', value: '^[^\\n]+\\n$' },
|
||||
];
|
||||
assert.deepEqual(ValidationEngine.variablesToCollect(tests), ['total']);
|
||||
assert.ok(v.validate(tests, { stdout: '10.0\n', result: ok }).passed);
|
||||
const bad = v.validate(tests, { stdout: '10\n', result: { ...ok, variables: { total: { type: 'int', value: 10 } } } });
|
||||
assert.deepEqual(bad.results.map((r) => r.reason), [null, 'type_mismatch', 'stdout_mismatch', null]);
|
||||
assert.equal(v.validate([{ kind: 'no_syntax_error' }], { stdout: '', result: { ok: false, error: { type: 'SyntaxError' }, variables: {} } }).results[0].reason, 'syntax_error');
|
||||
assert.equal(v.validate([{ kind: 'no_syntax_error' }], { stdout: '', result: { ok: false, error: { type: 'NameError' }, variables: {} } }).passed, false);
|
||||
assert.equal(v.validate([{ kind: 'var_equals', name: 'x', value: 1 }], { stdout: '', result: ok }).results[0].reason, 'variable_missing');
|
||||
console.log('validation ok');
|
||||
@@ -0,0 +1,26 @@
|
||||
import { PyodideWorkerClient } from '../../app/js/core/PyodideWorkerClient.js';
|
||||
import assert from 'node:assert';
|
||||
let spawned = 0;
|
||||
globalThis.Worker = class {
|
||||
constructor() { spawned++; this.l = {}; this.mode = spawned; }
|
||||
addEventListener(t, f) { this.l[t] = f; }
|
||||
terminate() { this.dead = true; }
|
||||
postMessage(m) {
|
||||
const r = (d) => queueMicrotask(() => !this.dead && this.l.message({ data: d }));
|
||||
if (m.type === 'init') r({ type: 'ready', interruptible: false });
|
||||
if (m.type === 'run_code' && m.code === 'ok') { r({ type: 'stdout', id: m.id, text: 'hi\n' }); r({ type: 'result', id: m.id, ok: true, error: null, variables: {} }); }
|
||||
}
|
||||
};
|
||||
const c = new PyodideWorkerClient({ indexURL: '/v/', workerUrl: 'x' });
|
||||
let out = '';
|
||||
const res = await c.run('ok', { onStdout: (t) => (out += t) });
|
||||
assert.equal(out, 'hi\n'); assert.equal(res.ok, true); assert.equal(res.type, undefined);
|
||||
const hang = c.run('loop');
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
c.interrupt();
|
||||
const h = await hang;
|
||||
assert.equal(h.error.type, 'KeyboardInterrupt');
|
||||
assert.equal(spawned, 2);
|
||||
assert.equal((await c.run('ok')).ok, true);
|
||||
c.dispose();
|
||||
console.log('client ok');
|
||||
Binary file not shown.
@@ -0,0 +1,49 @@
|
||||
"""Tests du runner de cellules (exécutés avec CPython ; même code que sous Pyodide)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "app" / "python"))
|
||||
|
||||
import pyquest_runner as runner # noqa: E402
|
||||
|
||||
|
||||
def run(code: str, collect: list[str] | None = None) -> dict[str, Any]:
|
||||
return json.loads(runner.run_cell(code, json.dumps(collect or [])))
|
||||
|
||||
|
||||
class RunnerTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
runner.reset_namespace()
|
||||
|
||||
def test_variables_are_described(self) -> None:
|
||||
result = run("x = 10.0", ["x"])
|
||||
self.assertTrue(result["ok"])
|
||||
self.assertEqual(result["variables"]["x"], {"type": "float", "repr": "10.0", "value": 10.0})
|
||||
|
||||
def test_namespace_persists_until_reset(self) -> None:
|
||||
run("a = 1")
|
||||
self.assertEqual(run("b = a + 1", ["b"])["variables"]["b"]["value"], 2)
|
||||
runner.reset_namespace()
|
||||
self.assertEqual(run("a")["error"]["type"], "NameError")
|
||||
|
||||
def test_runtime_error_has_line_and_clean_traceback(self) -> None:
|
||||
error = run("x = 1\n1 / 0")["error"]
|
||||
self.assertEqual((error["type"], error["lineno"]), ("ZeroDivisionError", 2))
|
||||
self.assertNotIn("run_cell", error["traceback"])
|
||||
|
||||
def test_syntax_error(self) -> None:
|
||||
error = run("def f(:\n pass")["error"]
|
||||
self.assertEqual((error["type"], error["lineno"]), ("SyntaxError", 1))
|
||||
|
||||
def test_non_finite_float_has_no_json_value(self) -> None:
|
||||
self.assertIsNone(run("x = float('inf')", ["x"])["variables"]["x"]["value"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user