From cc7ccd0834e25471806db5e9fc0fe255f52282f6 Mon Sep 17 00:00:00 2001 From: Abhik Sarkar Date: Thu, 5 Nov 2026 13:24:26 +0530 Subject: [PATCH] style: establish the production Ruff baseline Resolve existing lint and formatting debt in production code, scripts, and tests before enabling the required gate. Preserve executable behavior, learner files, runtime text, and generated documentation outputs. Refs #132. --- docs/assets/reviews/style-baseline.svg | 215 +++++++++++ pythonlings/app.py | 6 +- pythonlings/cli.py | 82 ++-- pythonlings/core/curriculum.py | 7 +- pythonlings/core/docs.py | 4 +- pythonlings/core/doctor.py | 37 +- pythonlings/core/manifest.py | 27 +- pythonlings/core/reset.py | 12 +- pythonlings/core/runner.py | 7 +- pythonlings/core/state.py | 3 +- pythonlings/core/workspace.py | 5 +- pythonlings/screens/docs.py | 11 +- pythonlings/screens/topic_picker.py | 4 +- pythonlings/screens/track.py | 17 +- pythonlings/screens/welcome.py | 6 +- pythonlings/widgets/output_panel.py | 8 +- pythonlings/widgets/progress.py | 3 +- scripts/fetch_python_docs.py | 397 +++++++++++++++++--- tests/integration/test_cli_cold_start.py | 16 +- tests/integration/test_cli_doctor.py | 15 +- tests/integration/test_cli_dry_run.py | 5 +- tests/integration/test_cli_reset.py | 13 +- tests/integration/test_cli_solution.py | 13 +- tests/integration/test_cli_topics.py | 4 +- tests/integration/test_cli_verify.py | 81 ++-- tests/integration/test_cli_workspace.py | 21 +- tests/integration/test_first_run.py | 15 +- tests/integration/test_solution_verify.py | 5 +- tests/test_functional_assertion_messages.py | 1 - tests/test_json_checks_messages.py | 2 +- tests/tui/test_app_pilot.py | 49 ++- tests/tui/test_editor_pane.py | 2 +- tests/tui/test_output_panel.py | 21 +- tests/tui/test_welcome_pilot.py | 5 +- tests/unit/test_check_namespaces.py | 8 +- tests/unit/test_curriculum.py | 35 +- tests/unit/test_docs.py | 5 +- tests/unit/test_doctor.py | 13 +- tests/unit/test_exercise.py | 6 +- tests/unit/test_manifest.py | 49 ++- tests/unit/test_reset.py | 19 +- tests/unit/test_state.py | 6 +- tests/unit/test_type_hints1_check.py | 4 +- tests/unit/test_workspace.py | 9 +- 44 files changed, 1034 insertions(+), 239 deletions(-) create mode 100644 docs/assets/reviews/style-baseline.svg diff --git a/docs/assets/reviews/style-baseline.svg b/docs/assets/reviews/style-baseline.svg new file mode 100644 index 0000000..214ac9b --- /dev/null +++ b/docs/assets/reviews/style-baseline.svg @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + pythonlings + + + + + + + + + + ⭘pythonlings — topic: alpha +Topic: ░░░░░░░░░░░░░░░░░░░░ 0/2 (0%)   Overall: ░░░░░░░░░░░░░░░░░░░░ 0/3 (0%) +▊▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▎│ +▊1  # I AM NOT DONE▎│a10/2 complete +▊2  x = ??? ▎│../../../../../../tmp/tmphdcr3f2w/work/exercises/alpha/a1.py +▊3  ▎│Edit the code on the left. Checks update automatically. +▊▎│ +▊▎│─────────────────────────────────────────────────────────────── +▊▎│ +▊▎│Goal +▊▎│a1 +▊▎│ +▊▎│Docs +▊▎│https://docs.python.org/3/tutorial/introduction.html +▊▎│ +▊▎│Not passing yet +▊▎│ +▊▎│Read the details, fix the code, then pause typing. +▊▎│alpha one. +▊▎│ +▊▎│Details +▊▎│Traceback (most recent call last): +▊▎│  File "/tmp/tmpocrb5lvs.py", line 13, in <module> +▊▎│    exec(compile(exercise_src, str(exercise_path), 'exec'), +▊▎│namespace) +▊▎│         ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +▊▎│  File "/tmp/tmphdcr3f2w/work/exercises/alpha/a1.py", line 2 +▊▎│    x = ??? +▊▎│        ^ +▊▎│SyntaxError: invalid syntax +▊▎│ +▊▎│ +▊▎│ +▊▎│ +▊▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▎│ + f1 Hint  f2 Reset  f3 List  f4 Topics  f5 Docs  esc Quit ▏^p palette + + + diff --git a/pythonlings/app.py b/pythonlings/app.py index ac47602..bf0e033 100644 --- a/pythonlings/app.py +++ b/pythonlings/app.py @@ -5,8 +5,10 @@ from textual.app import App -from pythonlings.core.manifest import Manifest, load as load_manifest -from pythonlings.core.state import State, load as load_state, next_pending +from pythonlings.core.manifest import Manifest +from pythonlings.core.manifest import load as load_manifest +from pythonlings.core.state import State, next_pending +from pythonlings.core.state import load as load_state from pythonlings.screens.topic_picker import TopicPickerScreen from pythonlings.screens.track import TrackScreen diff --git a/pythonlings/cli.py b/pythonlings/cli.py index 4de9f45..b858295 100644 --- a/pythonlings/cli.py +++ b/pythonlings/cli.py @@ -3,21 +3,29 @@ import argparse import sys -from importlib.metadata import PackageNotFoundError, version as _package_version +from importlib.metadata import PackageNotFoundError +from importlib.metadata import version as _package_version from pathlib import Path from pythonlings.core.workspace import default_workspace_root try: __version__ = _package_version("pythonlings") -except PackageNotFoundError: # running from a source checkout without an install +except ( + PackageNotFoundError +): # running from a source checkout without an install __version__ = "0.0.0+unknown" # Status glyphs, with ASCII stand-ins for consoles whose encoding cannot # represent them (a Windows code page, or LC_ALL=C). The fallbacks stay one # column wide so aligned output keeps its shape. -_ASCII_FALLBACK = {"\u2713": "+", "\u2717": "x", "\u25cf": ">", "\U0001f512": "-"} +_ASCII_FALLBACK = { + "\u2713": "+", + "\u2717": "x", + "\u25cf": ">", + "\U0001f512": "-", +} def _encodable(stream: object, text: str) -> bool: @@ -39,7 +47,7 @@ def _symbol(stream: object, glyph: str) -> str: def _write(stream, text: str) -> None: - """Write captured output, degrading characters the encoding cannot represent. + """Write output, replacing characters the encoding cannot represent. Check files print their own status line (`print("variables1 \u2713")`), so curriculum output reaches us containing glyphs a strict-ASCII console @@ -49,14 +57,20 @@ def _write(stream, text: str) -> None: stream.write(text) except UnicodeEncodeError: encoding = getattr(stream, "encoding", None) or "ascii" - stream.write(text.encode(encoding, "replace").decode(encoding, "replace")) + stream.write( + text.encode(encoding, "replace").decode(encoding, "replace") + ) def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="pythonlings") - parser.add_argument("--version", action="version", version=f"pythonlings {__version__}") parser.add_argument( - "--debug", action="store_true", help="Write debug output to .pythonlings_debug.log." + "--version", action="version", version=f"pythonlings {__version__}" + ) + parser.add_argument( + "--debug", + action="store_true", + help="Write debug output to .pythonlings_debug.log.", ) parser.add_argument( "--root", @@ -69,10 +83,14 @@ def _build_parser() -> argparse.ArgumentParser: p_init = sub.add_parser("init", help="Create a pythonlings workspace.") p_init.add_argument("--path", type=Path, default=default_workspace_root()) p_init.add_argument( - "--force", action="store_true", help="Overwrite managed workspace files." + "--force", + action="store_true", + help="Overwrite managed workspace files.", ) - p_update = sub.add_parser("update", help="Update an existing pythonlings workspace.") + p_update = sub.add_parser( + "update", help="Update an existing pythonlings workspace." + ) p_update.add_argument("--path", type=Path, default=None) sub.add_parser("watch", help="Launch the TUI in watch mode (default).") @@ -81,7 +99,9 @@ def _build_parser() -> argparse.ArgumentParser: p_run = sub.add_parser("run", help="Run a single exercise.") p_run.add_argument("name") - p_dry_run = sub.add_parser("dry-run", help="Run one exercise non-interactively.") + p_dry_run = sub.add_parser( + "dry-run", help="Run one exercise non-interactively." + ) p_dry_run.add_argument("name") p_solution = sub.add_parser( @@ -92,15 +112,23 @@ def _build_parser() -> argparse.ArgumentParser: p_hint = sub.add_parser("hint", help="Print the hint for an exercise.") p_hint.add_argument("name") - p_list = sub.add_parser("list", help="List topics, or one topic's exercises.") - p_list.add_argument("topic", nargs="?", help="Show exercises of this topic.") + p_list = sub.add_parser( + "list", help="List topics, or one topic's exercises." + ) + p_list.add_argument( + "topic", nargs="?", help="Show exercises of this topic." + ) p_start = sub.add_parser("start", help="Launch the TUI on a topic's track.") p_start.add_argument("topic") - p_reset = sub.add_parser("reset", help="Restore an exercise from its snapshot.") + p_reset = sub.add_parser( + "reset", help="Restore an exercise from its snapshot." + ) p_reset.add_argument("name") - p_reset.add_argument("--yes", action="store_true", help="Skip the confirmation prompt.") + p_reset.add_argument( + "--yes", action="store_true", help="Skip the confirmation prompt." + ) p_verify = sub.add_parser( "verify", help="Run every exercise, or just one topic's." @@ -190,7 +218,8 @@ def _cmd_verify(root: Path, topic: str | None) -> int: def _cmd_list(root: Path, topic: str | None) -> int: from pythonlings.core.manifest import load as load_manifest - from pythonlings.core.state import load as load_state, next_pending + from pythonlings.core.state import load as load_state + from pythonlings.core.state import next_pending manifest = load_manifest(root) state = load_state(root) @@ -199,8 +228,10 @@ def _cmd_list(root: Path, topic: str | None) -> int: for name in manifest.topics(): exs = manifest.exercises_in(name) done = sum(1 for ex in exs if ex.name in state.completed) - mark = _symbol(sys.stdout, "✓") if done == len(exs) else ( - _symbol(sys.stdout, "●") if done else " " + mark = ( + _symbol(sys.stdout, "✓") + if done == len(exs) + else (_symbol(sys.stdout, "●") if done else " ") ) print(f" {mark} {name} {done}/{len(exs)}") return 0 @@ -252,13 +283,16 @@ def _cmd_run(root: Path, name: str) -> int: if result.stderr: _write(sys.stderr, result.stderr) if result.timed_out: - sys.stderr.write(f"pythonlings: {name} timed out after {result.duration_s:.1f}s\n") + sys.stderr.write( + f"pythonlings: {name} timed out after {result.duration_s:.1f}s\n" + ) return 1 if result.exit_code != 0: return 1 if ex.is_pending(): sys.stderr.write( - f"pythonlings: tests pass but the '# I AM NOT DONE' marker is still in {name}.\n" + "pythonlings: tests pass but the '# I AM NOT DONE' marker " + f"is still in {name}.\n" ) return 1 return 0 @@ -290,7 +324,8 @@ def _cmd_solution(root: Path, name: str) -> int: def _cmd_reset(root: Path, name: str, yes: bool) -> int: from pythonlings.core.manifest import load as load_manifest from pythonlings.core.reset import ResetError, restore - from pythonlings.core.state import load as load_state, save as save_state + from pythonlings.core.state import load as load_state + from pythonlings.core.state import save as save_state manifest = load_manifest(root) try: @@ -369,7 +404,9 @@ def main(argv: list[str] | None = None) -> int: ) except (OSError, RuntimeError) as exc: if args.command == "doctor": - unresolved = args.root if args.root is not None else Path(".") + unresolved = ( + args.root if args.root is not None else Path(".") + ) return _cmd_doctor(unresolved, resolution_error=exc) raise root = resolved.root @@ -422,9 +459,11 @@ def main(argv: list[str] | None = None) -> int: start_topic = getattr(args, "topic", None) if start_topic is not None: from pythonlings.core.manifest import load as load_manifest + if _resolve_topic(load_manifest(root), start_topic) is None: return 2 from pythonlings.app import run_tui # lazy: Textual is heavy + return run_tui( root, start_topic, @@ -437,6 +476,7 @@ def main(argv: list[str] | None = None) -> int: except Exception as e: # Manifest errors and other startup failures use exit code 2. from pythonlings.core.manifest import ManifestError + if isinstance(e, ManifestError): sys.stderr.write(f"pythonlings: {e}\n") return 2 diff --git a/pythonlings/core/curriculum.py b/pythonlings/core/curriculum.py index 0f483ea..9886bdb 100644 --- a/pythonlings/core/curriculum.py +++ b/pythonlings/core/curriculum.py @@ -68,7 +68,9 @@ def _write_workspace_gitignore(root: Path) -> None: existing = "" existing_lines = set(existing.splitlines()) - missing_lines = [line for line in GITIGNORE_LINES if line not in existing_lines] + missing_lines = [ + line for line in GITIGNORE_LINES if line not in existing_lines + ] if not missing_lines: return @@ -95,7 +97,8 @@ def init_workspace(path: Path, *, force: bool = False) -> Path: if path.exists() and any(path.iterdir()) and not force: raise WorkspaceError( f"{path} isn't empty and isn't a pythonlings workspace. " - "Pick another location with --path , or --force to set up here anyway." + "Pick another location with --path , " + "or --force to set up here anyway." ) src_root = source_root().resolve() if path == src_root: diff --git a/pythonlings/core/docs.py b/pythonlings/core/docs.py index 34deefc..9ff987a 100644 --- a/pythonlings/core/docs.py +++ b/pythonlings/core/docs.py @@ -44,7 +44,9 @@ def load_snippet(topic: str, source_url: str = "") -> DocSnippet | None: def _load_index() -> dict[str, Any] | None: try: docs_root = resources.files("pythonlings.docs") - return json.loads((docs_root / "index.json").read_text(encoding="utf-8")) + return json.loads( + (docs_root / "index.json").read_text(encoding="utf-8") + ) except (FileNotFoundError, json.JSONDecodeError, ModuleNotFoundError): return None diff --git a/pythonlings/core/doctor.py b/pythonlings/core/doctor.py index bbaf145..60ddbfe 100644 --- a/pythonlings/core/doctor.py +++ b/pythonlings/core/doctor.py @@ -1,3 +1,4 @@ +# pythonlings/core/doctor.py from __future__ import annotations import errno @@ -67,7 +68,8 @@ def run_diagnostics( CheckResult( "Workspace", CheckStatus.FAILURE, - f"could not resolve {display_root}: {exc}; check the path and symlinks", + f"could not resolve {display_root}: {exc}; " + "check the path and symlinks", ) ) return DoctorReport(root=display_root, checks=tuple(checks)) @@ -152,7 +154,8 @@ def _check_workspace(root: Path) -> CheckResult: "Workspace", CheckStatus.FAILURE, f"missing or invalid required paths: {', '.join(invalid)}; " - "run `pythonlings update --path ` or initialize a new workspace", + "run `pythonlings update --path ` " + "or initialize a new workspace", ) return CheckResult("Workspace", CheckStatus.OK, str(root)) @@ -238,10 +241,13 @@ def _check_state(root: Path) -> CheckResult: return CheckResult( "Progress state", CheckStatus.WARNING, - f"state.json is a broken symlink: {exc}; replace or remove the link", + f"state.json is a broken symlink: {exc}; " + "replace or remove the link", ) if not path.exists(): - return CheckResult("Progress state", CheckStatus.OK, "no progress file yet") + return CheckResult( + "Progress state", CheckStatus.OK, "no progress file yet" + ) if not path.is_file(): return CheckResult( "Progress state", @@ -255,14 +261,16 @@ def _check_state(root: Path) -> CheckResult: return CheckResult( "Progress state", CheckStatus.WARNING, - f"state.json is unreadable: {exc}; back it up before starting Pythonlings", + f"state.json is unreadable: {exc}; " + "back it up before starting Pythonlings", ) if not isinstance(data, dict): return CheckResult( "Progress state", CheckStatus.WARNING, - "state.json must contain an object; back it up before starting Pythonlings", + "state.json must contain an object; " + "back it up before starting Pythonlings", ) if data.get("format_version") != FORMAT_VERSION: return CheckResult( @@ -283,7 +291,9 @@ def _check_state(root: Path) -> CheckResult: "back up state.json before starting Pythonlings", ) return CheckResult( - "Progress state", CheckStatus.OK, f"readable ({len(completed)} completed)" + "Progress state", + CheckStatus.OK, + f"readable ({len(completed)} completed)", ) @@ -333,7 +343,8 @@ def _check_docs(manifest: Manifest | None) -> CheckResult: return CheckResult( "Bundled docs", CheckStatus.OK, - "documentation index is readable; topic coverage was not checked", + "documentation index is readable; " + "topic coverage was not checked", ) missing: list[str] = [] @@ -383,13 +394,19 @@ def _manifest_validation_error(manifest: Manifest) -> str | None: for exercise in manifest.exercises: if not isinstance(exercise.name, str) or not exercise.name: - return f"exercise name must be a non-empty string, got {exercise.name!r}" + return ( + "exercise name must be a non-empty string, " + f"got {exercise.name!r}" + ) if not isinstance(exercise.hint, str): return f"hint for {exercise.name!r} must be a string" if not isinstance(exercise.docs, str): return f"docs for {exercise.name!r} must be a string" if not exercise.path.is_file(): - return f"exercise path is not a file: {exercise.rel_path or exercise.path}" + return ( + "exercise path is not a file: " + f"{exercise.rel_path or exercise.path}" + ) if not exercise.check_path.is_file(): return ( "check path is not a file: " diff --git a/pythonlings/core/manifest.py b/pythonlings/core/manifest.py index 2727f6b..a416b81 100644 --- a/pythonlings/core/manifest.py +++ b/pythonlings/core/manifest.py @@ -20,7 +20,9 @@ def _resolve_path(path: Path, description: str) -> Path: try: return path.resolve() except (OSError, RuntimeError) as e: - raise ManifestError(f"could not resolve {description} at {path}: {e}") from e + raise ManifestError( + f"could not resolve {description} at {path}: {e}" + ) from e @dataclass(frozen=True) @@ -70,11 +72,14 @@ def load(root: Path) -> Manifest: except tomllib.TOMLDecodeError as e: raise ManifestError(f"info.toml is not valid TOML: {e}") from e except OSError as e: - raise ManifestError(f"could not read info.toml at {info_path}: {e}") from e + raise ManifestError( + f"could not read info.toml at {info_path}: {e}" + ) from e if data.get("format_version") != 1: raise ManifestError( - f"info.toml format_version must be 1, got {data.get('format_version')!r}" + "info.toml format_version must be 1, " + f"got {data.get('format_version')!r}" ) welcome_message = data.get("welcome_message", "Welcome to pythonlings!") @@ -88,10 +93,14 @@ def load(root: Path) -> Manifest: raw_exercises = data.get("exercises", []) if not isinstance(raw_exercises, list) or not raw_exercises: - raise ManifestError("info.toml must define a non-empty [[exercises]] array") + raise ManifestError( + "info.toml must define a non-empty [[exercises]] array" + ) resolved_root = _resolve_path(root, "workspace root") - exercises_root = _resolve_path(root / "exercises", "workspace exercises/ directory") + exercises_root = _resolve_path( + root / "exercises", "workspace exercises/ directory" + ) checks_root = _resolve_path(root / "checks", "workspace checks/ directory") for directory, resolved_directory in ( ("exercises", exercises_root), @@ -142,7 +151,9 @@ def load(root: Path) -> Manifest: # when the written path looks clean (e.g. exercises/link/a.py # where "link" is a symlink pointing elsewhere). Resolve and # confirm containment before touching the filesystem further. - resolved_abs_path = _resolve_path(abs_path, f"exercise path for {name!r}") + resolved_abs_path = _resolve_path( + abs_path, f"exercise path for {name!r}" + ) if not resolved_abs_path.is_relative_to(exercises_root): raise ManifestError( f"exercise {name!r} path escapes the workspace exercises/ " @@ -154,7 +165,9 @@ def load(root: Path) -> Manifest: # Derive the check path: exercises/<...> mirrors to checks/<...>. check_rel = Path("checks", *rel_path.parts[1:]) check_abs = root / check_rel - resolved_check_abs = _resolve_path(check_abs, f"check path for {name!r}") + resolved_check_abs = _resolve_path( + check_abs, f"check path for {name!r}" + ) if not resolved_check_abs.is_relative_to(checks_root): raise ManifestError( f"check path for {name!r} escapes the workspace checks/ " diff --git a/pythonlings/core/reset.py b/pythonlings/core/reset.py index a9eccc2..6012c3c 100644 --- a/pythonlings/core/reset.py +++ b/pythonlings/core/reset.py @@ -21,11 +21,16 @@ def _snapshot_path(root: Path, exercise: Exercise) -> Path: def _original_path(root: Path, exercise: Exercise) -> Path: if exercise.rel_path is None: return _snapshot_path(root, exercise) - return root / ".pythonlings" / "originals" / exercise.rel_path.relative_to("exercises") + return ( + root + / ".pythonlings" + / "originals" + / exercise.rel_path.relative_to("exercises") + ) def snapshot(root: Path, exercise: Exercise) -> None: - """Copy the pristine source into .pythonlings/originals/ if not already snapshotted.""" + """Snapshot pristine source in .pythonlings/originals/ if absent.""" snap = _original_path(root, exercise) if snap.exists(): return @@ -38,6 +43,7 @@ def restore(root: Path, exercise: Exercise) -> None: snap = _original_path(root, exercise) if not snap.exists(): raise ResetError( - f"no snapshot for {exercise.name!r}. Run 'pythonlings update' first." + f"no snapshot for {exercise.name!r}. " + "Run 'pythonlings update' first." ) shutil.copy2(snap, exercise.path) diff --git a/pythonlings/core/runner.py b/pythonlings/core/runner.py index dda8f29..d1e7f04 100644 --- a/pythonlings/core/runner.py +++ b/pythonlings/core/runner.py @@ -8,8 +8,7 @@ import tempfile import time -from pythonlings.core.exercise import Exercise -from pythonlings.core.exercise import RunResult +from pythonlings.core.exercise import Exercise, RunResult DEFAULT_TIMEOUT_S = 5.0 @@ -121,8 +120,8 @@ def run(exercise: Exercise, timeout_s: float = DEFAULT_TIMEOUT_S) -> RunResult: def run_verify( exercise: Exercise, timeout_s: float = DEFAULT_TIMEOUT_S ) -> RunResult: - """Run an exercise but treat the marker as a no-op (CI / curriculum-author mode).""" + """Run an exercise ignoring its marker (CI / curriculum-author mode).""" result = run(exercise, timeout_s=timeout_s) - # `verify` cares only about exit code; recompute passed without the marker check. + # `verify` cares only about exit code, ignoring the marker check. result.passed = result.exit_code == 0 and not result.timed_out return result diff --git a/pythonlings/core/state.py b/pythonlings/core/state.py index 5a686d0..714a11f 100644 --- a/pythonlings/core/state.py +++ b/pythonlings/core/state.py @@ -45,7 +45,8 @@ def load(root: Path) -> State: data = json.loads(path.read_text(encoding="utf-8")) if data.get("format_version") != FORMAT_VERSION: raise ValueError( - f"unsupported state format_version: {data.get('format_version')}" + "unsupported state format_version: " + f"{data.get('format_version')}" ) return State( completed=set(data.get("completed", [])), diff --git a/pythonlings/core/workspace.py b/pythonlings/core/workspace.py index c55713e..0a63005 100644 --- a/pythonlings/core/workspace.py +++ b/pythonlings/core/workspace.py @@ -1,3 +1,4 @@ +# pythonlings/core/workspace.py from __future__ import annotations import os @@ -42,7 +43,9 @@ def resolve_workspace_root( `create_if_missing`) a freshly created home workspace. """ if explicit_root is not None: - return ResolvedWorkspace(explicit_root.expanduser().resolve(), created=False) + return ResolvedWorkspace( + explicit_root.expanduser().resolve(), created=False + ) cwd = cwd.resolve() if is_workspace(cwd): diff --git a/pythonlings/screens/docs.py b/pythonlings/screens/docs.py index 5b7f3bf..c5ed44b 100644 --- a/pythonlings/screens/docs.py +++ b/pythonlings/screens/docs.py @@ -44,9 +44,16 @@ def __init__(self, exercise: Exercise) -> None: def compose(self) -> ComposeResult: yield Vertical( - Static(f"[bold]Docs: {escape(self.exercise.name)}[/bold]", id="docs-title"), + Static( + f"[bold]Docs: {escape(self.exercise.name)}[/bold]", + id="docs-title", + ), VerticalScroll( - Markdown(self._reference_markdown(), id="docs-content", open_links=False), + Markdown( + self._reference_markdown(), + id="docs-content", + open_links=False, + ), id="docs-scroll", ), _DocsFooter(_COMPACT_FOOTER_TEXT, id="docs-footer"), diff --git a/pythonlings/screens/topic_picker.py b/pythonlings/screens/topic_picker.py index c88f780..0dac216 100644 --- a/pythonlings/screens/topic_picker.py +++ b/pythonlings/screens/topic_picker.py @@ -81,7 +81,9 @@ def _preferred_topic(self) -> str | None: if done < total: return topic return self._first_incomplete_topic() or ( - self.app.manifest.topics()[0] if self.app.manifest.topics() else None + self.app.manifest.topics()[0] + if self.app.manifest.topics() + else None ) def _banner_text(self) -> str: diff --git a/pythonlings/screens/track.py b/pythonlings/screens/track.py index b0342a6..44e8ffe 100644 --- a/pythonlings/screens/track.py +++ b/pythonlings/screens/track.py @@ -11,7 +11,8 @@ from pythonlings.core.exercise import Exercise, RunResult from pythonlings.core.runner import run as run_exercise -from pythonlings.core.state import completed_count, next_pending, save as save_state +from pythonlings.core.state import completed_count, next_pending +from pythonlings.core.state import save as save_state from pythonlings.widgets.editor_pane import EditorPane from pythonlings.widgets.exercise_tree import ExerciseTree from pythonlings.widgets.output_panel import OutputPanel @@ -52,8 +53,10 @@ def celebration_message(total: int) -> str: return ( f"🎉 You finished all {total} pythonlings exercises! 🎉\n\n" "That's the whole curriculum — nicely done.\n" - f"Share it: \"I just completed all {total} pythonlings Python exercises 🎉\"\n" - "If pythonlings helped, a ⭐ on GitHub or a contribution is hugely appreciated.\n\n" + f'Share it: "I just completed all {total} ' + 'pythonlings Python exercises 🎉"\n' + "If pythonlings helped, a ⭐ on GitHub " + "or a contribution is hugely appreciated.\n\n" "Press Ctrl+Q to quit, or F4 to revisit topics." ) @@ -169,7 +172,9 @@ def on_text_area_changed(self, event: TextArea.Changed) -> None: return if self._save_timer is not None: self._save_timer.stop() - self._save_timer = self.set_timer(_DEBOUNCE_SECONDS, self._flush_and_run) + self._save_timer = self.set_timer( + _DEBOUNCE_SECONDS, self._flush_and_run + ) def _flush_and_run(self) -> None: self._save_timer = None @@ -240,7 +245,9 @@ def _apply_result(self, exercise: Exercise, result: RunResult) -> None: def action_toggle_hint(self) -> None: if self.current is None: return - self.query_one(OutputPanel).toggle_hint(self._exercise(self.current).hint) + self.query_one(OutputPanel).toggle_hint( + self._exercise(self.current).hint + ) def action_reset(self) -> None: from pythonlings.core.reset import restore diff --git a/pythonlings/screens/welcome.py b/pythonlings/screens/welcome.py index 2cf7bd1..74cc035 100644 --- a/pythonlings/screens/welcome.py +++ b/pythonlings/screens/welcome.py @@ -13,10 +13,12 @@ def welcome_text() -> str: """The first-launch explainer for the edit/save/advance loop.""" return ( - "You learn Python here by fixing small broken programs. The loop is:\n\n" + "You learn Python here by fixing small broken programs. " + "The loop is:\n\n" " 1. Edit the current exercise in the built-in editor.\n" " 2. Checks rerun automatically as you type.\n" - " 3. Remove the `# I AM NOT DONE` marker to advance to the next one.\n\n" + " 3. Remove the `# I AM NOT DONE` marker " + "to advance to the next one.\n\n" "Handy keys: F1 hint - F3 exercise list - F4 topics - " "F5 local docs - Ctrl+Q quit.\n\n" "Press Enter to start." diff --git a/pythonlings/widgets/output_panel.py b/pythonlings/widgets/output_panel.py index dd7d1c7..fd10305 100644 --- a/pythonlings/widgets/output_panel.py +++ b/pythonlings/widgets/output_panel.py @@ -137,7 +137,9 @@ def _render_header( self, exercise: Exercise, completed: int = 0, total: int = 0 ) -> None: header = self.query_one("#output-header", Static) - progress = f" [dim]{completed}/{total} complete[/dim]" if total else "" + progress = ( + f" [dim]{completed}/{total} complete[/dim]" if total else "" + ) header.update( f"[bold]{exercise.name}[/bold]{progress} " f"[dim]{self._display_path(exercise)}[/dim]\n" @@ -183,7 +185,9 @@ def toggle_hint(self, text: str) -> None: hint.remove_class("visible") else: hint.add_class("visible") - hint.update(f"[italic]Hint:[/italic] {text or '(no hint provided)'}") + hint.update( + f"[italic]Hint:[/italic] {text or '(no hint provided)'}" + ) def reset_hint(self) -> None: hint = self.query_one("#hint", Static) diff --git a/pythonlings/widgets/progress.py b/pythonlings/widgets/progress.py index 2bdff91..1d6b2aa 100644 --- a/pythonlings/widgets/progress.py +++ b/pythonlings/widgets/progress.py @@ -20,7 +20,8 @@ def format_progress( overall_bar, overall_pct = _bar(overall_completed, overall_total) return ( f"Topic: {topic_bar} {completed}/{total} ({topic_pct:.0f}%)" - f" Overall: {overall_bar} {overall_completed}/{overall_total} ({overall_pct:.0f}%)" + f" Overall: {overall_bar} {overall_completed}/{overall_total} " + f"({overall_pct:.0f}%)" ) diff --git a/scripts/fetch_python_docs.py b/scripts/fetch_python_docs.py index 3be2852..8b99c05 100644 --- a/scripts/fetch_python_docs.py +++ b/scripts/fetch_python_docs.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# scripts/fetch_python_docs.py """Fetch small local reference snippets from the official Python docs. The generated snippets are committed so learners can use pythonlings offline. @@ -19,7 +20,6 @@ from pathlib import Path from urllib.parse import urldefrag - BASE_URL = "https://docs.python.org/3/" OUTPUT = Path("pythonlings/docs") MAX_LINES = 40 @@ -36,37 +36,344 @@ class Source: SOURCES: tuple[Source, ...] = ( - Source("variables", "Variables", BASE_URL + "tutorial/introduction.html#using-python-as-a-calculator", "Assigning names with `=` lets you keep values for later expressions.", BASE_URL + "reference/simple_stmts.html#assignment-statements", "Assignment statement syntax and semantics, including multiple and unpacking targets."), - Source("strings", "Strings", BASE_URL + "library/stdtypes.html#text-sequence-type-str", "Strings are immutable text sequences with indexing, slicing, and many useful methods.", BASE_URL + "library/stdtypes.html#string-methods", "Full reference of string methods with signatures and behaviors."), - Source("conditionals", "Conditionals", BASE_URL + "tutorial/controlflow.html#if-statements", "`if`, `elif`, and `else` choose which block runs based on boolean conditions.", BASE_URL + "tutorial/controlflow.html#match-statements", "`match` pattern matching with examples and syntax."), - Source("loops", "Loops", BASE_URL + "tutorial/controlflow.html#for-statements", "`for` loops iterate over items; `while` loops continue while a condition is true.", BASE_URL + "reference/compound_stmts.html#the-for-statement", "Formal for-statement syntax and iteration semantics."), - Source("functions", "Functions", BASE_URL + "tutorial/controlflow.html#defining-functions", "`def` creates reusable behavior with parameters, return values, and optional defaults.", BASE_URL + "reference/compound_stmts.html#function-definitions", "Function definition syntax including parameters, annotations, and decorators."), - Source("lists", "Lists", BASE_URL + "tutorial/datastructures.html#more-on-lists", "Lists are mutable ordered collections with methods such as `append`, `pop`, and `sort`.", BASE_URL + "library/stdtypes.html#sequence-types-list-tuple-range", "Sequence types reference with list methods, operations, and type tables."), - Source("tuples", "Tuples", BASE_URL + "tutorial/datastructures.html#tuples-and-sequences", "Tuples group ordered values and are commonly unpacked into multiple names.", BASE_URL + "library/stdtypes.html#common-sequence-operations", "Operations shared by all sequence types: indexing, slicing, concatenation."), - Source("dictionaries", "Dictionaries", BASE_URL + "tutorial/datastructures.html#dictionaries", "Dictionaries map keys to values and are the standard way to represent lookup tables.", BASE_URL + "library/stdtypes.html#mapping-types-dict", "The dict type with constructor forms, methods, and creation examples."), - Source("sets", "Sets", BASE_URL + "tutorial/datastructures.html#sets", "Sets store unique values and support membership tests and set operations.", BASE_URL + "library/stdtypes.html#set-types-set-frozenset", "set and frozenset methods for membership and set relationships."), - Source("comprehensions", "Comprehensions", BASE_URL + "tutorial/datastructures.html#list-comprehensions", "Comprehensions build new collections by combining an expression with one or more loops.", BASE_URL + "tutorial/datastructures.html#nested-list-comprehensions", "Nested comprehensions that build lists of lists from multiple loops."), - Source("exceptions", "Exceptions", BASE_URL + "tutorial/errors.html#handling-exceptions", "`try` and `except` handle errors without crashing the whole program.", BASE_URL + "library/exceptions.html#concrete-exceptions", "Concrete built-in exceptions like ValueError, KeyError, and TypeError."), - Source("file_io", "File I/O", BASE_URL + "tutorial/inputoutput.html#reading-and-writing-files", "`open` and `with` are the usual tools for reading and writing files safely.", BASE_URL + "library/io.html#high-level-module-interface", "The high-level `open()` interface and its modes."), - Source("classes", "Classes", BASE_URL + "tutorial/classes.html#a-first-look-at-classes", "Classes combine data and behavior into reusable types.", BASE_URL + "reference/datamodel.html#special-method-names", "Special methods like `__init__`, `__str__`, and `__repr__`."), - Source("functional", "Functional Tools", BASE_URL + "howto/functional.html", "Functional style uses functions, iterators, and transformations as building blocks.", BASE_URL + "library/itertools.html#itertool-functions", "itertools building blocks with signatures and usage patterns."), - Source("decorators", "Decorators", BASE_URL + "reference/compound_stmts.html#function-definitions", "Decorators wrap or transform functions and classes with `@decorator` syntax.", BASE_URL + "library/functools.html#functools.wraps", "`functools.wraps` preserves the wrapped function's metadata."), - Source("generators", "Generators", BASE_URL + "tutorial/classes.html#generators", "Generators produce values lazily with `yield` instead of returning a whole collection.", BASE_URL + "reference/expressions.html#generator-expressions", "Generator expression syntax for compact lazy iterators."), - Source("context_managers", "Context Managers", BASE_URL + "reference/compound_stmts.html#the-with-statement", "Context managers run setup and cleanup around a block using `with`.", BASE_URL + "library/contextlib.html#contextlib.contextmanager", "`contextlib.contextmanager` builds a context manager from a generator."), - Source("dataclasses", "Dataclasses", BASE_URL + "library/dataclasses.html", "Dataclasses generate common class methods for data-focused classes.", BASE_URL + "tutorial/classes.html#class-and-instance-variables", "Class vs instance variables — the distinction behind dataclass fields."), - Source("type_hints", "Type Hints", BASE_URL + "library/typing.html", "Type hints annotate expected values and help tools reason about your code.", BASE_URL + "reference/datamodel.html#annotations", "How annotations are stored in `__annotations__`."), - Source("regex", "Regular Expressions", BASE_URL + "library/re.html", "The `re` module searches, matches, and transforms text using regular expressions.", BASE_URL + "howto/regex.html#search-and-replace", "Practical search-and-replace patterns from the regex HOWTO."), - Source("testing", "Testing", BASE_URL + "library/unittest.html", "Tests encode expected behavior so code can be checked repeatedly.", BASE_URL + "library/doctest.html#how-it-works", "How doctest finds and runs examples embedded in docstrings."), - Source("recursion", "Recursion", BASE_URL + "tutorial/controlflow.html#defining-functions", "Recursive functions solve a problem by calling themselves on smaller inputs.", BASE_URL + "library/sys.html#sys.setrecursionlimit", "Adjusting the interpreter's recursion limit with `sys.setrecursionlimit`."), - Source("modules", "Modules", BASE_URL + "tutorial/modules.html#modules", "Modules organize Python code into importable files and packages.", BASE_URL + "library/importlib.html#importlib.reload", "Reloading and dynamically importing modules with importlib."), - Source("collections", "Collections", BASE_URL + "library/collections.html", "`collections` provides specialized containers beyond the built-in list, dict, set, and tuple.", BASE_URL + "library/collections.html#collections.Counter", "`Counter` tallies hashable objects and finds the most common ones."), - Source("itertools", "Itertools", BASE_URL + "library/itertools.html", "`itertools` provides fast iterator building blocks for loops and data pipelines.", BASE_URL + "howto/functional.html#the-itertools-module", "The functional HOWTO's tour of itertools with examples."), - Source("json", "JSON", BASE_URL + "library/json.html", "`json` converts between Python values and JSON text.", BASE_URL + "tutorial/inputoutput.html#saving-structured-data-with-json", "Tutorial on saving and loading structured data as JSON."), - Source("datetime", "Datetime", BASE_URL + "library/datetime.html", "`datetime` represents dates, times, durations, and time zones.", BASE_URL + "library/datetime.html#examples-of-usage-datetime", "Worked `datetime` examples beyond the API reference."), - Source("enums", "Enums", BASE_URL + "library/enum.html", "Enums define named constant values that are easier to read than raw literals.", BASE_URL + "library/enum.html#enum.Flag", "`Flag` enums combine members with bitwise operators."), - Source("pathlib", "Pathlib", BASE_URL + "library/pathlib.html", "`pathlib.Path` represents filesystem paths with object-oriented helpers.", BASE_URL + "library/pathlib.html#pathlib.Path.mkdir", "`Path.mkdir` creates directories with parents/exist_ok options."), - Source("oop_advanced", "Advanced OOP", BASE_URL + "tutorial/classes.html", "Advanced class patterns build on attributes, methods, inheritance, and special methods.", BASE_URL + "reference/datamodel.html#object.__repr__", "`__repr__` and `__str__` for custom object representations."), - Source("async", "Asyncio", BASE_URL + "library/asyncio.html", "`asyncio` runs concurrent I/O-bound work with coroutines and an event loop.", BASE_URL + "library/asyncio-task.html#coroutines", "Coroutines and `async`/`await` with execution examples."), + Source( + "variables", + "Variables", + BASE_URL + "tutorial/introduction.html#using-python-as-a-calculator", + "Assigning names with `=` lets you keep values for later expressions.", + BASE_URL + "reference/simple_stmts.html#assignment-statements", + ( + "Assignment statement syntax and semantics, including " + "multiple and unpacking targets." + ), + ), + Source( + "strings", + "Strings", + BASE_URL + "library/stdtypes.html#text-sequence-type-str", + ( + "Strings are immutable text sequences with indexing, " + "slicing, and many useful methods." + ), + BASE_URL + "library/stdtypes.html#string-methods", + "Full reference of string methods with signatures and behaviors.", + ), + Source( + "conditionals", + "Conditionals", + BASE_URL + "tutorial/controlflow.html#if-statements", + ( + "`if`, `elif`, and `else` choose which block runs based on " + "boolean conditions." + ), + BASE_URL + "tutorial/controlflow.html#match-statements", + "`match` pattern matching with examples and syntax.", + ), + Source( + "loops", + "Loops", + BASE_URL + "tutorial/controlflow.html#for-statements", + ( + "`for` loops iterate over items; `while` loops continue " + "while a condition is true." + ), + BASE_URL + "reference/compound_stmts.html#the-for-statement", + "Formal for-statement syntax and iteration semantics.", + ), + Source( + "functions", + "Functions", + BASE_URL + "tutorial/controlflow.html#defining-functions", + ( + "`def` creates reusable behavior with parameters, return " + "values, and optional defaults." + ), + BASE_URL + "reference/compound_stmts.html#function-definitions", + ( + "Function definition syntax including parameters, " + "annotations, and decorators." + ), + ), + Source( + "lists", + "Lists", + BASE_URL + "tutorial/datastructures.html#more-on-lists", + ( + "Lists are mutable ordered collections with methods such as" + " `append`, `pop`, and `sort`." + ), + BASE_URL + "library/stdtypes.html#sequence-types-list-tuple-range", + ( + "Sequence types reference with list methods, operations, " + "and type tables." + ), + ), + Source( + "tuples", + "Tuples", + BASE_URL + "tutorial/datastructures.html#tuples-and-sequences", + ( + "Tuples group ordered values and are commonly unpacked into" + " multiple names." + ), + BASE_URL + "library/stdtypes.html#common-sequence-operations", + ( + "Operations shared by all sequence types: indexing, " + "slicing, concatenation." + ), + ), + Source( + "dictionaries", + "Dictionaries", + BASE_URL + "tutorial/datastructures.html#dictionaries", + ( + "Dictionaries map keys to values and are the standard way " + "to represent lookup tables." + ), + BASE_URL + "library/stdtypes.html#mapping-types-dict", + "The dict type with constructor forms, methods, and creation examples.", + ), + Source( + "sets", + "Sets", + BASE_URL + "tutorial/datastructures.html#sets", + ( + "Sets store unique values and support membership tests and " + "set operations." + ), + BASE_URL + "library/stdtypes.html#set-types-set-frozenset", + "set and frozenset methods for membership and set relationships.", + ), + Source( + "comprehensions", + "Comprehensions", + BASE_URL + "tutorial/datastructures.html#list-comprehensions", + ( + "Comprehensions build new collections by combining an " + "expression with one or more loops." + ), + BASE_URL + "tutorial/datastructures.html#nested-list-comprehensions", + "Nested comprehensions that build lists of lists from multiple loops.", + ), + Source( + "exceptions", + "Exceptions", + BASE_URL + "tutorial/errors.html#handling-exceptions", + "`try` and `except` handle errors without crashing the whole program.", + BASE_URL + "library/exceptions.html#concrete-exceptions", + ( + "Concrete built-in exceptions like ValueError, KeyError, " + "and TypeError." + ), + ), + Source( + "file_io", + "File I/O", + BASE_URL + "tutorial/inputoutput.html#reading-and-writing-files", + ( + "`open` and `with` are the usual tools for reading and " + "writing files safely." + ), + BASE_URL + "library/io.html#high-level-module-interface", + "The high-level `open()` interface and its modes.", + ), + Source( + "classes", + "Classes", + BASE_URL + "tutorial/classes.html#a-first-look-at-classes", + "Classes combine data and behavior into reusable types.", + BASE_URL + "reference/datamodel.html#special-method-names", + "Special methods like `__init__`, `__str__`, and `__repr__`.", + ), + Source( + "functional", + "Functional Tools", + BASE_URL + "howto/functional.html", + ( + "Functional style uses functions, iterators, and " + "transformations as building blocks." + ), + BASE_URL + "library/itertools.html#itertool-functions", + "itertools building blocks with signatures and usage patterns.", + ), + Source( + "decorators", + "Decorators", + BASE_URL + "reference/compound_stmts.html#function-definitions", + ( + "Decorators wrap or transform functions and classes with " + "`@decorator` syntax." + ), + BASE_URL + "library/functools.html#functools.wraps", + "`functools.wraps` preserves the wrapped function's metadata.", + ), + Source( + "generators", + "Generators", + BASE_URL + "tutorial/classes.html#generators", + ( + "Generators produce values lazily with `yield` instead of " + "returning a whole collection." + ), + BASE_URL + "reference/expressions.html#generator-expressions", + "Generator expression syntax for compact lazy iterators.", + ), + Source( + "context_managers", + "Context Managers", + BASE_URL + "reference/compound_stmts.html#the-with-statement", + "Context managers run setup and cleanup around a block using `with`.", + BASE_URL + "library/contextlib.html#contextlib.contextmanager", + ( + "`contextlib.contextmanager` builds a context manager from " + "a generator." + ), + ), + Source( + "dataclasses", + "Dataclasses", + BASE_URL + "library/dataclasses.html", + "Dataclasses generate common class methods for data-focused classes.", + BASE_URL + "tutorial/classes.html#class-and-instance-variables", + ( + "Class vs instance variables — the distinction behind " + "dataclass fields." + ), + ), + Source( + "type_hints", + "Type Hints", + BASE_URL + "library/typing.html", + ( + "Type hints annotate expected values and help tools reason " + "about your code." + ), + BASE_URL + "reference/datamodel.html#annotations", + "How annotations are stored in `__annotations__`.", + ), + Source( + "regex", + "Regular Expressions", + BASE_URL + "library/re.html", + ( + "The `re` module searches, matches, and transforms text " + "using regular expressions." + ), + BASE_URL + "howto/regex.html#search-and-replace", + "Practical search-and-replace patterns from the regex HOWTO.", + ), + Source( + "testing", + "Testing", + BASE_URL + "library/unittest.html", + "Tests encode expected behavior so code can be checked repeatedly.", + BASE_URL + "library/doctest.html#how-it-works", + "How doctest finds and runs examples embedded in docstrings.", + ), + Source( + "recursion", + "Recursion", + BASE_URL + "tutorial/controlflow.html#defining-functions", + ( + "Recursive functions solve a problem by calling themselves " + "on smaller inputs." + ), + BASE_URL + "library/sys.html#sys.setrecursionlimit", + ( + "Adjusting the interpreter's recursion limit with " + "`sys.setrecursionlimit`." + ), + ), + Source( + "modules", + "Modules", + BASE_URL + "tutorial/modules.html#modules", + "Modules organize Python code into importable files and packages.", + BASE_URL + "library/importlib.html#importlib.reload", + "Reloading and dynamically importing modules with importlib.", + ), + Source( + "collections", + "Collections", + BASE_URL + "library/collections.html", + ( + "`collections` provides specialized containers beyond the " + "built-in list, dict, set, and tuple." + ), + BASE_URL + "library/collections.html#collections.Counter", + "`Counter` tallies hashable objects and finds the most common ones.", + ), + Source( + "itertools", + "Itertools", + BASE_URL + "library/itertools.html", + ( + "`itertools` provides fast iterator building blocks for " + "loops and data pipelines." + ), + BASE_URL + "howto/functional.html#the-itertools-module", + "The functional HOWTO's tour of itertools with examples.", + ), + Source( + "json", + "JSON", + BASE_URL + "library/json.html", + "`json` converts between Python values and JSON text.", + BASE_URL + "tutorial/inputoutput.html#saving-structured-data-with-json", + "Tutorial on saving and loading structured data as JSON.", + ), + Source( + "datetime", + "Datetime", + BASE_URL + "library/datetime.html", + "`datetime` represents dates, times, durations, and time zones.", + BASE_URL + "library/datetime.html#examples-of-usage-datetime", + "Worked `datetime` examples beyond the API reference.", + ), + Source( + "enums", + "Enums", + BASE_URL + "library/enum.html", + ( + "Enums define named constant values that are easier to read" + " than raw literals." + ), + BASE_URL + "library/enum.html#enum.Flag", + "`Flag` enums combine members with bitwise operators.", + ), + Source( + "pathlib", + "Pathlib", + BASE_URL + "library/pathlib.html", + ( + "`pathlib.Path` represents filesystem paths with " + "object-oriented helpers." + ), + BASE_URL + "library/pathlib.html#pathlib.Path.mkdir", + "`Path.mkdir` creates directories with parents/exist_ok options.", + ), + Source( + "oop_advanced", + "Advanced OOP", + BASE_URL + "tutorial/classes.html", + ( + "Advanced class patterns build on attributes, methods, " + "inheritance, and special methods." + ), + BASE_URL + "reference/datamodel.html#object.__repr__", + "`__repr__` and `__str__` for custom object representations.", + ), + Source( + "async", + "Asyncio", + BASE_URL + "library/asyncio.html", + ( + "`asyncio` runs concurrent I/O-bound work with coroutines " + "and an event loop." + ), + BASE_URL + "library/asyncio-task.html#coroutines", + "Coroutines and `async`/`await` with execution examples.", + ), ) @@ -75,7 +382,7 @@ class SectionParser(HTMLParser): Triggers on any element whose id matches the URL fragment. A `
` anchor captures that section; a `
` anchor (Sphinx object/method entry) - captures its enclosing `
` so the signature and description come together. + captures its enclosing `
` with the signature and description together. """ def __init__(self, target_id: str | None) -> None: @@ -91,7 +398,9 @@ def __init__(self, target_id: str | None) -> None: self.in_code = False self.parts: list[str] = [] - def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + def handle_starttag( + self, tag: str, attrs: list[tuple[str, str | None]] + ) -> None: attr = dict(attrs) if tag in {"script", "style", "nav", "footer"}: self.skip_depth += 1 @@ -202,8 +511,8 @@ def render_markdown(source: Source, extracted: str, extra: str = "") -> str: md = ( f"# {source.title}\n\n" f"Source: {source.url}\n\n" - "This local reference is generated from the official Python documentation " - "and trimmed for pythonlings.\n\n" + "This local reference is generated from the official Python " + "documentation and trimmed for pythonlings.\n\n" f"{source.summary}\n\n" "## Extracted reference\n\n" f"{extracted}\n" @@ -248,16 +557,16 @@ def write_outputs(sources: tuple[Source, ...], output: Path) -> None: (output / "NOTICE.md").write_text( textwrap.dedent( """\ - # Bundled Python Documentation Snippets + # Bundled Python Documentation Snippets - These snippets are generated from the official Python documentation at - https://docs.python.org/3/ and trimmed for use inside pythonlings. + These snippets are generated from the official Python documentation at + https://docs.python.org/3/ and trimmed for use inside pythonlings. - Python documentation pages are licensed under the Python Software - Foundation License Version 2. Examples, recipes, and other code in the - documentation are additionally licensed under the Zero Clause BSD License. - See https://docs.python.org/3/copyright.html for details. - """ + Python documentation pages are licensed under the Python Software + Foundation License Version 2. Examples, recipes, and other code in the + documentation are additionally licensed under the Zero Clause BSD License. + See https://docs.python.org/3/copyright.html for details. + """ ), encoding="utf-8", ) diff --git a/tests/integration/test_cli_cold_start.py b/tests/integration/test_cli_cold_start.py index 6833d83..f11ea83 100644 --- a/tests/integration/test_cli_cold_start.py +++ b/tests/integration/test_cli_cold_start.py @@ -1,7 +1,6 @@ # tests/integration/test_cli_cold_start.py import subprocess import sys -import time from pathlib import Path FIXTURES = Path(__file__).parent.parent / "fixtures" / "tiny_curriculum" @@ -12,7 +11,16 @@ def _cold_start_ms(*args: str) -> str: # We don't measure wall-clock for the test (CI flake); we assert that # textual was never imported in the subcommand path. proc = subprocess.run( - [sys.executable, "-X", "importtime", "-m", "pythonlings", "--root", str(FIXTURES), *args], + [ + sys.executable, + "-X", + "importtime", + "-m", + "pythonlings", + "--root", + str(FIXTURES), + *args, + ], capture_output=True, text=True, ) @@ -21,7 +29,9 @@ def _cold_start_ms(*args: str) -> str: def test_hint_does_not_import_textual() -> None: out = _cold_start_ms("hint", "passing") - assert "import 'textual'" not in out, f"textual loaded for `pythonlings hint`:\n{out}" + assert "import 'textual'" not in out, ( + f"textual loaded for `pythonlings hint`:\n{out}" + ) def test_list_does_not_import_textual() -> None: diff --git a/tests/integration/test_cli_doctor.py b/tests/integration/test_cli_doctor.py index 3ea8717..9107d17 100644 --- a/tests/integration/test_cli_doctor.py +++ b/tests/integration/test_cli_doctor.py @@ -1,3 +1,4 @@ +# tests/integration/test_cli_doctor.py from __future__ import annotations import os @@ -31,16 +32,14 @@ def _make_workspace(root: Path) -> Path: "answer = 42\n", encoding="utf-8" ) ( - root - / ".pythonlings" - / "originals" - / "variables" - / "variables1.py" + root / ".pythonlings" / "originals" / "variables" / "variables1.py" ).write_text(exercise, encoding="utf-8") return root -def _run(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: +def _run( + *args: str, cwd: Path | None = None +) -> subprocess.CompletedProcess[str]: return subprocess.run( [sys.executable, "-m", "pythonlings", *args], cwd=cwd, @@ -190,7 +189,9 @@ def test_doctor_is_listed_in_cli_help() -> None: assert "doctor" in result.stdout -def test_doctor_honors_explicit_root_over_current_workspace(tmp_path: Path) -> None: +def test_doctor_honors_explicit_root_over_current_workspace( + tmp_path: Path, +) -> None: current = _make_workspace(tmp_path / "current") explicit = _make_workspace(tmp_path / "explicit") diff --git a/tests/integration/test_cli_dry_run.py b/tests/integration/test_cli_dry_run.py index ff848f3..72293e9 100644 --- a/tests/integration/test_cli_dry_run.py +++ b/tests/integration/test_cli_dry_run.py @@ -1,7 +1,10 @@ +# tests/integration/test_cli_dry_run.py from pythonlings.cli import main def test_dry_run_alias_runs_one_exercise() -> None: - code = main(["--root", "tests/fixtures/passing_curriculum", "dry-run", "passing1"]) + code = main( + ["--root", "tests/fixtures/passing_curriculum", "dry-run", "passing1"] + ) assert code == 0 diff --git a/tests/integration/test_cli_reset.py b/tests/integration/test_cli_reset.py index 922b1d5..e38c55a 100644 --- a/tests/integration/test_cli_reset.py +++ b/tests/integration/test_cli_reset.py @@ -11,7 +11,9 @@ FIXTURES = Path(__file__).parent.parent / "fixtures" / "tiny_curriculum" -def _run(*args: str, input: str | None = None) -> subprocess.CompletedProcess[str]: +def _run( + *args: str, input: str | None = None +) -> subprocess.CompletedProcess[str]: return subprocess.run( [sys.executable, "-m", "pythonlings", *args], capture_output=True, @@ -41,9 +43,13 @@ def test_reset_without_yes_aborts_on_no(tmp_path: Path) -> None: assert target.read_text() == "scrambled" -def test_reset_does_not_create_original_from_current_file(tmp_path: Path) -> None: +def test_reset_does_not_create_original_from_current_file( + tmp_path: Path, +) -> None: work = tmp_path / "work" - shutil.copytree(FIXTURES, work, ignore=shutil.ignore_patterns(".pythonlings")) + shutil.copytree( + FIXTURES, work, ignore=shutil.ignore_patterns(".pythonlings") + ) target = work / "exercises" / "passing.py" target.write_text("# learner edit before reset\n", encoding="utf-8") @@ -57,4 +63,3 @@ def test_reset_does_not_create_original_from_current_file(tmp_path: Path) -> Non def test_reset_unknown_exercise_exits_nonzero() -> None: result = _run("--root", str(FIXTURES), "reset", "nope", "--yes") assert result.returncode != 0 - diff --git a/tests/integration/test_cli_solution.py b/tests/integration/test_cli_solution.py index 953e5bf..6bde9ce 100644 --- a/tests/integration/test_cli_solution.py +++ b/tests/integration/test_cli_solution.py @@ -1,3 +1,4 @@ +# tests/integration/test_cli_solution.py from pathlib import Path from pythonlings.cli import main @@ -22,7 +23,9 @@ def test_solution_command_runs_workspace_solution(tmp_path: Path) -> None: ) (root / "exercises" / "passing1.py").write_text("x = 0\n", encoding="utf-8") (root / "solutions" / "passing1.py").write_text("x = 1\n", encoding="utf-8") - (root / "checks" / "passing1.py").write_text("assert x == 1\n", encoding="utf-8") + (root / "checks" / "passing1.py").write_text( + "assert x == 1\n", encoding="utf-8" + ) code = main(["--root", str(root), "solution", "passing1"]) @@ -46,9 +49,13 @@ def test_debug_writes_workspace_log(tmp_path: Path) -> None: encoding="utf-8", ) (root / "exercises" / "passing1.py").write_text("x = 1\n", encoding="utf-8") - (root / "checks" / "passing1.py").write_text("assert x == 1\n", encoding="utf-8") + (root / "checks" / "passing1.py").write_text( + "assert x == 1\n", encoding="utf-8" + ) code = main(["--debug", "--root", str(root), "run", "passing1"]) assert code == 0 - assert "run" in (root / ".pythonlings_debug.log").read_text(encoding="utf-8") + assert "run" in (root / ".pythonlings_debug.log").read_text( + encoding="utf-8" + ) diff --git a/tests/integration/test_cli_topics.py b/tests/integration/test_cli_topics.py index af23bed..ed9ff54 100644 --- a/tests/integration/test_cli_topics.py +++ b/tests/integration/test_cli_topics.py @@ -11,7 +11,9 @@ def _run(*args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( - [sys.executable, "-m", "pythonlings", *args], capture_output=True, text=True + [sys.executable, "-m", "pythonlings", *args], + capture_output=True, + text=True, ) diff --git a/tests/integration/test_cli_verify.py b/tests/integration/test_cli_verify.py index 599c3cb..0966dd7 100644 --- a/tests/integration/test_cli_verify.py +++ b/tests/integration/test_cli_verify.py @@ -47,8 +47,8 @@ def test_verify_fails_on_first_failure() -> None: def test_verify_against_only_passing_fixture(tmp_path: Path) -> None: info = tmp_path / "info.toml" info.write_text( - 'format_version = 1\n' - '[[exercises]]\n' + "format_version = 1\n" + "[[exercises]]\n" 'name = "ok"\n' 'path = "exercises/ok.py"\n' 'hint = "h"\n', @@ -57,7 +57,9 @@ def test_verify_against_only_passing_fixture(tmp_path: Path) -> None: (tmp_path / "exercises").mkdir() (tmp_path / "exercises" / "ok.py").write_text("x = 1\n", encoding="utf-8") (tmp_path / "checks").mkdir() - (tmp_path / "checks" / "ok.py").write_text("assert x == 1\n", encoding="utf-8") + (tmp_path / "checks" / "ok.py").write_text( + "assert x == 1\n", encoding="utf-8" + ) result = _run("--root", str(tmp_path), "verify") assert result.returncode == 0, result.stderr @@ -68,7 +70,7 @@ def test_verify_ignores_marker(tmp_path: Path) -> None: # should be treated as a verify-pass. info = tmp_path / "info.toml" info.write_text( - 'format_version = 1\n' + "format_version = 1\n" '[[exercises]]\nname = "ok"\npath = "exercises/ok.py"\nhint = "h"\n', encoding="utf-8", ) @@ -77,7 +79,9 @@ def test_verify_ignores_marker(tmp_path: Path) -> None: "# I AM NOT DONE\nx = 1\n", encoding="utf-8" ) (tmp_path / "checks").mkdir() - (tmp_path / "checks" / "ok.py").write_text("assert x == 1\n", encoding="utf-8") + (tmp_path / "checks" / "ok.py").write_text( + "assert x == 1\n", encoding="utf-8" + ) result = _run("--root", str(tmp_path), "verify") assert result.returncode == 0 @@ -89,8 +93,12 @@ def test_verify_reports_manifest_error_with_exit_2(tmp_path: Path) -> None: assert "info.toml" in result.stderr -def test_verify_malformed_toml_exits_2_without_traceback(tmp_path: Path) -> None: - (tmp_path / "info.toml").write_text("format_version = [1\n", encoding="utf-8") +def test_verify_malformed_toml_exits_2_without_traceback( + tmp_path: Path, +) -> None: + (tmp_path / "info.toml").write_text( + "format_version = [1\n", encoding="utf-8" + ) result = _run("--root", str(tmp_path), "verify") assert result.returncode == 2 assert "info.toml" in result.stderr @@ -106,7 +114,9 @@ def test_verify_invalid_utf8_exits_2_without_traceback(tmp_path: Path) -> None: assert "Traceback" not in result.stderr -def test_verify_info_toml_read_error_exits_2_without_traceback(tmp_path: Path) -> None: +def test_verify_info_toml_read_error_exits_2_without_traceback( + tmp_path: Path, +) -> None: (tmp_path / "info.toml").mkdir() result = _run("--root", str(tmp_path), "verify") assert result.returncode == 2 @@ -114,10 +124,12 @@ def test_verify_info_toml_read_error_exits_2_without_traceback(tmp_path: Path) - assert "Traceback" not in result.stderr -def test_verify_traversal_path_exits_2_without_traceback(tmp_path: Path) -> None: +def test_verify_traversal_path_exits_2_without_traceback( + tmp_path: Path, +) -> None: (tmp_path / "info.toml").write_text( - 'format_version = 1\n' - '[[exercises]]\n' + "format_version = 1\n" + "[[exercises]]\n" 'name = "a"\n' 'path = "exercises/../../etc/passwd"\n' 'hint = "h"\n', @@ -129,12 +141,14 @@ def test_verify_traversal_path_exits_2_without_traceback(tmp_path: Path) -> None assert result.stderr.startswith("pythonlings:") -def test_verify_directory_path_exits_2_without_traceback(tmp_path: Path) -> None: +def test_verify_directory_path_exits_2_without_traceback( + tmp_path: Path, +) -> None: (tmp_path / "exercises" / "topic").mkdir(parents=True) (tmp_path / "checks" / "topic").mkdir(parents=True) (tmp_path / "info.toml").write_text( - 'format_version = 1\n' - '[[exercises]]\n' + "format_version = 1\n" + "[[exercises]]\n" 'name = "a"\n' 'path = "exercises/topic"\n', encoding="utf-8", @@ -146,17 +160,19 @@ def test_verify_directory_path_exits_2_without_traceback(tmp_path: Path) -> None assert "Traceback" not in result.stderr -def test_hint_non_string_field_exits_2_without_traceback(tmp_path: Path) -> None: +def test_hint_non_string_field_exits_2_without_traceback( + tmp_path: Path, +) -> None: (tmp_path / "exercises").mkdir() (tmp_path / "exercises" / "a.py").write_text("", encoding="utf-8") (tmp_path / "checks").mkdir() (tmp_path / "checks" / "a.py").write_text("", encoding="utf-8") (tmp_path / "info.toml").write_text( - 'format_version = 1\n' - '[[exercises]]\n' + "format_version = 1\n" + "[[exercises]]\n" 'name = "a"\n' 'path = "exercises/a.py"\n' - 'hint = 1\n', + "hint = 1\n", encoding="utf-8", ) @@ -172,14 +188,16 @@ def test_verify_completes_under_ascii_encoding(tmp_path: Path) -> None: # strict-ASCII console. info = tmp_path / "info.toml" info.write_text( - 'format_version = 1\n' - '[[exercises]]\n' + "format_version = 1\n" + "[[exercises]]\n" 'name = "ok"\n' 'path = "exercises/ok.py"\n', encoding="utf-8", ) (tmp_path / "exercises").mkdir() - (tmp_path / "exercises" / "ok.py").write_text("value = 1\n", encoding="utf-8") + (tmp_path / "exercises" / "ok.py").write_text( + "value = 1\n", encoding="utf-8" + ) (tmp_path / "checks").mkdir() (tmp_path / "checks" / "ok.py").write_text( 'assert value == 1, "value should be 1"\nprint("ok \u2713")\n', @@ -198,20 +216,31 @@ def test_verify_completes_under_ascii_encoding(tmp_path: Path) -> None: def test_verify_keeps_unicode_symbol_under_utf8(tmp_path: Path) -> None: info = tmp_path / "info.toml" info.write_text( - 'format_version = 1\n' - '[[exercises]]\n' + "format_version = 1\n" + "[[exercises]]\n" 'name = "ok"\n' 'path = "exercises/ok.py"\n', encoding="utf-8", ) (tmp_path / "exercises").mkdir() - (tmp_path / "exercises" / "ok.py").write_text("value = 1\n", encoding="utf-8") + (tmp_path / "exercises" / "ok.py").write_text( + "value = 1\n", encoding="utf-8" + ) (tmp_path / "checks").mkdir() - (tmp_path / "checks" / "ok.py").write_text("assert value == 1\n", encoding="utf-8") + (tmp_path / "checks" / "ok.py").write_text( + "assert value == 1\n", encoding="utf-8" + ) env = {**os.environ, "PYTHONIOENCODING": "utf-8"} result = subprocess.run( - [sys.executable, "-m", "pythonlings", "--root", str(tmp_path), "verify"], + [ + sys.executable, + "-m", + "pythonlings", + "--root", + str(tmp_path), + "verify", + ], capture_output=True, text=True, # The child writes UTF-8 because of PYTHONIOENCODING above; decode it diff --git a/tests/integration/test_cli_workspace.py b/tests/integration/test_cli_workspace.py index 86810f3..d188a6d 100644 --- a/tests/integration/test_cli_workspace.py +++ b/tests/integration/test_cli_workspace.py @@ -4,9 +4,8 @@ import pytest -from pythonlings.core import curriculum from pythonlings.cli import main - +from pythonlings.core import curriculum _STALE_CHECK = "# stale check used to identify the updated workspace\n" @@ -43,7 +42,9 @@ def test_init_command_creates_workspace(tmp_path: Path) -> None: ] -def test_init_rejects_non_empty_non_workspace_dir(tmp_path: Path, capsys) -> None: +def test_init_rejects_non_empty_non_workspace_dir( + tmp_path: Path, capsys +) -> None: target = tmp_path / "stuff" target.mkdir() (target / "notes.txt").write_text("keep", encoding="utf-8") @@ -55,7 +56,9 @@ def test_init_rejects_non_empty_non_workspace_dir(tmp_path: Path, capsys) -> Non assert "isn't empty and isn't a pythonlings workspace" in err -def test_init_on_existing_workspace_is_friendly_noop(tmp_path: Path, capsys) -> None: +def test_init_on_existing_workspace_is_friendly_noop( + tmp_path: Path, capsys +) -> None: target = tmp_path / "ws" assert main(["init", "--path", str(target)]) == 0 capsys.readouterr() # discard first output @@ -153,7 +156,7 @@ def test_update_via_path_migrates_legacy_state_dir(tmp_path: Path) -> None: encoding="utf-8", ) - # --path points at the workspace; cwd is elsewhere. The legacy dir must move. + # --path points at the workspace, not cwd; the legacy dir must move. main(["update", "--path", str(target)]) assert not (target / ".pylings").exists() @@ -212,7 +215,9 @@ def test_update_path_takes_precedence_over_root_and_cwd( _assert_not_updated(cwd_check) -def test_update_root_takes_precedence_over_cwd(tmp_path: Path, monkeypatch) -> None: +def test_update_root_takes_precedence_over_cwd( + tmp_path: Path, monkeypatch +) -> None: cwd = tmp_path / "cwd-ws" root = tmp_path / "root-ws" cwd_check = _stale_workspace(cwd) @@ -226,7 +231,9 @@ def test_update_root_takes_precedence_over_cwd(tmp_path: Path, monkeypatch) -> N _assert_not_updated(cwd_check) -def test_bare_update_prefers_current_workspace(tmp_path: Path, monkeypatch) -> None: +def test_bare_update_prefers_current_workspace( + tmp_path: Path, monkeypatch +) -> None: home = tmp_path / "home-ws" monkeypatch.setenv("PYTHONLINGS_HOME", str(home)) home_check = _stale_workspace(home) diff --git a/tests/integration/test_first_run.py b/tests/integration/test_first_run.py index 0e40ee2..cef6c70 100644 --- a/tests/integration/test_first_run.py +++ b/tests/integration/test_first_run.py @@ -1,12 +1,13 @@ +# tests/integration/test_first_run.py from __future__ import annotations -from pathlib import Path - import pythonlings.app as app_module from pythonlings.cli import main -def test_bare_run_creates_home_workspace_and_launches(tmp_path, monkeypatch, capsys): +def test_bare_run_creates_home_workspace_and_launches( + tmp_path, monkeypatch, capsys +): home = tmp_path / "home" monkeypatch.setenv("PYTHONLINGS_HOME", str(home)) monkeypatch.chdir(tmp_path) # cwd is not a workspace @@ -27,14 +28,18 @@ def fake_run_tui(root, start_topic, force_picker=False): assert "Created your workspace at" in capsys.readouterr().out -def test_bare_run_resumes_existing_home_without_notice(tmp_path, monkeypatch, capsys): +def test_bare_run_resumes_existing_home_without_notice( + tmp_path, monkeypatch, capsys +): home = tmp_path / "home" monkeypatch.setenv("PYTHONLINGS_HOME", str(home)) main(["init", "--path", str(home)]) capsys.readouterr() monkeypatch.chdir(tmp_path) - monkeypatch.setattr(app_module, "run_tui", lambda root, t, force_picker=False: 0) + monkeypatch.setattr( + app_module, "run_tui", lambda root, t, force_picker=False: 0 + ) code = main([]) diff --git a/tests/integration/test_solution_verify.py b/tests/integration/test_solution_verify.py index 62668a2..597f000 100644 --- a/tests/integration/test_solution_verify.py +++ b/tests/integration/test_solution_verify.py @@ -1,3 +1,4 @@ +# tests/integration/test_solution_verify.py from pathlib import Path from pythonlings.core.manifest import load @@ -13,6 +14,8 @@ def test_every_reference_solution_passes() -> None: for exercise in manifest.exercises: result = run_verify(solution_exercise(root, exercise)) if not result.passed: - failures.append(f"{exercise.name}: {result.stderr or result.stdout}") + failures.append( + f"{exercise.name}: {result.stderr or result.stdout}" + ) assert failures == [] diff --git a/tests/test_functional_assertion_messages.py b/tests/test_functional_assertion_messages.py index 70ed7d1..a185dd5 100644 --- a/tests/test_functional_assertion_messages.py +++ b/tests/test_functional_assertion_messages.py @@ -2,7 +2,6 @@ import ast from pathlib import Path - CHECKS_DIR = Path(__file__).resolve().parent.parent / "checks" / "functional" BATCH = ("functional7.py", "functional8.py", "functional9.py") diff --git a/tests/test_json_checks_messages.py b/tests/test_json_checks_messages.py index 6d16314..6c07abe 100644 --- a/tests/test_json_checks_messages.py +++ b/tests/test_json_checks_messages.py @@ -40,7 +40,7 @@ def test_asserts_have_messages() -> None: "data = {}\nname = 'Ada'\n", "{'name': 'Ada', 'language': 'Python'}", ), - ("json2", "text = '{}'\n", "'{\"a\": 1, \"b\": 2}'"), + ("json2", "text = '{}'\n", '\'{"a": 1, "b": 2}\''), ], ) def test_failure_reports_expected_json_value( diff --git a/tests/tui/test_app_pilot.py b/tests/tui/test_app_pilot.py index 67e90da..e740c16 100644 --- a/tests/tui/test_app_pilot.py +++ b/tests/tui/test_app_pilot.py @@ -8,7 +8,8 @@ from textual.worker import WorkerCancelled from pythonlings.app import PythonlingsApp -from pythonlings.core.state import State, save as save_state +from pythonlings.core.state import State +from pythonlings.core.state import save as save_state from pythonlings.screens.docs import DocsScreen from pythonlings.screens.topic_picker import TopicPickerScreen from pythonlings.screens.track import TrackScreen @@ -36,7 +37,9 @@ async def _settle(pilot) -> None: @pytest.mark.asyncio -async def test_default_launch_opens_first_pending_exercise(tmp_path: Path) -> None: +async def test_default_launch_opens_first_pending_exercise( + tmp_path: Path, +) -> None: app = PythonlingsApp(root=_work_copy(tmp_path)) async with app.run_test() as pilot: await _settle(pilot) @@ -135,13 +138,14 @@ async def test_picker_shows_first_run_start_banner(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_picker_rows_show_status_labels(tmp_path: Path) -> None: work = _work_copy(tmp_path) - save_state(work, State(completed={"a1"}, seen_intro=True, last_topic="alpha")) + save_state( + work, State(completed={"a1"}, seen_intro=True, last_topic="alpha") + ) app = PythonlingsApp(root=work, force_picker=True) async with app.run_test() as pilot: await _settle(pilot) rendered = " ".join( - str(row.content) - for row in app.screen.query(".topic-row").results() + str(row.content) for row in app.screen.query(".topic-row").results() ) assert "Continue" in rendered assert "Start" in rendered @@ -157,7 +161,9 @@ async def test_start_topic_opens_track(tmp_path: Path) -> None: @pytest.mark.asyncio -async def test_default_launch_resumes_last_incomplete_exercise(tmp_path: Path) -> None: +async def test_default_launch_resumes_last_incomplete_exercise( + tmp_path: Path, +) -> None: work = _work_copy(tmp_path) save_state( work, @@ -172,7 +178,9 @@ async def test_default_launch_resumes_last_incomplete_exercise(tmp_path: Path) - @pytest.mark.asyncio -async def test_default_launch_falls_back_from_invalid_resume_state(tmp_path: Path) -> None: +async def test_default_launch_falls_back_from_invalid_resume_state( + tmp_path: Path, +) -> None: work = _work_copy(tmp_path) save_state( work, @@ -241,9 +249,7 @@ async def test_narrow_layout_keeps_navigation_discoverable_and_usable( await pilot.pause() assert isinstance(app.screen, TopicPickerScreen) picker_footer = app.screen.query_one(Footer) - picker_keys = { - key.key: key for key in picker_footer.query("FooterKey") - } + picker_keys = {key.key: key for key in picker_footer.query("FooterKey")} escape_key = picker_keys["escape"] assert escape_key.region.x >= picker_footer.region.x assert escape_key.region.right <= picker_footer.region.right @@ -254,7 +260,9 @@ async def test_narrow_layout_keeps_navigation_discoverable_and_usable( @pytest.mark.asyncio -async def test_normal_width_footer_keeps_all_track_labels(tmp_path: Path) -> None: +async def test_normal_width_footer_keeps_all_track_labels( + tmp_path: Path, +) -> None: app = PythonlingsApp(root=_work_copy(tmp_path), start_topic="alpha") async with app.run_test(size=(80, 24)) as pilot: await _settle(pilot) @@ -337,14 +345,18 @@ async def test_f5_opens_docs_popup_for_current_exercise(tmp_path: Path) -> None: assert "Local reference" in rendered assert "# Variables" not in rendered assert "Assigning names" in rendered - assert "https://docs.python.org/3/tutorial/introduction.html" in rendered + assert ( + "https://docs.python.org/3/tutorial/introduction.html" in rendered + ) footer = app.screen.query_one("#docs-footer", Static).content assert "O Open official docs" in str(footer) assert "Esc Close" in str(footer) @pytest.mark.asyncio -async def test_escape_closes_docs_popup_without_quitting(tmp_path: Path) -> None: +async def test_escape_closes_docs_popup_without_quitting( + tmp_path: Path, +) -> None: app = PythonlingsApp(root=_work_copy(tmp_path), start_topic="alpha") async with app.run_test() as pilot: await _settle(pilot) @@ -371,7 +383,9 @@ async def test_docs_popup_can_open_browser( assert isinstance(app.screen, DocsScreen) await pilot.press("o") await pilot.pause() - assert opened == ["https://docs.python.org/3/tutorial/introduction.html"] + assert opened == [ + "https://docs.python.org/3/tutorial/introduction.html" + ] @pytest.mark.asyncio @@ -562,7 +576,9 @@ async def test_solving_a_topic_marks_progress(tmp_path: Path) -> None: @pytest.mark.asyncio -async def test_picker_refreshes_progress_after_returning(tmp_path: Path) -> None: +async def test_picker_refreshes_progress_after_returning( + tmp_path: Path, +) -> None: work = _work_copy(tmp_path) app = PythonlingsApp(root=work, start_topic="beta") async with app.run_test() as pilot: @@ -576,8 +592,7 @@ async def test_picker_refreshes_progress_after_returning(tmp_path: Path) -> None await _settle(pilot) assert isinstance(app.screen, TopicPickerScreen) rendered = " ".join( - str(row.content) - for row in app.screen.query(".topic-row").results() + str(row.content) for row in app.screen.query(".topic-row").results() ) # beta's one exercise is now done -> "1/1" must appear. assert "1/1" in rendered diff --git a/tests/tui/test_editor_pane.py b/tests/tui/test_editor_pane.py index 9318472..c196cc0 100644 --- a/tests/tui/test_editor_pane.py +++ b/tests/tui/test_editor_pane.py @@ -44,7 +44,7 @@ async def test_editor_recovers_after_unreadable_exercise( exercise = Exercise("ex", path, tmp_path / "check.py", "t", "") app = _Harness() - async with app.run_test() as pilot: + async with app.run_test(): pane = app.query_one(EditorPane) pane.load_exercise(exercise) assert pane.query_one("#code", TextArea).read_only diff --git a/tests/tui/test_output_panel.py b/tests/tui/test_output_panel.py index 31f6ed1..63c1de2 100644 --- a/tests/tui/test_output_panel.py +++ b/tests/tui/test_output_panel.py @@ -1,3 +1,4 @@ +# tests/tui/test_output_panel.py from pathlib import Path import pytest @@ -57,7 +58,9 @@ async def test_render_running_state(tmp_path: Path) -> None: _exercise(tmp_path, "# Goal: set name\nname = broken\n"), 0, 2 ) await pilot.pause() - assert "Running checks" in str(panel.query_one("#status", Static).content) + assert "Running checks" in str( + panel.query_one("#status", Static).content + ) @pytest.mark.asyncio @@ -100,7 +103,9 @@ async def test_result_shows_docs_link(tmp_path: Path) -> None: await pilot.pause() rendered = panel.renderable_text() assert "Docs" in rendered - assert "https://docs.python.org/3/tutorial/introduction.html" in rendered + assert ( + "https://docs.python.org/3/tutorial/introduction.html" in rendered + ) @pytest.mark.asyncio @@ -125,16 +130,22 @@ async def test_full_hint_toggles_on_f1(tmp_path: Path) -> None: panel = app.query_one(OutputPanel) panel.toggle_hint("Full hint text.") await pilot.pause() - assert "Full hint text." in str(panel.query_one("#hint", Static).content) + assert "Full hint text." in str( + panel.query_one("#hint", Static).content + ) @pytest.mark.asyncio -async def test_show_topic_complete_uses_topic_header_not_global(tmp_path: Path) -> None: +async def test_show_topic_complete_uses_topic_header_not_global( + tmp_path: Path, +) -> None: app = _Harness() async with app.run_test() as pilot: await pilot.pause() panel = app.query_one(OutputPanel) - panel.show_topic_complete("Topic 'variables' complete — press F4 for topics.") + panel.show_topic_complete( + "Topic 'variables' complete — press F4 for topics." + ) await pilot.pause() header = str(panel.query_one("#output-header", Static).content) assert "Topic complete" in header diff --git a/tests/tui/test_welcome_pilot.py b/tests/tui/test_welcome_pilot.py index ad30032..7d092d3 100644 --- a/tests/tui/test_welcome_pilot.py +++ b/tests/tui/test_welcome_pilot.py @@ -1,3 +1,4 @@ +# tests/tui/test_welcome_pilot.py from __future__ import annotations import shutil @@ -7,7 +8,9 @@ from textual.worker import WorkerCancelled from pythonlings.app import PythonlingsApp -from pythonlings.core.state import State, load as load_state, save as save_state +from pythonlings.core.state import State +from pythonlings.core.state import load as load_state +from pythonlings.core.state import save as save_state from pythonlings.screens.track import TrackScreen from pythonlings.screens.welcome import WelcomeScreen diff --git a/tests/unit/test_check_namespaces.py b/tests/unit/test_check_namespaces.py index 47222a7..14cb91a 100644 --- a/tests/unit/test_check_namespaces.py +++ b/tests/unit/test_check_namespaces.py @@ -12,7 +12,9 @@ def test_area_check_preserves_learner_globals() -> None: namespace["area"] = 0 check = ( Path(__file__).resolve().parents[2] - / "checks" / "oop_advanced" / "oop_advanced3.py" + / "checks" + / "oop_advanced" + / "oop_advanced3.py" ) exec( @@ -51,7 +53,9 @@ def wrong_once(*args): namespace[function] = wrong_once check = ( Path(__file__).resolve().parents[2] - / "checks" / "functional" / f"{name}.py" + / "checks" + / "functional" + / f"{name}.py" ) with pytest.raises(AssertionError, match="should be"): exec( diff --git a/tests/unit/test_curriculum.py b/tests/unit/test_curriculum.py index 8773692..00ae4a8 100644 --- a/tests/unit/test_curriculum.py +++ b/tests/unit/test_curriculum.py @@ -65,7 +65,9 @@ def test_force_init_rejects_resolved_curriculum_source( assert not (source / ".pythonlings").exists() -def test_force_init_preserves_existing_gitignore_entries(tmp_path: Path) -> None: +def test_force_init_preserves_existing_gitignore_entries( + tmp_path: Path, +) -> None: target = tmp_path / "workspace" target.mkdir() gitignore = target / ".gitignore" @@ -93,10 +95,15 @@ def test_force_init_populates_empty_gitignore(tmp_path: Path) -> None: curriculum.init_workspace(target, force=True) - assert gitignore.read_text(encoding="utf-8").splitlines() == curriculum.GITIGNORE_LINES + assert ( + gitignore.read_text(encoding="utf-8").splitlines() + == curriculum.GITIGNORE_LINES + ) -def test_force_init_preserves_gitignore_crlf_line_endings(tmp_path: Path) -> None: +def test_force_init_preserves_gitignore_crlf_line_endings( + tmp_path: Path, +) -> None: target = tmp_path / "workspace" target.mkdir() gitignore = target / ".gitignore" @@ -105,9 +112,14 @@ def test_force_init_preserves_gitignore_crlf_line_endings(tmp_path: Path) -> Non curriculum.init_workspace(target, force=True) - expected = original + b"\r\n" + b"\r\n".join( - line.encode("utf-8") for line in curriculum.GITIGNORE_LINES - ) + b"\r\n" + expected = ( + original + + b"\r\n" + + b"\r\n".join( + line.encode("utf-8") for line in curriculum.GITIGNORE_LINES + ) + + b"\r\n" + ) assert gitignore.read_bytes() == expected @@ -119,12 +131,19 @@ def test_update_workspace_preserves_user_exercise_edit(tmp_path: Path) -> None: curriculum.update_workspace(target) assert exercise.read_text(encoding="utf-8") == "# user edit\n" - original = target / ".pythonlings" / "originals" / exercise.relative_to(target / "exercises") + original = ( + target + / ".pythonlings" + / "originals" + / exercise.relative_to(target / "exercises") + ) assert original.exists() assert (target / "solutions" / "_answers.py").exists() -def test_update_workspace_preserves_existing_gitignore_entries(tmp_path: Path) -> None: +def test_update_workspace_preserves_existing_gitignore_entries( + tmp_path: Path, +) -> None: target = curriculum.init_workspace(tmp_path / "workspace") gitignore = target / ".gitignore" original = "# Team rules\n.coverage\n" diff --git a/tests/unit/test_docs.py b/tests/unit/test_docs.py index 0ddc000..ab545e1 100644 --- a/tests/unit/test_docs.py +++ b/tests/unit/test_docs.py @@ -1,3 +1,4 @@ +# tests/unit/test_docs.py from pathlib import Path from pythonlings.core.docs import load_snippet @@ -37,7 +38,9 @@ def test_real_curriculum_topics_have_bundled_references() -> None: assert missing == [] -def test_docs_screen_markdown_includes_configured_docs_for_all_exercises() -> None: +def test_docs_screen_markdown_includes_configured_docs_for_all_exercises() -> ( + None +): repo = Path(__file__).parents[2] manifest = load(repo) diff --git a/tests/unit/test_doctor.py b/tests/unit/test_doctor.py index 204a49d..3693d2f 100644 --- a/tests/unit/test_doctor.py +++ b/tests/unit/test_doctor.py @@ -1,3 +1,4 @@ +# tests/unit/test_doctor.py from __future__ import annotations from pathlib import Path @@ -30,11 +31,7 @@ def _make_workspace(root: Path) -> Path: "answer = 42\n", encoding="utf-8" ) ( - root - / ".pythonlings" - / "originals" - / "variables" - / "variables1.py" + root / ".pythonlings" / "originals" / "variables" / "variables1.py" ).write_text(exercise, encoding="utf-8") return root @@ -93,11 +90,7 @@ def test_missing_solution_is_a_warning(tmp_path: Path) -> None: def test_missing_snapshot_is_an_actionable_warning(tmp_path: Path) -> None: root = _make_workspace(tmp_path) ( - root - / ".pythonlings" - / "originals" - / "variables" - / "variables1.py" + root / ".pythonlings" / "originals" / "variables" / "variables1.py" ).unlink() report = run_diagnostics(root, package_version="0.4.1") diff --git a/tests/unit/test_exercise.py b/tests/unit/test_exercise.py index 346745b..f7a750d 100644 --- a/tests/unit/test_exercise.py +++ b/tests/unit/test_exercise.py @@ -10,7 +10,11 @@ def _ex(path: Path) -> Exercise: return Exercise( - name="ex", path=path, check_path=path.parent / "check.py", topic="t", hint="" + name="ex", + path=path, + check_path=path.parent / "check.py", + topic="t", + hint="", ) diff --git a/tests/unit/test_manifest.py b/tests/unit/test_manifest.py index e27157d..e308e24 100644 --- a/tests/unit/test_manifest.py +++ b/tests/unit/test_manifest.py @@ -21,7 +21,9 @@ def _write_curriculum( encoding="utf-8", ) (root / "exercises").mkdir(exist_ok=True) - (root / "exercises" / f"{name}.py").write_text(exercise_src, encoding="utf-8") + (root / "exercises" / f"{name}.py").write_text( + exercise_src, encoding="utf-8" + ) (root / "checks").mkdir(exist_ok=True) (root / "checks" / f"{name}.py").write_text(check_src, encoding="utf-8") @@ -75,13 +77,17 @@ def test_load_rejects_missing_info_toml(tmp_path: Path) -> None: def test_load_rejects_wrong_format_version(tmp_path: Path) -> None: - (tmp_path / "info.toml").write_text("format_version = 2\n", encoding="utf-8") + (tmp_path / "info.toml").write_text( + "format_version = 2\n", encoding="utf-8" + ) with pytest.raises(ManifestError, match="format_version"): load(tmp_path) def test_load_rejects_empty_exercises_list(tmp_path: Path) -> None: - (tmp_path / "info.toml").write_text("format_version = 1\n", encoding="utf-8") + (tmp_path / "info.toml").write_text( + "format_version = 1\n", encoding="utf-8" + ) with pytest.raises(ManifestError, match="non-empty"): load(tmp_path) @@ -193,7 +199,9 @@ def test_real_curriculum_has_roadmap_topic_counts() -> None: def test_real_curriculum_exercises_have_official_docs_links() -> None: repo = Path(__file__).parents[2] manifest = load(repo) - missing = [exercise.name for exercise in manifest.exercises if not exercise.docs] + missing = [ + exercise.name for exercise in manifest.exercises if not exercise.docs + ] assert missing == [] assert all( exercise.docs.startswith("https://docs.python.org/3/") @@ -214,7 +222,9 @@ def test_real_curriculum_check_files_parse() -> None: def test_load_rejects_invalid_toml_syntax(tmp_path: Path) -> None: - (tmp_path / "info.toml").write_text("format_version = [1\n", encoding="utf-8") + (tmp_path / "info.toml").write_text( + "format_version = [1\n", encoding="utf-8" + ) with pytest.raises(ManifestError, match=r"info\.toml"): load(tmp_path) @@ -258,10 +268,7 @@ def test_load_rejects_wrong_type_name_field(tmp_path: Path) -> None: def test_load_rejects_missing_path_field(tmp_path: Path) -> None: (tmp_path / "info.toml").write_text( - "format_version = 1\n" - "[[exercises]]\n" - 'name = "a"\n' - 'hint = "h"\n', + 'format_version = 1\n[[exercises]]\nname = "a"\nhint = "h"\n', encoding="utf-8", ) with pytest.raises(ManifestError, match="'path'"): @@ -306,7 +313,9 @@ def test_load_rejects_symlink_escape(tmp_path: Path) -> None: (outside / "secret.py").write_text("SECRET = 1\n", encoding="utf-8") (tmp_path / "exercises").mkdir() - (tmp_path / "exercises" / "link").symlink_to(outside, target_is_directory=True) + (tmp_path / "exercises" / "link").symlink_to( + outside, target_is_directory=True + ) (tmp_path / "checks").mkdir() (tmp_path / "info.toml").write_text( @@ -329,7 +338,9 @@ def test_load_rejects_check_symlink_escape(tmp_path: Path) -> None: (tmp_path / "exercises" / "topic").mkdir(parents=True) (tmp_path / "exercises" / "topic" / "a.py").write_text("", encoding="utf-8") (tmp_path / "checks").mkdir() - (tmp_path / "checks" / "topic").symlink_to(outside, target_is_directory=True) + (tmp_path / "checks" / "topic").symlink_to( + outside, target_is_directory=True + ) (tmp_path / "info.toml").write_text( "format_version = 1\n" "[[exercises]]\n" @@ -339,11 +350,15 @@ def test_load_rejects_check_symlink_escape(tmp_path: Path) -> None: encoding="utf-8", ) - with pytest.raises(ManifestError, match=r"check path.*escapes the workspace"): + with pytest.raises( + ManifestError, match=r"check path.*escapes the workspace" + ): load(tmp_path) -def test_load_rejects_top_level_exercises_symlink_escape(tmp_path: Path) -> None: +def test_load_rejects_top_level_exercises_symlink_escape( + tmp_path: Path, +) -> None: workspace = tmp_path / "workspace" outside = tmp_path / "outside_exercises" workspace.mkdir() @@ -435,7 +450,9 @@ def fail_exercise_resolution(path: Path, strict: bool = False) -> Path: @pytest.mark.parametrize("field", ["hint", "docs"]) -def test_load_rejects_non_string_exercise_text(tmp_path: Path, field: str) -> None: +def test_load_rejects_non_string_exercise_text( + tmp_path: Path, field: str +) -> None: _write_curriculum(tmp_path, "a") (tmp_path / "info.toml").write_text( "format_version = 1\n" @@ -451,7 +468,9 @@ def test_load_rejects_non_string_exercise_text(tmp_path: Path, field: str) -> No @pytest.mark.parametrize("field", ["welcome_message", "final_message"]) -def test_load_rejects_non_string_manifest_text(tmp_path: Path, field: str) -> None: +def test_load_rejects_non_string_manifest_text( + tmp_path: Path, field: str +) -> None: _write_curriculum(tmp_path, "a") info_path = tmp_path / "info.toml" info_path.write_text( diff --git a/tests/unit/test_reset.py b/tests/unit/test_reset.py index 7d4f39d..822e98a 100644 --- a/tests/unit/test_reset.py +++ b/tests/unit/test_reset.py @@ -85,16 +85,25 @@ def test_snapshot_keys_on_exercise_name_not_filename(tmp_path: Path) -> None: snapshot(tmp_path, b) originals = tmp_path / ".pythonlings" / "originals" - assert (originals / "variables_utils.py").read_text() == "variables-version\n" - assert (originals / "functions_utils.py").read_text() == "functions-version\n" + assert ( + originals / "variables_utils.py" + ).read_text() == "variables-version\n" + assert ( + originals / "functions_utils.py" + ).read_text() == "functions-version\n" -def test_restore_uses_pristine_originals_not_current_file(tmp_path: Path) -> None: +def test_restore_uses_pristine_originals_not_current_file( + tmp_path: Path, +) -> None: root = init_workspace(tmp_path / "workspace") manifest = load(root) exercise = manifest.exercises[0] - original = root / ".pythonlings" / "originals" / exercise.rel_path.relative_to( - "exercises" + original = ( + root + / ".pythonlings" + / "originals" + / exercise.rel_path.relative_to("exercises") ) pristine = original.read_text(encoding="utf-8") exercise.path.write_text("# corrupted user edit\n", encoding="utf-8") diff --git a/tests/unit/test_state.py b/tests/unit/test_state.py index b490e25..412790b 100644 --- a/tests/unit/test_state.py +++ b/tests/unit/test_state.py @@ -32,7 +32,9 @@ def test_save_then_load_ux_fields(tmp_path: Path) -> None: assert loaded.last_exercise == "a2" -def test_missing_ux_fields_default_for_existing_v2_state(tmp_path: Path) -> None: +def test_missing_ux_fields_default_for_existing_v2_state( + tmp_path: Path, +) -> None: import json pdir = tmp_path / ".pythonlings" @@ -50,6 +52,7 @@ def test_missing_ux_fields_default_for_existing_v2_state(tmp_path: Path) -> None def test_state_file_is_format_version_2(tmp_path: Path) -> None: import json + save(tmp_path, State(completed={"a"})) data = json.loads((tmp_path / ".pythonlings" / "state.json").read_text()) assert data["format_version"] == 2 @@ -58,6 +61,7 @@ def test_state_file_is_format_version_2(tmp_path: Path) -> None: def test_old_v1_state_is_discarded(tmp_path: Path) -> None: import json + pdir = tmp_path / ".pythonlings" pdir.mkdir() (pdir / "state.json").write_text( diff --git a/tests/unit/test_type_hints1_check.py b/tests/unit/test_type_hints1_check.py index dd2d2c2..b30215a 100644 --- a/tests/unit/test_type_hints1_check.py +++ b/tests/unit/test_type_hints1_check.py @@ -57,7 +57,9 @@ def test_none_annotation_hook_fails_with_clear_message(tmp_path: Path) -> None: def test_callable_annotation_hook_passes(tmp_path: Path) -> None: - exercise_src = "def __annotate__(format_value):\n return {'count': int}\n" + exercise_src = ( + "def __annotate__(format_value):\n return {'count': int}\n" + ) result = _run_case(tmp_path, exercise_src) assert result.passed is True assert "type_hints1 ✓" in result.stdout diff --git a/tests/unit/test_workspace.py b/tests/unit/test_workspace.py index bb9f8dc..ca13b2a 100644 --- a/tests/unit/test_workspace.py +++ b/tests/unit/test_workspace.py @@ -1,3 +1,4 @@ +# tests/unit/test_workspace.py from __future__ import annotations from pathlib import Path @@ -35,7 +36,9 @@ def _make_ws(path: Path) -> Path: def test_resolve_prefers_explicit_root(tmp_path, monkeypatch): monkeypatch.setenv("PYTHONLINGS_HOME", str(tmp_path / "home")) explicit = tmp_path / "given" - out = resolve_workspace_root(tmp_path / "cwd", explicit, create_if_missing=True) + out = resolve_workspace_root( + tmp_path / "cwd", explicit, create_if_missing=True + ) assert out == ResolvedWorkspace(explicit.resolve(), created=False) @@ -65,6 +68,8 @@ def test_resolve_creates_home_when_missing(tmp_path, monkeypatch): def test_resolve_does_not_create_when_flag_off(tmp_path, monkeypatch): home = tmp_path / "home" monkeypatch.setenv("PYTHONLINGS_HOME", str(home)) - out = resolve_workspace_root(tmp_path / "cwd", None, create_if_missing=False) + out = resolve_workspace_root( + tmp_path / "cwd", None, create_if_missing=False + ) assert out == ResolvedWorkspace(home.resolve(), created=False) assert not home.exists()