Compare commits

...

4 Commits

Author SHA1 Message Date
e3214c813c Clear the seven over-cap code_tutor test modules
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
Partitioned at the section banners each file already used, into ten new
modules named for what they cover. python_pkg/code_tutor is now entirely
under the cap, from thirteen violations.

The splitter copies the whole original header into each new file and
lets ruff's F401 pass prune it - 59 imports removed correctly, versus a
hand-written import block failing on every earlier test split today.
That does not cover module-level helpers: _make_verifier sat between two
banners and was left behind by its callers, so it moved to conftest.py,
taking test_verifier.py's shadowing copy of _make_live_mock with it.

No patch string changed. Pass count is 217 before and after.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:06:38 +02:00
eb322dcf80 Split the Claude backend out of code_tutor/_llm
_llm.py 295 -> 217, clearing the last code_tutor source violation; only
its seven test modules remain over the cap.

The seam falls between the two backends because each pins a different
plain import: test_llm.py patches requests.post on _llm for
OllamaBackend and anthropic.Anthropic for ClaudeBackend. _llm keeps its
own anthropic import - complete_with_fallback still catches APIError -
so the four anthropic patch strings were split per test rather than
moved wholesale.

Pass count is 217 before and after.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:00:53 +02:00
1d1938ce23 Split code_tutor cli and verifier, deleting two lint suppressions
cli.py 345 -> 222 and _verifier.py 347 -> 228, via _cli_checks.py and
_verifier_support.py.

The cli seam cut straight through code covered by its per-file-ignores.
Rather than copy S607 and PERF203 onto a second entry, both are fixed:
systemctl is resolved with shutil.which, and the readiness poll no
longer carries a try/except in its body now that the probe is its own
function. Both ignores are deleted from meta/pyproject.toml and ruff
passes without them - the repo has two fewer suppressions than before.

The which() fix adds a systemctl-is-None branch, so the pass count goes
216 -> 217: one new test for it, no existing test touched. Coverage is
back at 100% by covering the branch, not excluding it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 17:57:38 +02:00
c113a3a192 Split the code_tutor import graph and scan tables out of _analyzer
_analyzer.py 388 -> 226. The file walk, dotted-name map, import
resolution and fingerprint go to _deps.py; the skip frozensets and the
function regex to _scan_tables.py, which covered the last nine lines
after the first cut landed at 259.

_is_binary is the only name any test patches on _analyzer and it stays
put, so no patch string needed editing. Only test_analyzer.py's import
block had to be split.

Pass count is 216 before and after.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 17:48:32 +02:00
37 changed files with 2698 additions and 2076 deletions

View File

@ -0,0 +1,19 @@
{
"title": "Split code_tutor/_analyzer.py under the 250-line cap",
"objective": "Bring python_pkg/code_tutor/_analyzer.py (388 lines) under the repo-wide 250-line cap by moving the file-walking and import-graph half into _deps.py and the static scan tables into _scan_tables.py.",
"acceptance_criteria": [
"_analyzer.py, _deps.py and _scan_tables.py are each at most 250 lines.",
"The code_tutor suite still reports exactly 216 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
"The package keeps 100% branch coverage of the code_tutor source modules.",
"_is_binary, the only name any test patches on _analyzer, stays defined there so that patch string needs no edit.",
"Every importer of the moved functions -- cli.py, _plan_builder.py and test_analyzer.py -- names _deps directly rather than reaching them through an _analyzer re-export.",
"No assertion is changed and no test is deleted, skipped or weakened.",
"No suppression is added and no coverage exclusion is introduced."
],
"out_of_scope": [
"Changing what any test asserts, or which paths the analyzer skips.",
"Splitting cli.py, _verifier.py, _llm.py or the code_tutor test modules, which are separate commits.",
"Adding a re-export shim in _analyzer."
],
"verifier": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (expects exactly 216 passed), plus an import-time assertion that every patched name resolves, plus pre-commit run --files on the touched files."
}

View File

@ -0,0 +1,18 @@
{
"title": "Split code_tutor cli.py and _verifier.py under the cap, removing two lint suppressions",
"objective": "Bring python_pkg/code_tutor/cli.py (345 lines) and _verifier.py (347) under the repo-wide 250-line cap. cli.py's split separated code covered by its per-file-ignores, so rather than copying S607 and PERF203 onto a second file the underlying lint is fixed and both entries are deleted.",
"acceptance_criteria": [
"cli.py, _cli_checks.py, _verifier.py and _verifier_support.py are each at most 250 lines.",
"The S607 and PERF203 entries are removed from meta/pyproject.toml's per-file-ignores for code_tutor/cli.py, and ruff passes on the result. The repo's total suppression count goes down by two; it must not go up.",
"The code_tutor suite reports 217 passing tests: the 216 baseline plus exactly one new test covering the shutil.which(\"systemctl\") is None branch that the S607 fix introduced.",
"The package keeps 100% branch coverage of the code_tutor source modules, with the new branch covered by a real test rather than an exclusion.",
"Every patch string is repointed per test by which function is under test: the _ensure_ollama_running and _ensure_fresh_plan tests move to _cli_checks, the analyze/study/status/drill command tests keep cli.",
"No existing assertion is changed and no test is deleted, skipped or weakened."
],
"out_of_scope": [
"Changing the observable behaviour of the Ollama startup path: it must still probe, start via systemctl, poll to the same timeout and print the same messages.",
"Removing the B008 ignore, which is the standard Typer dependency-injection pattern and stays with the command definitions in cli.py.",
"Splitting the code_tutor test modules, which are separate commits."
],
"verifier": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (expects exactly 217 passed), plus pre-commit run ruff --files python_pkg/code_tutor/cli.py passing with the two ignores deleted, plus pre-commit run pytest-coverage confirming 100%."
}

View File

@ -0,0 +1,19 @@
{
"title": "Clear the seven over-cap code_tutor test modules",
"objective": "Bring every python_pkg/code_tutor test module under the repo-wide 250-line cap by partitioning them at the banner comments that already mark each function-under-test, taking code_tutor from thirteen violations to zero.",
"acceptance_criteria": [
"bash ~/utils/scripts/check_file_length.sh --all lists no file under python_pkg/code_tutor.",
"The code_tutor suite still reports exactly 217 passing tests -- the count established once the cli lint fix added its covering test -- proving no test was dropped or silently skipped.",
"The package keeps 100% branch coverage of the code_tutor source modules.",
"No patch string changes: this is a pure partition of test sections, and the source splits in the preceding commits already put every patched name in the module each file names.",
"The shared _make_verifier builder moves to tests/conftest.py rather than being duplicated, and the local copy of _make_live_mock that shadowed conftest's is deleted.",
"No assertion is changed and no test is deleted, skipped or weakened.",
"No suppression is added and no coverage exclusion is introduced."
],
"out_of_scope": [
"Changing what any test asserts.",
"Touching the code_tutor source, which is already under the cap.",
"Adding a fourth partN-style file name: each new module is named after the concern it covers."
],
"verifier": "timeout 120 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (expects exactly 217 passed), plus bash ~/utils/scripts/check_file_length.sh --all showing no code_tutor entry, plus pre-commit run --files on the touched files."
}

View File

@ -0,0 +1,51 @@
{
"intent": "Bring code_tutor/_analyzer.py under the 250-line cap by separating the import-graph half and the static scan tables, with no behaviour change.",
"scope": [
"python_pkg/code_tutor/_deps.py, _scan_tables.py (new)",
"python_pkg/code_tutor/_analyzer.py (388 -> 226)",
"python_pkg/code_tutor/cli.py, _plan_builder.py (import paths only)",
"python_pkg/code_tutor/tests/test_analyzer.py (import path only)",
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
],
"changes": [
"Moved get_python_files, _build_dotted_map, _match_deps, get_file_imports and codebase_fingerprint into _deps.py, which imports _should_skip back from _analyzer and owns the hashlib import it was the only user of.",
"Moved the _SKIP_DIRS, _SKIP_SUFFIXES and _OTHER_LANGS frozensets and the _FUNCTION_RE pattern into _scan_tables.py. The first cut left _analyzer.py at 259, nine over; these tables are pure data with no patch targets, which made them the cheapest remaining lines.",
"cli.py and _plan_builder.py import the moved functions from _deps directly. test_analyzer.py's single import block was split across the two modules.",
"_is_binary is the only name any test patches on _analyzer, and it stays there, so no patch string in the package needed editing - a much cheaper seam than the _challenge one."
],
"verification": [
{
"command": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q",
"result": "pass",
"evidence": "216 passed in 2.2s - identical to the baseline count, and inside the timeout that the previous commit's hang made standard here."
},
{
"command": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (first run)",
"result": "fail then pass",
"evidence": "One collection ImportError: test_analyzer.py imports _build_dotted_map and four other moved names from _analyzer. Its import block was split across the two modules and the run returned to 216."
},
{
"command": "PYTHONPATH=. python3 -c \"from python_pkg.code_tutor import _analyzer as a, _deps as d, cli, _plan_builder as pb, _scan_tables as t; a._is_binary; a._SKIP_DIRS; a._FUNCTION_RE; d.get_file_imports; d._should_skip; d.hashlib; cli.codebase_fingerprint; pb.get_python_files\"",
"result": "pass",
"evidence": "all patch targets resolve - including cli.codebase_fingerprint, which three test_cli.py patches name and which still resolves because cli imports it from its new home."
},
{
"command": "wc -l python_pkg/code_tutor/_analyzer.py python_pkg/code_tutor/_deps.py python_pkg/code_tutor/_scan_tables.py",
"result": "pass",
"evidence": "226, 145 and 48 lines, all under the 250-line cap."
},
{
"command": "pre-commit run --files <the touched files and artifacts>",
"result": "pass",
"evidence": "ruff auto-sorted six import statements across the new and edited modules; clean on re-run, and pytest-with-coverage passes."
}
],
"risks": [
"_analyzer <- _deps and _analyzer <- _scan_tables must stay one-way; _analyzer importing from _deps would be a cycle, and _deps already imports _should_skip from _analyzer.",
"The scan tables are now two modules away from the extraction code that reads them, so a future skip-list change has to be made in _scan_tables rather than where it is used."
],
"rollback": [
"git revert the commit; _analyzer.py returns to 388 lines and the two new modules disappear.",
"After rollback, re-run the package suite and confirm it still reports 216 passed."
]
}

View File

@ -0,0 +1,44 @@
{
"intent": "Bring code_tutor/_llm.py under the 250-line cap by moving the Anthropic-API backend into its own module, clearing the last code_tutor source violation.",
"scope": [
"python_pkg/code_tutor/_claude_backend.py (new)",
"python_pkg/code_tutor/_llm.py (295 -> 217)",
"python_pkg/code_tutor/tests/test_llm.py (import and patch paths only)",
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
],
"changes": [
"Moved ClaudeBackend into _claude_backend.py. The seam falls between the two backends precisely because each pins a different plain import: test_llm.py patches requests.post on _llm for OllamaBackend and anthropic.Anthropic for ClaudeBackend, so separating the classes separates the two pinned modules cleanly.",
"_llm.py keeps its anthropic import, because complete_with_fallback still catches anthropic.APIError, and imports ClaudeBackend back since it constructs one.",
"Repointed the four anthropic patch strings belonging to the ClaudeBackend tests. The two in complete_with_fallback tests stay on _llm, since that is the module whose globals the except clause resolves through."
],
"verification": [
{
"command": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q",
"result": "pass",
"evidence": "217 passed - unchanged from the count established by the previous commit."
},
{
"command": "PYTHONPATH=. python3 -c \"from python_pkg.code_tutor import _llm as l, _claude_backend as c; l.requests; l.anthropic; l.ClaudeBackend; l.OllamaBackend; c.anthropic; c.ClaudeBackend\"",
"result": "pass",
"evidence": "resolve OK - anthropic is a real attribute of both modules, which is what makes the per-test split of its patch strings valid."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep code_tutor",
"result": "pass",
"evidence": "Only test modules are listed now: every code_tutor source file is under the 250-line cap."
},
{
"command": "pre-commit run --files <the touched files and artifacts>",
"result": "pass",
"evidence": "ruff flagged E501 on a patch string the longer module name pushed past 88 columns; auto-formatted, then clean. pytest-with-coverage passes at 100%."
}
],
"risks": [
"anthropic is now imported by two modules and patched on both, for different reasons. A future change that stops complete_with_fallback catching APIError would make the _llm import unused, and ruff would strip it and break the two patches that remain there.",
"_llm imports ClaudeBackend from _claude_backend; the reverse import would be a cycle."
],
"rollback": [
"git revert the commit; _llm.py returns to 295 lines and _claude_backend.py disappears.",
"After rollback, re-run the package suite and confirm it still reports 217 passed."
]
}

View File

@ -0,0 +1,52 @@
{
"intent": "Bring code_tutor's cli.py and _verifier.py under the 250-line cap, and fix the two lint rules the cli split would otherwise have forced onto a second suppression entry.",
"scope": [
"python_pkg/code_tutor/_cli_checks.py, _verifier_support.py (new)",
"python_pkg/code_tutor/cli.py (345 -> 222), _verifier.py (347 -> 228)",
"meta/pyproject.toml (two per-file-ignores removed)",
"python_pkg/code_tutor/tests/test_cli.py, test_verifier.py (import and patch paths, plus one new test)",
"Non-goal: no existing assertion changed, no test deleted, skipped or weakened"
],
"changes": [
"Fixed S607 by resolving systemctl through shutil.which and invoking the absolute path, and PERF203 by extracting the API probe into _ollama_reachable so the readiness poll is a plain loop with no try/except in its body. Both ignores are deleted from meta/pyproject.toml rather than copied to a new entry: the repo's suppression count drops by two.",
"The shutil.which fix introduced a systemctl-is-None branch, so test_ensure_ollama_running_no_systemctl was added to cover it. That is the only reason the pass count moves from 216 to 217.",
"Moved the Ollama checks, _ensure_fresh_plan and the codebase-discovery helpers into _cli_checks.py, taking requests, subprocess, time, shutil and json with them. cli.py imports the four entry points back because the command tests patch them there.",
"Moved the verifier's prompt constants, _QUESTIONS, _class_header, _read_snippet and _parse_verdict into _verifier_support.py. The Verifier class stays in _verifier, which is what cli and _session construct.",
"Repointed 17 patch strings in test_cli.py per test: the seven _ensure_ollama_running and _ensure_fresh_plan tests name _cli_checks, the command tests keep cli."
],
"verification": [
{
"command": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q",
"result": "pass",
"evidence": "217 passed - the 216 baseline plus exactly one new test. No existing test was lost; the delta is fully accounted for by the branch the S607 fix added."
},
{
"command": "pre-commit run ruff --files python_pkg/code_tutor/cli.py (with S607 and PERF203 deleted from per-file-ignores)",
"result": "pass",
"evidence": "Passed. This is the check that proves the lint was actually fixed rather than relocated - with the ignores gone, ruff has nothing left to suppress."
},
{
"command": "pre-commit run pytest-coverage --files python_pkg/code_tutor/cli.py",
"result": "fail then pass",
"evidence": "First run reported _cli_checks.py at 97%, missing lines 55-56 - the new systemctl-is-None branch. Covered with a real test rather than an exclusion, per the coverage rule, and the hook then passed."
},
{
"command": "PYTHONPATH=. python3 -c \"<assert every patched name resolves on cli and _cli_checks>\"",
"result": "pass",
"evidence": "Caught that cli.codebase_fingerprint, cli.subprocess and cli.time no longer exist after the move, which is what identified the 17 patch strings needing repointing before the suite was run."
},
{
"command": "wc -l python_pkg/code_tutor/cli.py python_pkg/code_tutor/_cli_checks.py python_pkg/code_tutor/_verifier.py python_pkg/code_tutor/_verifier_support.py",
"result": "pass",
"evidence": "222, 175, 228 and 142 lines, all under the 250-line cap."
}
],
"risks": [
"The Ollama startup path is not exercised against a real systemd here; only its mocked behaviour is pinned. The refactor preserves the call sequence (probe, start, poll to the same deadline, same messages), and the four existing tests plus the new one cover every branch, but a live run was not performed.",
"_verifier_support._QUESTIONS was missed on the first pass of the import block and only surfaced as a NameError in the suite. Any further split of a module with module-level tables should grep for every capitalised or underscore-prefixed module global, not just the functions."
],
"rollback": [
"git revert the commit; cli.py and _verifier.py return to 345 and 347 lines, the two new modules disappear, and the S607/PERF203 ignores come back.",
"After rollback, re-run the package suite and confirm it reports 216 passed - the added test reverts with the branch it covers."
]
}

View File

@ -0,0 +1,45 @@
{
"intent": "Clear the seven over-cap code_tutor test modules by partitioning them at their existing section banners, taking the package from thirteen violations to zero.",
"scope": [
"python_pkg/code_tutor/tests/test_cli.py (500 -> 208) + test_cli_commands.py, test_cli_status_drill.py, test_cli_discovery.py",
"python_pkg/code_tutor/tests/test_analyzer.py (454 -> 225) + test_deps.py",
"python_pkg/code_tutor/tests/test_challenge_part3.py (378 -> 123) + test_challenge_flows.py, test_run_coding_challenge.py",
"python_pkg/code_tutor/tests/test_verifier.py (361 -> 231) + test_verifier_lesson.py",
"python_pkg/code_tutor/tests/test_challenge.py (343 -> 192) + test_pytest_runner.py",
"python_pkg/code_tutor/tests/test_llm.py (324 -> 79) + test_claude_backend.py, test_llm_fallback.py",
"python_pkg/code_tutor/tests/test_challenge_part2.py (307 -> 98) + test_signature_block.py",
"python_pkg/code_tutor/tests/conftest.py (gained _make_verifier)",
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
],
"changes": [
"Wrote a small splitter that cuts a module at a named section banner and copies the ENTIRE original header into the new file, then let ruff's F401 pass prune what each half does not use. That ordering is deliberate: hand-guessing the import block caused an intermediate failure in every earlier test split in this session, and here it pruned 59 imports correctly with none missed.",
"Ten new modules, each named after the concern it covers rather than a partN suffix.",
"_make_verifier was defined between two banners in test_verifier.py, so the cut left it behind while its callers moved. Rather than duplicate it, it moved to tests/conftest.py where _make_live_mock already lives - and test_verifier.py's local _make_live_mock, which had been shadowing conftest's identical copy, was deleted with it.",
"No patch string changed anywhere in this commit. The source splits in the preceding commits had already put every patched name in the module each test file names, so this is a pure partition."
],
"verification": [
{
"command": "timeout 120 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q",
"result": "pass",
"evidence": "217 passed - identical to the count before the split. The single intermediate failure (4 failed, 213 passed) still summed to 217, which confirmed at a glance that the split had misplaced a helper rather than lost a test."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep code_tutor",
"result": "pass",
"evidence": "No output - python_pkg/code_tutor is entirely under the 250-line cap, down from thirteen violations at the start of the package."
},
{
"command": "pre-commit run --files <the touched test files and artifacts>",
"result": "pass",
"evidence": "ruff pruned 59 then 15 unused imports across the new modules; clean on re-run. name-tests-test, mypy, pylint and pytest-with-coverage all pass at 100%."
}
],
"risks": [
"Copying the whole header and letting ruff prune is safe for imports but not for module-level helpers: ruff has no way to know a function defined mid-file is still needed elsewhere. _make_verifier is the case that proves it, and any future banner split should check for defs sitting between sections before running the suite.",
"conftest.py now imports Verifier, so a future move of that class must update the fixture builder as well as the test modules."
],
"rollback": [
"git revert the commit; the seven originals return at their previous sizes and the ten new modules disappear.",
"After rollback, re-run the package suite and confirm it still reports 217 passed."
]
}

View File

@ -51,10 +51,6 @@ unfixable = []
"**/code_tutor/cli.py" = [
"B008", # typer.Argument(...) as a parameter default is the standard Typer
# dependency-injection pattern, not a mutable-default bug.
"S607", # invoking "systemctl" by name (not full path) is fine for a
# local developer tool that assumes a normal PATH.
"PERF203", # the try/except inside the Ollama readiness-poll loop is
# intentional: retry once per second until the server answers.
]
"**/tests/**/*.py" = [
"ARG", # @patch decorators inject mock params that aren't always referenced;

View File

@ -8,47 +8,13 @@ from __future__ import annotations
import ast
from dataclasses import dataclass, field
import hashlib
from pathlib import Path
import re
_SKIP_DIRS: frozenset[str] = frozenset(
{
"third_party",
".venv",
"node_modules",
"__pycache__",
".git",
"dist",
"build",
}
)
_SKIP_SUFFIXES: frozenset[str] = frozenset(
{
".geojson",
".png",
".jpg",
".jpeg",
".gif",
".ico",
".svg",
".webp",
".pdf",
".zip",
".tar",
".gz",
".bin",
}
)
_OTHER_LANGS: frozenset[str] = frozenset(
{".js", ".ts", ".go", ".rs", ".c", ".cpp", ".dart"}
)
# Matches leading keyword(s) followed by an identifier and opening paren.
_FUNCTION_RE: re.Pattern[str] = re.compile(
r"^[ \t]*(?:(?:pub(?:lic)?|priv(?:ate)?|prot(?:ected)?|static|async)\s+)*"
r"(?:def|function|fn|func|void|int|float|bool|string)\s+(\w+)\s*\(",
re.MULTILINE,
from python_pkg.code_tutor._scan_tables import (
_FUNCTION_RE,
_OTHER_LANGS,
_SKIP_DIRS,
_SKIP_SUFFIXES,
)
@ -258,131 +224,3 @@ def extract_items(codebase: Path) -> list[CodeItem]:
elif path.suffix in _OTHER_LANGS:
items.extend(_extract_other(path, rel))
return items
def get_python_files(codebase: Path) -> list[Path]:
"""Return all non-skipped Python files under *codebase*.
Args:
codebase: Root directory to search.
Returns:
Sorted list of absolute Python file paths.
"""
return [
path
for path in sorted(codebase.rglob("*.py"))
if path.is_file() and not _should_skip(str(path.relative_to(codebase)))
]
def _build_dotted_map(codebase: Path, all_files: list[Path]) -> dict[Path, str]:
"""Build a mapping from file to its dotted module path relative to *codebase*.
Args:
codebase: Root directory used for relative path computation.
all_files: All Python files within the codebase.
Returns:
Dict mapping each file in *all_files* to its dotted module string.
Files that cannot be made relative to *codebase* are excluded.
"""
result: dict[Path, str] = {}
for f in all_files:
try:
rel = f.relative_to(codebase)
except ValueError:
continue
result[f] = ".".join(rel.with_suffix("").parts)
return result
def _match_deps(
imported: set[str],
dotted_map: dict[Path, str],
path: Path,
) -> set[Path]:
"""Return the subset of *dotted_map* files that *path* appears to import.
A file ``f`` is included when any imported module name equals, contains,
or is contained by ``f``'s dotted path.
Args:
imported: Set of module name strings collected from import statements.
dotted_map: Mapping of file to dotted module path.
path: The file being analysed (excluded from its own dependency set).
Returns:
Set of dependency files.
"""
deps: set[Path] = set()
for imp in imported:
for f, dotted in dotted_map.items():
if f != path and (
imp == dotted
or imp.endswith("." + dotted)
or dotted.endswith("." + imp)
):
deps.add(f)
return deps
def get_file_imports(path: Path, codebase: Path, all_files: list[Path]) -> set[Path]:
"""Parse Python imports and return the codebase files this file depends on.
Uses a suffix-match heuristic: if an imported module name ends with (or
matches) the dotted path of a file in *all_files*, that file is treated as
a dependency.
Args:
path: The Python file to analyse.
codebase: Root directory used for relative path computation.
all_files: All Python files within the codebase.
Returns:
Subset of *all_files* that *path* imports from.
"""
try:
source = path.read_text(encoding="utf-8", errors="replace")
tree = ast.parse(source)
except SyntaxError:
return set()
imported: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imported.add(alias.name)
elif isinstance(node, ast.ImportFrom) and node.module:
imported.add(node.module)
dotted_map = _build_dotted_map(codebase, all_files)
return _match_deps(imported, dotted_map, path)
def codebase_fingerprint(codebase: Path) -> str:
"""Compute a short fingerprint of all source files under *codebase*.
Uses each file's mtime and size rather than content, so it is fast
even on large repositories. Returns a 16-character hex string that
changes whenever any tracked file is added, removed, or modified.
Args:
codebase: Root directory of the codebase.
Returns:
16-character hex fingerprint string.
"""
parts: list[str] = []
for path in sorted(codebase.rglob("*")):
if not path.is_file():
continue
rel = str(path.relative_to(codebase))
if _should_skip(rel):
continue
try:
s = path.stat()
parts.append(f"{rel}:{s.st_mtime_ns}:{s.st_size}")
except OSError:
pass
return hashlib.sha256("\n".join(parts).encode()).hexdigest()[:16]

View File

@ -0,0 +1,93 @@
"""The Anthropic-API backend used as a fallback when the local model is weak.
Split out of :mod:`python_pkg.code_tutor._llm` to keep it under the 250-line
cap. The ``anthropic`` import travels with the only class that uses it, so
``tests/test_llm.py`` patches it on this module and ``requests`` on ``_llm``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import anthropic
if TYPE_CHECKING:
from collections.abc import Callable
class ClaudeBackend:
"""LLM backend that calls the Anthropic Claude API.
Reads ``ANTHROPIC_API_KEY`` from the environment automatically.
Args:
model: Claude model identifier.
max_tokens: Maximum tokens in the response.
"""
def __init__(
self,
model: str = "claude-sonnet-4-6",
max_tokens: int = 1024,
) -> None:
"""Initialise Anthropic client."""
self._client = anthropic.Anthropic()
self._model = model
self._max_tokens = max_tokens
def complete(self, system: str, user: str) -> str:
"""Call Claude and return the response text.
Args:
system: System prompt.
user: User message.
Returns:
Response string from Claude.
Raises:
anthropic.APIError: On any Anthropic API failure.
"""
message = self._client.messages.create(
model=self._model,
max_tokens=self._max_tokens,
system=system,
messages=[{"role": "user", "content": user}],
)
block = message.content[0]
if hasattr(block, "text"):
return str(block.text)
return ""
def stream(
self,
system: str,
user: str,
on_token: Callable[[str], None],
) -> str:
"""Call Claude with streaming, invoking *on_token* per text delta.
Falls back to ``complete`` on ``APIError``.
Args:
system: System prompt.
user: User message.
on_token: Callback invoked with each text delta as it arrives.
Returns:
Full accumulated response text.
"""
try:
parts: list[str] = []
with self._client.messages.stream(
model=self._model,
max_tokens=self._max_tokens,
system=system,
messages=[{"role": "user", "content": user}],
) as s:
for text in s.text_stream:
on_token(text)
parts.append(text)
return "".join(parts)
except anthropic.APIError:
return self.complete(system, user)

View File

@ -0,0 +1,175 @@
"""Ollama readiness and plan-freshness checks for the CLI commands.
Split out of :mod:`python_pkg.code_tutor.cli` to keep it under the 250-line
cap. ``cli`` imports all three entry points back, because the command tests
patch them on ``cli``; ``requests``, ``subprocess`` and ``time`` travel here
with the code that calls them, and the Ollama tests patch them on this module.
"""
from __future__ import annotations
import json
from pathlib import Path
import shutil
import subprocess
import time
from typing import TYPE_CHECKING, cast
import requests
from python_pkg.code_tutor._analyzer import extract_items
from python_pkg.code_tutor._deps import codebase_fingerprint
from python_pkg.code_tutor._plan_builder import build_plan
from python_pkg.code_tutor._progress import save_plan
if TYPE_CHECKING:
from rich.console import Console
from python_pkg.code_tutor._progress import PlanData
_OLLAMA_API = "http://localhost:11434/api/tags"
_OLLAMA_START_TIMEOUT = 30
def _ollama_reachable() -> bool:
"""Return True when the Ollama API answers.
Keeping the probe in its own function is what lets the readiness poll below
stay a plain loop with no try/except in its body.
"""
try:
requests.get(_OLLAMA_API, timeout=2)
except requests.exceptions.RequestException:
return False
return True
def _start_ollama_service(console: Console) -> bool:
"""Run ``systemctl start ollama``. Returns False when the call fails.
Args:
console: Rich console for status messages.
"""
systemctl = shutil.which("systemctl")
if systemctl is None:
console.print("[red]systemctl not found.[/red]")
return False
try:
subprocess.run(
[systemctl, "start", "ollama"],
check=True,
capture_output=True,
)
except subprocess.CalledProcessError as exc:
console.print(
f"[red]systemctl start ollama failed: {exc.stderr.decode().strip()}[/red]"
)
return False
return True
def _ensure_ollama_running(console: Console) -> bool:
"""Start the Ollama systemd service if it is not already reachable.
Tries ``systemctl start ollama`` and polls the API for up to
``_OLLAMA_START_TIMEOUT`` seconds.
Args:
console: Rich console for status messages.
Returns:
True when Ollama is reachable, False after timeout.
"""
if _ollama_reachable():
return True
console.print("[yellow]Ollama not running -- starting via systemctl...[/yellow]")
if not _start_ollama_service(console):
return False
deadline = time.monotonic() + _OLLAMA_START_TIMEOUT
while time.monotonic() < deadline:
if _ollama_reachable():
console.print("[green]Ollama is up.[/green]")
return True
time.sleep(1)
console.print("[red]Ollama did not become ready in time.[/red]")
return False
def _ensure_fresh_plan(codebase: Path, plan: PlanData, console: Console) -> PlanData:
"""Rebuild *plan* if the codebase source files have changed since it was created.
Compares the plan's stored fingerprint against the current one. When they
differ, re-runs the full analyze pipeline, saves the new plan to disk, and
returns it. Plans without a stored fingerprint (created before this feature)
are returned unchanged.
Args:
codebase: Root directory of the codebase.
plan: Plan dict loaded from ``plan.json``.
console: Rich console for status messages.
Returns:
The original plan when up-to-date, or a freshly built ``PlanData`` when
the fingerprint has changed.
"""
saved = plan.get("source_fingerprint", "")
if not saved:
return plan
current = codebase_fingerprint(codebase)
if current == saved:
return plan
console.print(
"[yellow]Plan is stale -- source files changed. Rebuilding...[/yellow]"
)
items = extract_items(codebase)
if not items:
console.print("[red]No extractable items found -- keeping existing plan.[/red]")
return plan
new_plan = build_plan(codebase, items)
save_plan(codebase, new_plan)
n = new_plan["total_items"]
console.print(f"[green]Plan rebuilt: {n} items.[/green]")
return cast("PlanData", new_plan)
def _find_codebase_for_file(file: Path) -> Path | None:
"""Search all saved plans and return the codebase that contains *file*.
Args:
file: Absolute path to the source file.
Returns:
The codebase ``Path`` whose plan contains *file*, or ``None``.
"""
config_root = Path.home() / ".config" / "code_tutor"
if not config_root.exists():
return None
for plan_file in sorted(config_root.glob("*/plan.json")):
result = _check_plan_file(plan_file, file)
if result is not None:
return result
return None
def _check_plan_file(plan_file: Path, file: Path) -> Path | None:
"""Return the codebase path from *plan_file* if it contains *file*, else None.
Args:
plan_file: Path to a ``plan.json`` file.
file: Absolute path to look up.
Returns:
The codebase ``Path`` when *file* is relative to it, or ``None``.
"""
try:
data = json.loads(plan_file.read_text(encoding="utf-8"))
codebase = Path(str(data.get("codebase_path", "")))
file.relative_to(codebase)
except (ValueError, KeyError, OSError):
return None
return codebase

View File

@ -0,0 +1,145 @@
"""Walking the codebase for Python files and mapping their import graph.
Split out of :mod:`python_pkg.code_tutor._analyzer` to keep it under the
250-line cap. Item extraction stays there; this module answers "which files
does this one depend on" and fingerprints the tree.
"""
from __future__ import annotations
import ast
import hashlib
from typing import TYPE_CHECKING
from python_pkg.code_tutor._analyzer import _should_skip
if TYPE_CHECKING:
from pathlib import Path
def get_python_files(codebase: Path) -> list[Path]:
"""Return all non-skipped Python files under *codebase*.
Args:
codebase: Root directory to search.
Returns:
Sorted list of absolute Python file paths.
"""
return [
path
for path in sorted(codebase.rglob("*.py"))
if path.is_file() and not _should_skip(str(path.relative_to(codebase)))
]
def _build_dotted_map(codebase: Path, all_files: list[Path]) -> dict[Path, str]:
"""Build a mapping from file to its dotted module path relative to *codebase*.
Args:
codebase: Root directory used for relative path computation.
all_files: All Python files within the codebase.
Returns:
Dict mapping each file in *all_files* to its dotted module string.
Files that cannot be made relative to *codebase* are excluded.
"""
result: dict[Path, str] = {}
for f in all_files:
try:
rel = f.relative_to(codebase)
except ValueError:
continue
result[f] = ".".join(rel.with_suffix("").parts)
return result
def _match_deps(
imported: set[str],
dotted_map: dict[Path, str],
path: Path,
) -> set[Path]:
"""Return the subset of *dotted_map* files that *path* appears to import.
A file ``f`` is included when any imported module name equals, contains,
or is contained by ``f``'s dotted path.
Args:
imported: Set of module name strings collected from import statements.
dotted_map: Mapping of file to dotted module path.
path: The file being analysed (excluded from its own dependency set).
Returns:
Set of dependency files.
"""
deps: set[Path] = set()
for imp in imported:
for f, dotted in dotted_map.items():
if f != path and (
imp == dotted
or imp.endswith("." + dotted)
or dotted.endswith("." + imp)
):
deps.add(f)
return deps
def get_file_imports(path: Path, codebase: Path, all_files: list[Path]) -> set[Path]:
"""Parse Python imports and return the codebase files this file depends on.
Uses a suffix-match heuristic: if an imported module name ends with (or
matches) the dotted path of a file in *all_files*, that file is treated as
a dependency.
Args:
path: The Python file to analyse.
codebase: Root directory used for relative path computation.
all_files: All Python files within the codebase.
Returns:
Subset of *all_files* that *path* imports from.
"""
try:
source = path.read_text(encoding="utf-8", errors="replace")
tree = ast.parse(source)
except SyntaxError:
return set()
imported: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imported.add(alias.name)
elif isinstance(node, ast.ImportFrom) and node.module:
imported.add(node.module)
dotted_map = _build_dotted_map(codebase, all_files)
return _match_deps(imported, dotted_map, path)
def codebase_fingerprint(codebase: Path) -> str:
"""Compute a short fingerprint of all source files under *codebase*.
Uses each file's mtime and size rather than content, so it is fast
even on large repositories. Returns a 16-character hex string that
changes whenever any tracked file is added, removed, or modified.
Args:
codebase: Root directory of the codebase.
Returns:
16-character hex fingerprint string.
"""
parts: list[str] = []
for path in sorted(codebase.rglob("*")):
if not path.is_file():
continue
rel = str(path.relative_to(codebase))
if _should_skip(rel):
continue
try:
s = path.stat()
parts.append(f"{rel}:{s.st_mtime_ns}:{s.st_size}")
except OSError:
pass
return hashlib.sha256("\n".join(parts).encode()).hexdigest()[:16]

View File

@ -12,6 +12,8 @@ from typing import TYPE_CHECKING, Protocol
import anthropic
import requests
from python_pkg.code_tutor._claude_backend import ClaudeBackend
if TYPE_CHECKING:
from collections.abc import Callable
@ -157,84 +159,6 @@ class OllamaBackend:
return "".join(parts)
class ClaudeBackend:
"""LLM backend that calls the Anthropic Claude API.
Reads ``ANTHROPIC_API_KEY`` from the environment automatically.
Args:
model: Claude model identifier.
max_tokens: Maximum tokens in the response.
"""
def __init__(
self,
model: str = "claude-sonnet-4-6",
max_tokens: int = 1024,
) -> None:
"""Initialise Anthropic client."""
self._client = anthropic.Anthropic()
self._model = model
self._max_tokens = max_tokens
def complete(self, system: str, user: str) -> str:
"""Call Claude and return the response text.
Args:
system: System prompt.
user: User message.
Returns:
Response string from Claude.
Raises:
anthropic.APIError: On any Anthropic API failure.
"""
message = self._client.messages.create(
model=self._model,
max_tokens=self._max_tokens,
system=system,
messages=[{"role": "user", "content": user}],
)
block = message.content[0]
if hasattr(block, "text"):
return str(block.text)
return ""
def stream(
self,
system: str,
user: str,
on_token: Callable[[str], None],
) -> str:
"""Call Claude with streaming, invoking *on_token* per text delta.
Falls back to ``complete`` on ``APIError``.
Args:
system: System prompt.
user: User message.
on_token: Callback invoked with each text delta as it arrives.
Returns:
Full accumulated response text.
"""
try:
parts: list[str] = []
with self._client.messages.stream(
model=self._model,
max_tokens=self._max_tokens,
system=system,
messages=[{"role": "user", "content": user}],
) as s:
for text in s.text_stream:
on_token(text)
parts.append(text)
return "".join(parts)
except anthropic.APIError:
return self.complete(system, user)
def _is_weak(response: str) -> bool:
"""Return True if *response* looks too short or expresses uncertainty.

View File

@ -6,14 +6,17 @@ import dataclasses
from datetime import datetime, timezone
from graphlib import CycleError, TopologicalSorter
from pathlib import Path
from typing import TYPE_CHECKING
from python_pkg.code_tutor._analyzer import (
CodeItem,
from python_pkg.code_tutor._deps import (
codebase_fingerprint,
get_file_imports,
get_python_files,
)
if TYPE_CHECKING:
from python_pkg.code_tutor._analyzer import CodeItem
def _toposort_files(file_deps: dict[Path, set[Path]]) -> list[Path]:
"""Return files in topological order so dependencies come first.

View File

@ -0,0 +1,48 @@
"""Which paths the analyzer walks past, and how it spots a function.
Split out of :mod:`python_pkg.code_tutor._analyzer` to keep it under the
250-line cap. Pure data tables with no collaborators, so nothing patches them.
"""
from __future__ import annotations
import re
_SKIP_DIRS: frozenset[str] = frozenset(
{
"third_party",
".venv",
"node_modules",
"__pycache__",
".git",
"dist",
"build",
}
)
_SKIP_SUFFIXES: frozenset[str] = frozenset(
{
".geojson",
".png",
".jpg",
".jpeg",
".gif",
".ico",
".svg",
".webp",
".pdf",
".zip",
".tar",
".gz",
".bin",
}
)
_OTHER_LANGS: frozenset[str] = frozenset(
{".js", ".ts", ".go", ".rs", ".c", ".cpp", ".dart"}
)
# Matches leading keyword(s) followed by an identifier and opening paren.
_FUNCTION_RE: re.Pattern[str] = re.compile(
r"^[ \t]*(?:(?:pub(?:lic)?|priv(?:ate)?|prot(?:ected)?|static|async)\s+)*"
r"(?:def|function|fn|func|void|int|float|bool|string)\s+(\w+)\s*\(",
re.MULTILINE,
)

View File

@ -6,9 +6,6 @@ The LLM explanation is NEVER shown before the user attempts to explain.
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import time
from typing import TYPE_CHECKING
@ -18,6 +15,15 @@ from rich.text import Text
from python_pkg.code_tutor._challenge_flows import run_coding_challenge
from python_pkg.code_tutor._progress import LessonRecord
from python_pkg.code_tutor._verifier_support import (
_EXPLAIN_SYSTEM,
_IMPROVEMENT_Q,
_MAX_ATTEMPTS,
_QUESTIONS,
_SYSTEM_PROMPT,
_parse_verdict,
_read_snippet,
)
if TYPE_CHECKING:
from collections.abc import Callable
@ -27,131 +33,6 @@ if TYPE_CHECKING:
from python_pkg.code_tutor._analyzer import CodeItem
from python_pkg.code_tutor._llm import Backend
_MAX_ATTEMPTS = 3
_SYSTEM_PROMPT = (
"You are a fair but rigorous code tutor assessing whether a student"
" genuinely understands a piece of code.\n\n"
"Grade their explanation PASS or FAIL.\n\n"
"PASS when the student demonstrates understanding of:\n"
" - what problem the code solves (purpose)\n"
" - what goes in (inputs/parameters and their roles)\n"
" - what comes out or happens (return value or side effect)\n"
" - any key behavior that would surprise a reader"
" (edge cases, error handling, non-obvious constraints)\n\n"
"You do NOT require verbatim phrasing from the code or docstring.\n"
"Correct paraphrasing counts as understanding.\n"
"ONLY cite a gap if it is genuinely absent from the student's answer"
" -- do NOT cite a gap the student already covered in different words.\n\n"
"FAIL only if the student is vague, factually wrong, or missed a key"
" behavioral detail that materially changes how the code is used.\n"
'"It does some stuff" = FAIL. "It processes data" = FAIL.'
' But "it reads the first 512 bytes and checks for a null byte" = PASS'
" on the behavior criterion, even if they didn't mention OSError.\n\n"
"Respond with valid JSON only, no other text:\n"
'{"verdict": "PASS" | "FAIL",'
' "gap": "<one sentence on the specific missing piece, or empty string on PASS>"}'
)
_EXPLAIN_SYSTEM = (
"You are a code tutor."
" Explain the following code clearly and concisely in 3-5 sentences."
)
_QUESTIONS: tuple[tuple[str, str], ...] = (
("Purpose", "What does this code do?"),
("Inputs", "What are the inputs (parameters / arguments)?"),
("Outputs", "What does it output or do as a side effect?"),
("Why", "Why does it exist? What problem does it solve?"),
)
_IMPROVEMENT_Q = "What would you improve or simplify here? (Enter to skip)"
def _class_header(lines: list[str], class_name: str, before_line: int) -> str:
"""Find the class definition for *class_name* and return a short header.
Searches backward from *before_line* for ``class <class_name>``. Returns
the class signature plus up to 4 following lines (docstring / key attrs).
Args:
lines: All source lines of the file (0-indexed).
class_name: Name of the enclosing class.
before_line: 1-based line number of the method; search stops here.
Returns:
A short string summary of the class, or ``""`` if not found.
"""
pattern = re.compile(rf"^class\s+{re.escape(class_name)}\b")
for i in range(min(before_line - 1, len(lines)) - 1, -1, -1):
if pattern.match(lines[i]):
snippet_end = min(i + 5, before_line - 1)
return "\n".join(lines[i:snippet_end])
return ""
def _read_snippet(item: CodeItem, codebase_path: str) -> str:
"""Read source lines for *item* from *codebase_path*.
When the item belongs to a class, a short class header is prepended so
the user has context about what ``self`` refers to.
Args:
item: Code item whose file and line range to read.
codebase_path: Absolute path of the codebase root.
Returns:
The extracted source lines as a single string, or a placeholder
message when the file cannot be read.
"""
method_src = ""
try:
text = (Path(codebase_path) / item.file).read_text(
encoding="utf-8", errors="replace"
)
lines = text.splitlines()
start = max(0, item.start_line - 1)
end = min(len(lines), item.end_line)
method_src = "\n".join(lines[start:end])
if item.class_name:
header = _class_header(lines, item.class_name, item.start_line)
if header:
return (
f"# class {item.class_name} (context):\n{header}"
f"\n\n# method:\n{method_src}"
)
except OSError:
return f"(source unavailable for {item.file})"
return method_src
def _parse_verdict(raw: str) -> tuple[str, str]:
"""Parse the LLM's JSON verdict, tolerating markdown code fences.
Args:
raw: Raw text returned by the judge LLM.
Returns:
Tuple of ``(verdict, gap)`` where *verdict* is ``"PASS"`` or
``"FAIL"`` and *gap* is a one-sentence explanation of what was wrong.
Returns ``("FAIL", ...)`` on any parse failure.
"""
clean = re.sub(r"```(?:json)?\s*", "", raw, flags=re.DOTALL).strip()
start = clean.find("{")
end = clean.rfind("}") + 1
if start == -1 or end == 0:
return "FAIL", "Could not parse response from judge."
try:
data = json.loads(clean[start:end])
except json.JSONDecodeError:
return "FAIL", "Could not parse response from judge."
verdict = str(data.get("verdict", "FAIL")).upper()
if verdict not in {"PASS", "FAIL"}:
verdict = "FAIL"
gap = str(data.get("gap", "No specific gap identified."))
return verdict, gap
class Verifier:
"""Runs Socratic lessons: user explains first, then the LLM judges.

View File

@ -0,0 +1,142 @@
"""Prompts and source-snippet helpers for the lesson verifier.
Split out of :mod:`python_pkg.code_tutor._verifier` to keep it under the
250-line cap. ``Verifier`` itself stays there, because that is the name
``cli`` and ``_session`` construct and the tests patch.
"""
from __future__ import annotations
import json
from pathlib import Path
import re
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from python_pkg.code_tutor._analyzer import CodeItem
_MAX_ATTEMPTS = 3
_SYSTEM_PROMPT = (
"You are a fair but rigorous code tutor assessing whether a student"
" genuinely understands a piece of code.\n\n"
"Grade their explanation PASS or FAIL.\n\n"
"PASS when the student demonstrates understanding of:\n"
" - what problem the code solves (purpose)\n"
" - what goes in (inputs/parameters and their roles)\n"
" - what comes out or happens (return value or side effect)\n"
" - any key behavior that would surprise a reader"
" (edge cases, error handling, non-obvious constraints)\n\n"
"You do NOT require verbatim phrasing from the code or docstring.\n"
"Correct paraphrasing counts as understanding.\n"
"ONLY cite a gap if it is genuinely absent from the student's answer"
" -- do NOT cite a gap the student already covered in different words.\n\n"
"FAIL only if the student is vague, factually wrong, or missed a key"
" behavioral detail that materially changes how the code is used.\n"
'"It does some stuff" = FAIL. "It processes data" = FAIL.'
' But "it reads the first 512 bytes and checks for a null byte" = PASS'
" on the behavior criterion, even if they didn't mention OSError.\n\n"
"Respond with valid JSON only, no other text:\n"
'{"verdict": "PASS" | "FAIL",'
' "gap": "<one sentence on the specific missing piece, or empty string on PASS>"}'
)
_EXPLAIN_SYSTEM = (
"You are a code tutor."
" Explain the following code clearly and concisely in 3-5 sentences."
)
_QUESTIONS: tuple[tuple[str, str], ...] = (
("Purpose", "What does this code do?"),
("Inputs", "What are the inputs (parameters / arguments)?"),
("Outputs", "What does it output or do as a side effect?"),
("Why", "Why does it exist? What problem does it solve?"),
)
_IMPROVEMENT_Q = "What would you improve or simplify here? (Enter to skip)"
def _class_header(lines: list[str], class_name: str, before_line: int) -> str:
"""Find the class definition for *class_name* and return a short header.
Searches backward from *before_line* for ``class <class_name>``. Returns
the class signature plus up to 4 following lines (docstring / key attrs).
Args:
lines: All source lines of the file (0-indexed).
class_name: Name of the enclosing class.
before_line: 1-based line number of the method; search stops here.
Returns:
A short string summary of the class, or ``""`` if not found.
"""
pattern = re.compile(rf"^class\s+{re.escape(class_name)}\b")
for i in range(min(before_line - 1, len(lines)) - 1, -1, -1):
if pattern.match(lines[i]):
snippet_end = min(i + 5, before_line - 1)
return "\n".join(lines[i:snippet_end])
return ""
def _read_snippet(item: CodeItem, codebase_path: str) -> str:
"""Read source lines for *item* from *codebase_path*.
When the item belongs to a class, a short class header is prepended so
the user has context about what ``self`` refers to.
Args:
item: Code item whose file and line range to read.
codebase_path: Absolute path of the codebase root.
Returns:
The extracted source lines as a single string, or a placeholder
message when the file cannot be read.
"""
method_src = ""
try:
text = (Path(codebase_path) / item.file).read_text(
encoding="utf-8", errors="replace"
)
lines = text.splitlines()
start = max(0, item.start_line - 1)
end = min(len(lines), item.end_line)
method_src = "\n".join(lines[start:end])
if item.class_name:
header = _class_header(lines, item.class_name, item.start_line)
if header:
return (
f"# class {item.class_name} (context):\n{header}"
f"\n\n# method:\n{method_src}"
)
except OSError:
return f"(source unavailable for {item.file})"
return method_src
def _parse_verdict(raw: str) -> tuple[str, str]:
"""Parse the LLM's JSON verdict, tolerating markdown code fences.
Args:
raw: Raw text returned by the judge LLM.
Returns:
Tuple of ``(verdict, gap)`` where *verdict* is ``"PASS"`` or
``"FAIL"`` and *gap* is a one-sentence explanation of what was wrong.
Returns ``("FAIL", ...)`` on any parse failure.
"""
clean = re.sub(r"```(?:json)?\s*", "", raw, flags=re.DOTALL).strip()
start = clean.find("{")
end = clean.rfind("}") + 1
if start == -1 or end == 0:
return "FAIL", "Could not parse response from judge."
try:
data = json.loads(clean[start:end])
except json.JSONDecodeError:
return "FAIL", "Could not parse response from judge."
verdict = str(data.get("verdict", "FAIL")).upper()
if verdict not in {"PASS", "FAIL"}:
verdict = "FAIL"
gap = str(data.get("gap", "No specific gap identified."))
return verdict, gap

View File

@ -9,23 +9,23 @@ Commands:
from __future__ import annotations
import json
from pathlib import Path
import subprocess
import sys
import time
from typing import cast
import requests
from rich.console import Console
from rich.table import Table
import typer
from python_pkg.code_tutor._analyzer import codebase_fingerprint, extract_items
from python_pkg.code_tutor._analyzer import extract_items
from python_pkg.code_tutor._cli_checks import (
_ensure_fresh_plan,
_ensure_ollama_running,
_find_codebase_for_file,
)
from python_pkg.code_tutor._llm import OllamaBackend
from python_pkg.code_tutor._plan_builder import build_plan
from python_pkg.code_tutor._progress import (
PlanData,
append_session_record,
config_dir,
item_from_data,
@ -43,91 +43,6 @@ _OLLAMA_API = "http://localhost:11434/api/tags"
_OLLAMA_START_TIMEOUT = 30
def _ensure_ollama_running(console: Console) -> bool:
"""Start the Ollama systemd service if it is not already reachable.
Tries ``systemctl start ollama`` and polls the API for up to
``_OLLAMA_START_TIMEOUT`` seconds.
Args:
console: Rich console for status messages.
Returns:
True when Ollama is reachable, False after timeout.
"""
try:
requests.get(_OLLAMA_API, timeout=2)
except requests.exceptions.RequestException:
pass
else:
return True
console.print("[yellow]Ollama not running -- starting via systemctl...[/yellow]")
try:
subprocess.run(
["systemctl", "start", "ollama"],
check=True,
capture_output=True,
)
except subprocess.CalledProcessError as exc:
console.print(
f"[red]systemctl start ollama failed: {exc.stderr.decode().strip()}[/red]"
)
return False
deadline = time.monotonic() + _OLLAMA_START_TIMEOUT
while time.monotonic() < deadline:
try:
requests.get(_OLLAMA_API, timeout=2)
except requests.exceptions.RequestException:
time.sleep(1)
else:
console.print("[green]Ollama is up.[/green]")
return True
console.print("[red]Ollama did not become ready in time.[/red]")
return False
def _ensure_fresh_plan(codebase: Path, plan: PlanData, console: Console) -> PlanData:
"""Rebuild *plan* if the codebase source files have changed since it was created.
Compares the plan's stored fingerprint against the current one. When they
differ, re-runs the full analyze pipeline, saves the new plan to disk, and
returns it. Plans without a stored fingerprint (created before this feature)
are returned unchanged.
Args:
codebase: Root directory of the codebase.
plan: Plan dict loaded from ``plan.json``.
console: Rich console for status messages.
Returns:
The original plan when up-to-date, or a freshly built ``PlanData`` when
the fingerprint has changed.
"""
saved = plan.get("source_fingerprint", "")
if not saved:
return plan
current = codebase_fingerprint(codebase)
if current == saved:
return plan
console.print(
"[yellow]Plan is stale -- source files changed. Rebuilding...[/yellow]"
)
items = extract_items(codebase)
if not items:
console.print("[red]No extractable items found -- keeping existing plan.[/red]")
return plan
new_plan = build_plan(codebase, items)
save_plan(codebase, new_plan)
n = new_plan["total_items"]
console.print(f"[green]Plan rebuilt: {n} items.[/green]")
return cast("PlanData", new_plan)
@app.command()
def analyze(
codebase: Path = typer.Argument(
@ -303,43 +218,5 @@ def drill(
append_session_record(codebase, record)
def _find_codebase_for_file(file: Path) -> Path | None:
"""Search all saved plans and return the codebase that contains *file*.
Args:
file: Absolute path to the source file.
Returns:
The codebase ``Path`` whose plan contains *file*, or ``None``.
"""
config_root = Path.home() / ".config" / "code_tutor"
if not config_root.exists():
return None
for plan_file in sorted(config_root.glob("*/plan.json")):
result = _check_plan_file(plan_file, file)
if result is not None:
return result
return None
def _check_plan_file(plan_file: Path, file: Path) -> Path | None:
"""Return the codebase path from *plan_file* if it contains *file*, else None.
Args:
plan_file: Path to a ``plan.json`` file.
file: Absolute path to look up.
Returns:
The codebase ``Path`` when *file* is relative to it, or ``None``.
"""
try:
data = json.loads(plan_file.read_text(encoding="utf-8"))
codebase = Path(str(data.get("codebase_path", "")))
file.relative_to(codebase)
except (ValueError, KeyError, OSError):
return None
return codebase
if __name__ == "__main__":
sys.exit(app())

View File

@ -11,6 +11,7 @@ from __future__ import annotations
from unittest.mock import MagicMock
from python_pkg.code_tutor._analyzer import CodeItem
from python_pkg.code_tutor._verifier import Verifier
def _item(
@ -54,3 +55,10 @@ def _make_live_mock() -> MagicMock:
live.__enter__ = MagicMock(return_value=live)
live.__exit__ = MagicMock(return_value=False)
return live
def _make_verifier() -> tuple[Verifier, MagicMock, MagicMock]:
mock_backend = MagicMock()
mock_console = MagicMock()
verifier = Verifier(mock_backend, mock_console)
return verifier, mock_backend, mock_console

View File

@ -3,25 +3,22 @@
from __future__ import annotations
import ast
from pathlib import Path
from typing import TYPE_CHECKING
from unittest.mock import patch
from python_pkg.code_tutor._analyzer import (
CodeItem,
_build_dotted_map,
_extract_other,
_extract_python,
_FunctionVisitor,
_is_binary,
_make_id,
_match_deps,
_should_skip,
codebase_fingerprint,
extract_items,
get_file_imports,
get_python_files,
)
if TYPE_CHECKING:
from pathlib import Path
# ---------------------------------------------------------------------------
# _is_binary
# ---------------------------------------------------------------------------
@ -221,232 +218,3 @@ def test_extract_items_is_binary_oserror(tmp_path: Path) -> None:
):
items = extract_items(tmp_path)
assert items == []
# ---------------------------------------------------------------------------
# get_python_files
# ---------------------------------------------------------------------------
def test_get_python_files(tmp_path: Path) -> None:
(tmp_path / "a.py").write_text("x = 1", encoding="utf-8")
(tmp_path / "b.py").write_text("y = 2", encoding="utf-8")
skip_dir = tmp_path / ".venv"
skip_dir.mkdir()
(skip_dir / "c.py").write_text("z = 3", encoding="utf-8")
files = get_python_files(tmp_path)
names = {f.name for f in files}
assert "a.py" in names
assert "b.py" in names
assert "c.py" not in names
# ---------------------------------------------------------------------------
# _build_dotted_map
# ---------------------------------------------------------------------------
def test_build_dotted_map_normal(tmp_path: Path) -> None:
f = tmp_path / "pkg" / "mod.py"
f.parent.mkdir()
f.write_text("x = 1", encoding="utf-8")
result = _build_dotted_map(tmp_path, [f])
assert result[f] == "pkg.mod"
def test_build_dotted_map_value_error(tmp_path: Path) -> None:
other = tmp_path.parent / "other.py"
result = _build_dotted_map(tmp_path, [other])
assert other not in result
# ---------------------------------------------------------------------------
# _match_deps
# ---------------------------------------------------------------------------
def test_match_deps_exact(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
dotted_map = {f: "mod"}
path = tmp_path / "main.py"
result = _match_deps({"mod"}, dotted_map, path)
assert f in result
def test_match_deps_prefix(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
dotted_map = {f: "mod"}
path = tmp_path / "main.py"
result = _match_deps({"pkg.mod"}, dotted_map, path)
assert f in result
def test_match_deps_suffix(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
dotted_map = {f: "pkg.mod"}
path = tmp_path / "main.py"
result = _match_deps({"mod"}, dotted_map, path)
assert f in result
def test_match_deps_excludes_self(tmp_path: Path) -> None:
path = tmp_path / "mod.py"
dotted_map = {path: "mod"}
result = _match_deps({"mod"}, dotted_map, path)
assert path not in result
def test_match_deps_no_match(tmp_path: Path) -> None:
f = tmp_path / "other.py"
dotted_map = {f: "other"}
path = tmp_path / "main.py"
result = _match_deps({"unrelated"}, dotted_map, path)
assert f not in result
# ---------------------------------------------------------------------------
# Tests for get_file_imports
# ---------------------------------------------------------------------------
def test_get_file_imports_import(tmp_path: Path) -> None:
f = tmp_path / "main.py"
dep = tmp_path / "utils.py"
f.write_text("import utils\n", encoding="utf-8")
dep.write_text("x = 1", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f, dep])
assert dep in result
def test_get_file_imports_from_import(tmp_path: Path) -> None:
f = tmp_path / "main.py"
dep = tmp_path / "utils.py"
f.write_text("from utils import helper\n", encoding="utf-8")
dep.write_text("def helper(): pass\n", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f, dep])
assert dep in result
def test_get_file_imports_from_import_none_module(tmp_path: Path) -> None:
# Relative import: node.module is None
f = tmp_path / "main.py"
f.write_text("from . import helper\n", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f])
assert result == set()
def test_get_file_imports_syntax_error(tmp_path: Path) -> None:
f = tmp_path / "bad.py"
f.write_text("def (broken):\n", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f])
assert result == set()
# ---------------------------------------------------------------------------
# codebase_fingerprint
# ---------------------------------------------------------------------------
def test_codebase_fingerprint_basic(tmp_path: Path) -> None:
(tmp_path / "a.py").write_text("x = 1", encoding="utf-8")
result = codebase_fingerprint(tmp_path)
assert len(result) == 16
assert result.isalnum()
def test_codebase_fingerprint_skips_dir(tmp_path: Path) -> None:
sub = tmp_path / "sub"
sub.mkdir()
result = codebase_fingerprint(tmp_path)
assert len(result) == 16
def test_codebase_fingerprint_skips_should_skip(tmp_path: Path) -> None:
venv = tmp_path / ".venv"
venv.mkdir()
(venv / "lib.py").write_text("x = 1", encoding="utf-8")
result_without = codebase_fingerprint(tmp_path)
(tmp_path / "real.py").write_text("y = 2", encoding="utf-8")
result_with = codebase_fingerprint(tmp_path)
assert result_without != result_with
def test_codebase_fingerprint_stat_oserror(tmp_path: Path) -> None:
(tmp_path / "source.py").write_text("x = 1", encoding="utf-8")
stat_calls: dict[str, int] = {}
real_stat = Path.stat
def patched_stat(self: Path, **kwargs: object) -> object:
key = str(self)
stat_calls[key] = stat_calls.get(key, 0) + 1
if stat_calls[key] >= 2 and key.endswith(".py"):
msg = "simulated stat failure"
raise OSError(msg)
return real_stat(self, **kwargs)
with patch.object(Path, "stat", patched_stat):
result = codebase_fingerprint(tmp_path)
assert len(result) == 16
def test_codebase_fingerprint_changes_on_modification(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("x = 1", encoding="utf-8")
fp1 = codebase_fingerprint(tmp_path)
f.write_text("x = 2", encoding="utf-8")
fp2 = codebase_fingerprint(tmp_path)
assert fp1 != fp2
def test_extract_items_image_suffix(tmp_path: Path) -> None:
(tmp_path / "logo.png").write_bytes(b"\x89PNG\r\n")
items = extract_items(tmp_path)
assert items == []
def test_code_item_defaults() -> None:
item = CodeItem(
id="mod.fn",
file="mod.py",
type="function",
name="fn",
start_line=1,
end_line=5,
)
assert item.class_name == ""
assert item.depends_on == []
def test_codebase_fingerprint_stat_oserror_raises(tmp_path: Path) -> None:
"""Skip a file whose ``stat`` raises ``OSError`` (except branch).
``is_file()`` is forced True for the target so the loop reaches the
explicit ``path.stat()`` at fingerprint time; that stat then raises and
the ``except OSError`` handler drops the unreadable entry. Patching both
keeps this deterministic across Python versions (on some, ``is_file``
itself calls ``stat`` and would otherwise re-raise before line reached).
"""
(tmp_path / "source.py").write_text("x = 1", encoding="utf-8")
real_stat = Path.stat
real_is_file = Path.is_file
def failing_stat(self: Path, **kwargs: object) -> object:
"""Raise for the target file, delegate to the real stat otherwise."""
if str(self).endswith("source.py"):
msg = "simulated stat failure"
raise OSError(msg)
return real_stat(self, **kwargs)
def always_file(self: Path) -> bool:
"""Report the target as a regular file without calling stat."""
return str(self).endswith("source.py") or real_is_file(self)
with (
patch.object(Path, "stat", failing_stat),
patch.object(Path, "is_file", always_file),
):
result = codebase_fingerprint(tmp_path)
assert len(result) == 16

View File

@ -18,7 +18,6 @@ from python_pkg.code_tutor._challenge_support import (
_scan_test_file,
_show_test_panels,
)
from python_pkg.code_tutor._pytest_runner import _patch_and_test, _pytest_clean
from python_pkg.code_tutor.tests.conftest import _item
# ---------------------------------------------------------------------------
@ -190,154 +189,3 @@ def test_project_root_not_found(tmp_path: Path) -> None:
result = _project_root(isolated)
# When not found, returns start.resolve()
assert result == isolated.resolve()
# ---------------------------------------------------------------------------
# _pytest_clean
# ---------------------------------------------------------------------------
def test_pytest_clean_pass() -> None:
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = "1 passed"
mock_result.stderr = ""
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner.subprocess.run",
return_value=mock_result,
):
assert (
_pytest_clean(["test_mod.py::test_fn"], Path("/proj"), mock_console) is True
)
def test_pytest_clean_fail() -> None:
mock_result = MagicMock()
mock_result.returncode = 1
mock_result.stdout = ""
mock_result.stderr = "FAILED"
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner.subprocess.run",
return_value=mock_result,
):
assert (
_pytest_clean(["test_mod.py::test_fn"], Path("/proj"), mock_console)
is False
)
def test_pytest_clean_no_output() -> None:
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = ""
mock_result.stderr = ""
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner.subprocess.run",
return_value=mock_result,
):
_pytest_clean([], Path("/proj"), mock_console)
mock_console.print.assert_not_called()
# ---------------------------------------------------------------------------
# _patch_and_test
# ---------------------------------------------------------------------------
def test_patch_and_test_syntax_error(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
mock_console = MagicMock()
result = _patch_and_test(
_item(file="mod.py", start=1, end=2),
str(tmp_path),
"def fn(\n broken syntax",
[],
mock_console,
)
assert result is False
# Original file should be restored
assert (tmp_path / "mod.py").read_text(encoding="utf-8") == source
def test_patch_and_test_passes(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._pytest_runner._pytest_clean", return_value=True):
result = _patch_and_test(
_item(file="mod.py", start=1, end=2),
str(tmp_path),
"def fn():\n return 99",
[(test_file, ["test_fn"])],
mock_console,
)
assert result is True
# File restored
assert (tmp_path / "mod.py").read_text(encoding="utf-8") == source
def test_patch_and_test_fails(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner._pytest_clean", return_value=False
):
result = _patch_and_test(
_item(file="mod.py", start=1, end=2),
str(tmp_path),
"def fn():\n return 0",
[(test_file, ["test_fn"])],
mock_console,
)
assert result is False
assert (tmp_path / "mod.py").read_text(encoding="utf-8") == source
def test_scan_test_file_non_func_non_class_toplevel() -> None:
"""Skip a top-level node that is neither a function nor a class def.
A module-level ``import`` fails both ``isinstance`` checks, exercising
the branch that falls through the ``elif ClassDef`` back to the loop.
"""
source = "import os\ndef test_fn_uses_fn():\n fn()\n"
result = _scan_test_file(source, "fn")
assert result == ["test_fn_uses_fn"]
def test_show_test_panels_non_func_non_class_toplevel(tmp_path: Path) -> None:
"""Skip a top-level node that is neither a function nor a class def.
A module-level ``import`` yields an empty ``nodes`` list, so the
``elif ClassDef`` branch is not taken before the inner render loop.
"""
source = "import os\ndef test_fn():\n fn(1)\n"
test_file = tmp_path / "test_mod.py"
test_file.write_text(source, encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge_support.Syntax"):
_show_test_panels([(test_file, ["test_fn"])], mock_console)
assert mock_console.print.called
def test_show_test_panels_class_non_func_member(tmp_path: Path) -> None:
"""Skip a class-body member that is not a function definition.
The class-level ``attr = 1`` assignment fails the member ``isinstance``
check, exercising the branch that loops back to the next body member.
"""
source = "class TestFoo:\n attr = 1\n def test_fn(self):\n fn()\n"
test_file = tmp_path / "test_mod.py"
test_file.write_text(source, encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge_support.Syntax"):
_show_test_panels([(test_file, ["TestFoo::test_fn"])], mock_console)
assert mock_console.print.called

View File

@ -0,0 +1,211 @@
"""Tests for the two code_tutor challenge flows."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from python_pkg.code_tutor._challenge_flows import (
_existing_tests_flow,
_write_tests_first_flow,
)
from python_pkg.code_tutor.tests.conftest import _item
if TYPE_CHECKING:
from pathlib import Path
# ---------------------------------------------------------------------------
# _write_tests_first_flow
# ---------------------------------------------------------------------------
def test_write_tests_first_flow_user_declines(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "n",
)
assert result == "skipped"
def test_write_tests_first_flow_tests_none(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
return_value=None,
),
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
):
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "y",
)
assert result == "skipped"
def test_write_tests_first_flow_tests_fail_real(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
return_value="test code",
),
patch(
"python_pkg.code_tutor._challenge_flows._validate_tests_against_real",
return_value=False,
),
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
):
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "y",
)
assert result == "skipped"
def test_write_tests_first_flow_success(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
return_value="test code",
),
patch(
"python_pkg.code_tutor._challenge_flows._validate_tests_against_real",
return_value=True,
),
patch(
"python_pkg.code_tutor._challenge_flows._run_user_impl",
return_value="passed",
),
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
):
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "y",
)
assert result == "passed"
# ---------------------------------------------------------------------------
# _existing_tests_flow
# ---------------------------------------------------------------------------
def test_existing_tests_flow_user_declines(tmp_path: Path) -> None:
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
result = _existing_tests_flow(
_item(),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: "n",
)
assert result == "skipped"
def test_existing_tests_flow_user_skips_impl(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge_support.Syntax"):
result = _existing_tests_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: (
"y"
if "challenge" in str(_) or _ == "Take the challenge? [y/N] "
else "skip"
),
)
assert result == "skipped"
def test_existing_tests_flow_passes(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
inputs = iter(["y", "def fn():", " return 1", "END"])
with (
patch("python_pkg.code_tutor._challenge_support.Syntax"),
patch(
"python_pkg.code_tutor._challenge_flows._patch_and_test", return_value=True
),
):
result = _existing_tests_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: next(inputs),
)
assert result == "passed"
def test_existing_tests_flow_fails(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
inputs = iter(["y", "def fn():", " return 0", "END"])
with (
patch("python_pkg.code_tutor._challenge_support.Syntax"),
patch(
"python_pkg.code_tutor._challenge_flows._patch_and_test", return_value=False
),
):
result = _existing_tests_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: next(inputs),
)
assert result == "failed"

View File

@ -8,19 +8,10 @@ Covers the LLM verdict/signature helpers in ``_challenge_support``
from __future__ import annotations
from pathlib import Path
from unittest.mock import MagicMock, patch
from python_pkg.code_tutor._challenge import (
_collect_and_rate_tests,
_validate_tests_against_real,
)
from python_pkg.code_tutor._challenge_support import (
_extract_signature_block,
_import_hint,
)
from python_pkg.code_tutor._verdict import _parse_verdict, _stream_verdict
from python_pkg.code_tutor.tests.conftest import _item, _make_live_mock
from python_pkg.code_tutor.tests.conftest import _make_live_mock
# ---------------------------------------------------------------------------
# _stream_verdict
@ -96,212 +87,3 @@ def test_challenge_parse_verdict_json_error() -> None:
def test_challenge_parse_verdict_invalid() -> None:
verdict, _gap = _parse_verdict('{"verdict": "UNKNOWN", "gap": "x"}')
assert verdict == "FAIL"
# ---------------------------------------------------------------------------
# _extract_signature_block
# ---------------------------------------------------------------------------
def test_extract_signature_block_with_docstring(tmp_path: Path) -> None:
source = 'def fn(x):\n """Do thing."""\n return x\n'
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py"), str(tmp_path))
assert "def fn" in result
assert '"""Do thing."""' in result
def test_extract_signature_block_without_docstring(tmp_path: Path) -> None:
source = "def fn(x):\n return x\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py"), str(tmp_path))
assert "def fn" in result
assert "return" not in result
def test_extract_signature_block_oserror(tmp_path: Path) -> None:
result = _extract_signature_block(_item(file="missing.py"), str(tmp_path))
assert "def fn(...):" in result
def test_extract_signature_block_no_match(tmp_path: Path) -> None:
source = "def other(): pass\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py", name="fn"), str(tmp_path))
assert "def fn(...):" in result
def test_extract_signature_block_syntax_error(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def (broken):\n", encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py"), str(tmp_path))
assert "def fn(...):" in result
# ---------------------------------------------------------------------------
# Tests for _import_hint
# ---------------------------------------------------------------------------
def test_import_hint_relative_to_project(tmp_path: Path) -> None:
(tmp_path / "src").mkdir()
result = _import_hint(
_item(file="src/mod.py", name="fn"),
str(tmp_path),
tmp_path,
)
assert result == "from src.mod import fn"
def test_import_hint_value_error(tmp_path: Path) -> None:
# project_root is different from codebase_path
other_root = tmp_path / "other"
other_root.mkdir()
result = _import_hint(
_item(file="src/mod.py", name="fn"),
str(tmp_path),
other_root,
)
assert result == "from mod import fn"
# ---------------------------------------------------------------------------
# _validate_tests_against_real
# ---------------------------------------------------------------------------
def test_validate_tests_syntax_error() -> None:
mock_console = MagicMock()
result = _validate_tests_against_real(
"def (broken):", "import fn", Path("/proj"), mock_console
)
assert result is False
def test_validate_tests_passes() -> None:
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge._pytest_clean", return_value=True):
result = _validate_tests_against_real(
"def test_fn():\n assert True\n",
"# import",
Path("/proj"),
mock_console,
)
assert result is True
def test_validate_tests_fails() -> None:
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge._pytest_clean", return_value=False):
result = _validate_tests_against_real(
"def test_fn():\n assert False\n",
"# import",
Path("/proj"),
mock_console,
)
assert result is False
# ---------------------------------------------------------------------------
# _collect_and_rate_tests
# ---------------------------------------------------------------------------
def test_collect_and_rate_tests_skip() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: "skip",
)
assert result is None
def test_collect_and_rate_tests_pass_first() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
on_token('{"verdict": "PASS", "gap": ""}')
return ""
mock_backend.stream.side_effect = fake_stream
lines_iter = iter(["test code line", "END"])
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: next(lines_iter),
)
assert result == "test code line"
def test_collect_and_rate_tests_fail_twice() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
mock_backend.stream.return_value = '{"verdict": "FAIL", "gap": "bad"}'
attempt_inputs = [
# attempt 1: provide code, then END
"test code",
"END",
# attempt 2: provide code, then END
"test code again",
"END",
]
inputs_iter = iter(attempt_inputs)
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: next(inputs_iter),
)
assert result is None
def test_collect_and_rate_tests_fail_then_pass() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
call_count = [0]
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
call_count[0] += 1
verdict = (
'{"verdict": "FAIL", "gap": "not enough"}'
if call_count[0] == 1
else '{"verdict": "PASS", "gap": ""}'
)
on_token(verdict)
return ""
mock_backend.stream.side_effect = fake_stream
inputs = iter(["bad test", "END", "good test", "END"])
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: next(inputs),
)
assert result == "good test"

View File

@ -11,11 +11,6 @@ from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from python_pkg.code_tutor._challenge import _run_user_impl
from python_pkg.code_tutor._challenge_flows import (
_existing_tests_flow,
_write_tests_first_flow,
run_coding_challenge,
)
from python_pkg.code_tutor.tests.conftest import _item, _make_live_mock
if TYPE_CHECKING:
@ -121,258 +116,3 @@ def test_run_user_impl_failed(tmp_path: Path) -> None:
)
assert result == "failed"
assert (tmp_path / "mod.py").read_text(encoding="utf-8") == source
# ---------------------------------------------------------------------------
# _write_tests_first_flow
# ---------------------------------------------------------------------------
def test_write_tests_first_flow_user_declines(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "n",
)
assert result == "skipped"
def test_write_tests_first_flow_tests_none(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
return_value=None,
),
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
):
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "y",
)
assert result == "skipped"
def test_write_tests_first_flow_tests_fail_real(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
return_value="test code",
),
patch(
"python_pkg.code_tutor._challenge_flows._validate_tests_against_real",
return_value=False,
),
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
):
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "y",
)
assert result == "skipped"
def test_write_tests_first_flow_success(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_backend = MagicMock()
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
return_value="test code",
),
patch(
"python_pkg.code_tutor._challenge_flows._validate_tests_against_real",
return_value=True,
),
patch(
"python_pkg.code_tutor._challenge_flows._run_user_impl",
return_value="passed",
),
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
):
result = _write_tests_first_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
lambda _: "y",
)
assert result == "passed"
# ---------------------------------------------------------------------------
# _existing_tests_flow
# ---------------------------------------------------------------------------
def test_existing_tests_flow_user_declines(tmp_path: Path) -> None:
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
result = _existing_tests_flow(
_item(),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: "n",
)
assert result == "skipped"
def test_existing_tests_flow_user_skips_impl(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge_support.Syntax"):
result = _existing_tests_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: (
"y"
if "challenge" in str(_) or _ == "Take the challenge? [y/N] "
else "skip"
),
)
assert result == "skipped"
def test_existing_tests_flow_passes(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
inputs = iter(["y", "def fn():", " return 1", "END"])
with (
patch("python_pkg.code_tutor._challenge_support.Syntax"),
patch(
"python_pkg.code_tutor._challenge_flows._patch_and_test", return_value=True
),
):
result = _existing_tests_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: next(inputs),
)
assert result == "passed"
def test_existing_tests_flow_fails(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
inputs = iter(["y", "def fn():", " return 0", "END"])
with (
patch("python_pkg.code_tutor._challenge_support.Syntax"),
patch(
"python_pkg.code_tutor._challenge_flows._patch_and_test", return_value=False
),
):
result = _existing_tests_flow(
_item(file="mod.py"),
str(tmp_path),
"explanation",
[(test_file, ["test_fn"])],
mock_console,
lambda _: next(inputs),
)
assert result == "failed"
# ---------------------------------------------------------------------------
# run_coding_challenge
# ---------------------------------------------------------------------------
def test_run_coding_challenge_non_python() -> None:
mock_console = MagicMock()
mock_backend = MagicMock()
result = run_coding_challenge(
_item(file="main.go"),
"/codebase",
"explanation",
mock_backend,
mock_console,
)
assert result == "skipped"
def test_run_coding_challenge_with_existing_tests(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
mock_backend = MagicMock()
with patch(
"python_pkg.code_tutor._challenge_flows._existing_tests_flow",
return_value="passed",
):
result = run_coding_challenge(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
)
assert result == "passed"
def test_run_coding_challenge_no_tests(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_console = MagicMock()
mock_backend = MagicMock()
with patch(
"python_pkg.code_tutor._challenge_flows._write_tests_first_flow",
return_value="skipped",
):
result = run_coding_challenge(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
)
assert result == "skipped"

View File

@ -0,0 +1,100 @@
"""Tests for python_pkg.code_tutor._claude_backend."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from python_pkg.code_tutor._claude_backend import ClaudeBackend
# ---------------------------------------------------------------------------
# ClaudeBackend.complete
# ---------------------------------------------------------------------------
def test_claude_complete_with_text_block() -> None:
mock_block = MagicMock()
mock_block.text = "answer"
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client = MagicMock()
mock_client.messages.create.return_value = mock_message
with patch(
"python_pkg.code_tutor._claude_backend.anthropic.Anthropic",
return_value=mock_client,
):
backend = ClaudeBackend()
result = backend.complete("sys", "user")
assert result == "answer"
def test_claude_complete_no_text_attr() -> None:
mock_block = MagicMock(spec=[]) # no .text attribute
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client = MagicMock()
mock_client.messages.create.return_value = mock_message
with patch(
"python_pkg.code_tutor._claude_backend.anthropic.Anthropic",
return_value=mock_client,
):
backend = ClaudeBackend()
result = backend.complete("sys", "user")
assert result == ""
# ---------------------------------------------------------------------------
# ClaudeBackend.stream
# ---------------------------------------------------------------------------
def test_claude_stream_success() -> None:
mock_stream_ctx = MagicMock()
mock_stream_ctx.__enter__ = MagicMock(return_value=mock_stream_ctx)
mock_stream_ctx.__exit__ = MagicMock(return_value=False)
mock_stream_ctx.text_stream = iter(["hello", " world"])
mock_client = MagicMock()
mock_client.messages.stream.return_value = mock_stream_ctx
tokens: list[str] = []
with patch(
"python_pkg.code_tutor._claude_backend.anthropic.Anthropic",
return_value=mock_client,
):
backend = ClaudeBackend()
result = backend.stream("sys", "user", tokens.append)
assert result == "hello world"
assert tokens == ["hello", " world"]
def test_claude_stream_api_error_fallback() -> None:
import anthropic as anthropic_lib
mock_client = MagicMock()
mock_client.messages.stream.side_effect = anthropic_lib.APIError(
message="fail",
request=MagicMock(),
body=None,
)
mock_block = MagicMock()
mock_block.text = "fallback"
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client.messages.create.return_value = mock_message
tokens: list[str] = []
with patch(
"python_pkg.code_tutor._claude_backend.anthropic.Anthropic",
return_value=mock_client,
):
backend = ClaudeBackend()
result = backend.stream("sys", "user", tokens.append)
assert result == "fallback"

View File

@ -2,19 +2,15 @@
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import requests
from typer.testing import CliRunner
from python_pkg.code_tutor.cli import (
_check_plan_file,
from python_pkg.code_tutor._cli_checks import (
_ensure_fresh_plan,
_ensure_ollama_running,
_find_codebase_for_file,
app,
)
if TYPE_CHECKING:
@ -58,22 +54,38 @@ def _make_plan(codebase: Path, fingerprint: str = "abc") -> dict:
def test_ensure_ollama_running_already_up() -> None:
mock_console = MagicMock()
mock_resp = MagicMock()
with patch("python_pkg.code_tutor.cli.requests.get", return_value=mock_resp):
with patch(
"python_pkg.code_tutor._cli_checks.requests.get", return_value=mock_resp
):
result = _ensure_ollama_running(mock_console)
assert result is True
def test_ensure_ollama_running_no_systemctl() -> None:
"""A machine without systemctl should say so, not raise."""
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor._cli_checks.requests.get",
side_effect=requests.exceptions.ConnectionError(),
),
patch("python_pkg.code_tutor._cli_checks.shutil.which", return_value=None),
):
result = _ensure_ollama_running(mock_console)
assert result is False
def test_ensure_ollama_running_systemctl_fails() -> None:
import subprocess
mock_console = MagicMock()
with (
patch(
"python_pkg.code_tutor.cli.requests.get",
"python_pkg.code_tutor._cli_checks.requests.get",
side_effect=requests.exceptions.ConnectionError(),
),
patch(
"python_pkg.code_tutor.cli.subprocess.run",
"python_pkg.code_tutor._cli_checks.subprocess.run",
side_effect=subprocess.CalledProcessError(1, "systemctl", stderr=b"failed"),
),
):
@ -93,9 +105,12 @@ def test_ensure_ollama_running_starts_then_up() -> None:
return MagicMock()
with (
patch("python_pkg.code_tutor.cli.requests.get", side_effect=fake_get),
patch("python_pkg.code_tutor.cli.subprocess.run", return_value=mock_subprocess),
patch("python_pkg.code_tutor.cli.time.sleep"),
patch("python_pkg.code_tutor._cli_checks.requests.get", side_effect=fake_get),
patch(
"python_pkg.code_tutor._cli_checks.subprocess.run",
return_value=mock_subprocess,
),
patch("python_pkg.code_tutor._cli_checks.time.sleep"),
):
result = _ensure_ollama_running(mock_console)
assert result is True
@ -113,13 +128,16 @@ def test_ensure_ollama_running_times_out() -> None:
raise requests.exceptions.ConnectionError
with (
patch("python_pkg.code_tutor.cli.requests.get", side_effect=fake_get),
patch("python_pkg.code_tutor.cli.subprocess.run", return_value=mock_subprocess),
patch("python_pkg.code_tutor._cli_checks.requests.get", side_effect=fake_get),
patch(
"python_pkg.code_tutor.cli.time.monotonic",
"python_pkg.code_tutor._cli_checks.subprocess.run",
return_value=mock_subprocess,
),
patch(
"python_pkg.code_tutor._cli_checks.time.monotonic",
side_effect=time_values,
),
patch("python_pkg.code_tutor.cli.time.sleep"),
patch("python_pkg.code_tutor._cli_checks.time.sleep"),
):
result = _ensure_ollama_running(mock_console)
assert result is False
@ -146,7 +164,9 @@ def test_ensure_fresh_plan_no_fingerprint(tmp_path: Path) -> None:
def test_ensure_fresh_plan_up_to_date(tmp_path: Path) -> None:
plan = _make_plan(tmp_path, fingerprint="same")
mock_console = MagicMock()
with patch("python_pkg.code_tutor.cli.codebase_fingerprint", return_value="same"):
with patch(
"python_pkg.code_tutor._cli_checks.codebase_fingerprint", return_value="same"
):
result = _ensure_fresh_plan(tmp_path, plan, mock_console)
assert result is plan
@ -155,8 +175,10 @@ def test_ensure_fresh_plan_stale_no_items(tmp_path: Path) -> None:
plan = _make_plan(tmp_path, fingerprint="old")
mock_console = MagicMock()
with (
patch("python_pkg.code_tutor.cli.codebase_fingerprint", return_value="new"),
patch("python_pkg.code_tutor.cli.extract_items", return_value=[]),
patch(
"python_pkg.code_tutor._cli_checks.codebase_fingerprint", return_value="new"
),
patch("python_pkg.code_tutor._cli_checks.extract_items", return_value=[]),
):
result = _ensure_fresh_plan(tmp_path, plan, mock_console)
assert result is plan
@ -169,302 +191,14 @@ def test_ensure_fresh_plan_stale_rebuilds(tmp_path: Path) -> None:
mock_items = [MagicMock()]
with (
patch("python_pkg.code_tutor.cli.codebase_fingerprint", return_value="new"),
patch("python_pkg.code_tutor.cli.extract_items", return_value=mock_items),
patch("python_pkg.code_tutor.cli.build_plan", return_value=new_plan),
patch("python_pkg.code_tutor.cli.save_plan"),
patch(
"python_pkg.code_tutor._cli_checks.codebase_fingerprint", return_value="new"
),
patch(
"python_pkg.code_tutor._cli_checks.extract_items", return_value=mock_items
),
patch("python_pkg.code_tutor._cli_checks.build_plan", return_value=new_plan),
patch("python_pkg.code_tutor._cli_checks.save_plan"),
):
result = _ensure_fresh_plan(tmp_path, plan, mock_console)
assert result["source_fingerprint"] == "new"
# ---------------------------------------------------------------------------
# analyze command
# ---------------------------------------------------------------------------
def test_analyze_not_dir(tmp_path: Path) -> None:
result = runner.invoke(app, ["analyze", str(tmp_path / "no_such_dir")])
assert result.exit_code == 1
def test_analyze_no_items(tmp_path: Path) -> None:
with patch("python_pkg.code_tutor.cli.extract_items", return_value=[]):
result = runner.invoke(app, ["analyze", str(tmp_path)])
assert result.exit_code == 0
def test_analyze_with_items(tmp_path: Path) -> None:
mock_items = [MagicMock()]
mock_plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.extract_items", return_value=mock_items),
patch("python_pkg.code_tutor.cli.build_plan", return_value=mock_plan),
patch("python_pkg.code_tutor.cli.save_plan"),
patch("python_pkg.code_tutor.cli.config_dir", return_value=tmp_path),
):
result = runner.invoke(app, ["analyze", str(tmp_path)])
assert result.exit_code == 0
# ---------------------------------------------------------------------------
# study command
# ---------------------------------------------------------------------------
def test_study_not_dir(tmp_path: Path) -> None:
result = runner.invoke(app, ["study", str(tmp_path / "no_such_dir")])
assert result.exit_code == 1
def test_study_no_plan(tmp_path: Path) -> None:
with patch("python_pkg.code_tutor.cli.load_plan", return_value=None):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 1
def test_study_ollama_fails(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=False),
):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 1
def test_study_connection_error(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=True),
patch(
"python_pkg.code_tutor.cli.run_session",
side_effect=requests.exceptions.ConnectionError(),
),
):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 1
def test_study_success(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=True),
patch("python_pkg.code_tutor.cli.run_session"),
):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 0
# ---------------------------------------------------------------------------
# status command
# ---------------------------------------------------------------------------
def test_status_no_plan(tmp_path: Path) -> None:
with patch("python_pkg.code_tutor.cli.load_plan", return_value=None):
result = runner.invoke(app, ["status", str(tmp_path)])
assert result.exit_code == 1
def test_status_with_plan(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
progress = {"learned": [], "struggled": [], "skipped": [], "last_session": ""}
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli.load_progress", return_value=progress),
):
result = runner.invoke(app, ["status", str(tmp_path)])
assert result.exit_code == 0
# ---------------------------------------------------------------------------
# drill command
# ---------------------------------------------------------------------------
def test_drill_no_plan_for_file(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
with patch("python_pkg.code_tutor.cli._find_codebase_for_file", return_value=None):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 1
def test_drill_plan_disappears(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=None),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 1
def test_drill_no_items_in_plan(tmp_path: Path) -> None:
f = tmp_path / "other.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan = _make_plan(tmp_path) # plan has mod.py items, not other.py
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 0
def test_drill_ollama_fails(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan = _make_plan(tmp_path)
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=False),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 1
def test_drill_runs_lesson(tmp_path: Path) -> None:
from python_pkg.code_tutor._progress import LessonRecord
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan = _make_plan(tmp_path)
record = LessonRecord(
timestamp="t",
item_id="mod.fn",
file="mod.py",
lines="1-3",
snippet="code",
outcome="learned",
answers={},
improvement="",
verdict="PASS",
attempt=1,
)
mock_verifier = MagicMock()
mock_verifier.run_lesson.return_value = record
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=True),
patch("python_pkg.code_tutor.cli.Verifier", return_value=mock_verifier),
patch("python_pkg.code_tutor.cli.append_session_record"),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 0
mock_verifier.run_lesson.assert_called_once()
# ---------------------------------------------------------------------------
# _find_codebase_for_file
# ---------------------------------------------------------------------------
def test_find_codebase_for_file_no_config_dir(tmp_path: Path) -> None:
with patch(
"python_pkg.code_tutor.cli.Path.home",
return_value=tmp_path,
):
result = _find_codebase_for_file(tmp_path / "mod.py")
assert result is None
def test_find_codebase_for_file_found(tmp_path: Path) -> None:
home = tmp_path / "home"
config_root = home / ".config" / "code_tutor" / "hash"
config_root.mkdir(parents=True)
codebase = tmp_path / "codebase"
codebase.mkdir()
f = codebase / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan_data = {
"codebase_path": str(codebase),
"sessions": [],
}
(config_root / "plan.json").write_text(json.dumps(plan_data), encoding="utf-8")
with patch("python_pkg.code_tutor.cli.Path.home", return_value=home):
result = _find_codebase_for_file(f)
assert result == codebase
def test_find_codebase_for_file_not_found(tmp_path: Path) -> None:
home = tmp_path / "home"
config_root = home / ".config" / "code_tutor" / "hash"
config_root.mkdir(parents=True)
other_codebase = tmp_path / "other"
other_codebase.mkdir()
plan_data = {"codebase_path": str(other_codebase), "sessions": []}
(config_root / "plan.json").write_text(json.dumps(plan_data), encoding="utf-8")
target = tmp_path / "unrelated" / "mod.py"
with patch("python_pkg.code_tutor.cli.Path.home", return_value=home):
result = _find_codebase_for_file(target)
assert result is None
# ---------------------------------------------------------------------------
# _check_plan_file
# ---------------------------------------------------------------------------
def test_check_plan_file_found(tmp_path: Path) -> None:
codebase = tmp_path / "cb"
codebase.mkdir()
f = codebase / "mod.py"
plan_file = tmp_path / "plan.json"
plan_file.write_text(json.dumps({"codebase_path": str(codebase)}), encoding="utf-8")
result = _check_plan_file(plan_file, f)
assert result == codebase
def test_check_plan_file_value_error(tmp_path: Path) -> None:
codebase = tmp_path / "cb"
codebase.mkdir()
other_file = tmp_path / "other" / "mod.py"
plan_file = tmp_path / "plan.json"
plan_file.write_text(json.dumps({"codebase_path": str(codebase)}), encoding="utf-8")
# other_file is not relative to codebase → ValueError
result = _check_plan_file(plan_file, other_file)
assert result is None
def test_check_plan_file_oserror(tmp_path: Path) -> None:
plan_file = tmp_path / "missing_plan.json"
result = _check_plan_file(plan_file, tmp_path / "mod.py")
assert result is None
def test_check_plan_file_json_error(tmp_path: Path) -> None:
plan_file = tmp_path / "plan.json"
plan_file.write_text("not valid json {{{", encoding="utf-8")
result = _check_plan_file(plan_file, tmp_path / "mod.py")
assert result is None

View File

@ -0,0 +1,126 @@
"""Tests for the code_tutor CLI commands themselves."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import requests
from typer.testing import CliRunner
from python_pkg.code_tutor.cli import app
if TYPE_CHECKING:
from pathlib import Path
runner = CliRunner()
def _make_plan(codebase: Path, fingerprint: str = "abc") -> dict:
return {
"codebase_path": str(codebase),
"created_at": "2026-01-01T00:00:00+00:00",
"total_items": 2,
"source_fingerprint": fingerprint,
"sessions": [
{
"id": 1,
"title": "mod",
"items": [
{
"id": "mod.fn",
"file": "mod.py",
"type": "function",
"name": "fn",
"start_line": 1,
"end_line": 3,
"class_name": "",
"depends_on": [],
}
],
}
],
}
# ---------------------------------------------------------------------------
# analyze command
# ---------------------------------------------------------------------------
def test_analyze_not_dir(tmp_path: Path) -> None:
result = runner.invoke(app, ["analyze", str(tmp_path / "no_such_dir")])
assert result.exit_code == 1
def test_analyze_no_items(tmp_path: Path) -> None:
with patch("python_pkg.code_tutor.cli.extract_items", return_value=[]):
result = runner.invoke(app, ["analyze", str(tmp_path)])
assert result.exit_code == 0
def test_analyze_with_items(tmp_path: Path) -> None:
mock_items = [MagicMock()]
mock_plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.extract_items", return_value=mock_items),
patch("python_pkg.code_tutor.cli.build_plan", return_value=mock_plan),
patch("python_pkg.code_tutor.cli.save_plan"),
patch("python_pkg.code_tutor.cli.config_dir", return_value=tmp_path),
):
result = runner.invoke(app, ["analyze", str(tmp_path)])
assert result.exit_code == 0
# ---------------------------------------------------------------------------
# study command
# ---------------------------------------------------------------------------
def test_study_not_dir(tmp_path: Path) -> None:
result = runner.invoke(app, ["study", str(tmp_path / "no_such_dir")])
assert result.exit_code == 1
def test_study_no_plan(tmp_path: Path) -> None:
with patch("python_pkg.code_tutor.cli.load_plan", return_value=None):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 1
def test_study_ollama_fails(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=False),
):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 1
def test_study_connection_error(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=True),
patch(
"python_pkg.code_tutor.cli.run_session",
side_effect=requests.exceptions.ConnectionError(),
),
):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 1
def test_study_success(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=True),
patch("python_pkg.code_tutor.cli.run_session"),
):
result = runner.invoke(app, ["study", str(tmp_path)])
assert result.exit_code == 0

View File

@ -0,0 +1,138 @@
"""Tests for locating a codebase from a single file."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
from typer.testing import CliRunner
from python_pkg.code_tutor._cli_checks import (
_check_plan_file,
_find_codebase_for_file,
)
if TYPE_CHECKING:
from pathlib import Path
runner = CliRunner()
def _make_plan(codebase: Path, fingerprint: str = "abc") -> dict:
return {
"codebase_path": str(codebase),
"created_at": "2026-01-01T00:00:00+00:00",
"total_items": 2,
"source_fingerprint": fingerprint,
"sessions": [
{
"id": 1,
"title": "mod",
"items": [
{
"id": "mod.fn",
"file": "mod.py",
"type": "function",
"name": "fn",
"start_line": 1,
"end_line": 3,
"class_name": "",
"depends_on": [],
}
],
}
],
}
# ---------------------------------------------------------------------------
# _find_codebase_for_file
# ---------------------------------------------------------------------------
def test_find_codebase_for_file_no_config_dir(tmp_path: Path) -> None:
with patch(
"python_pkg.code_tutor.cli.Path.home",
return_value=tmp_path,
):
result = _find_codebase_for_file(tmp_path / "mod.py")
assert result is None
def test_find_codebase_for_file_found(tmp_path: Path) -> None:
home = tmp_path / "home"
config_root = home / ".config" / "code_tutor" / "hash"
config_root.mkdir(parents=True)
codebase = tmp_path / "codebase"
codebase.mkdir()
f = codebase / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan_data = {
"codebase_path": str(codebase),
"sessions": [],
}
(config_root / "plan.json").write_text(json.dumps(plan_data), encoding="utf-8")
with patch("python_pkg.code_tutor.cli.Path.home", return_value=home):
result = _find_codebase_for_file(f)
assert result == codebase
def test_find_codebase_for_file_not_found(tmp_path: Path) -> None:
home = tmp_path / "home"
config_root = home / ".config" / "code_tutor" / "hash"
config_root.mkdir(parents=True)
other_codebase = tmp_path / "other"
other_codebase.mkdir()
plan_data = {"codebase_path": str(other_codebase), "sessions": []}
(config_root / "plan.json").write_text(json.dumps(plan_data), encoding="utf-8")
target = tmp_path / "unrelated" / "mod.py"
with patch("python_pkg.code_tutor.cli.Path.home", return_value=home):
result = _find_codebase_for_file(target)
assert result is None
# ---------------------------------------------------------------------------
# _check_plan_file
# ---------------------------------------------------------------------------
def test_check_plan_file_found(tmp_path: Path) -> None:
codebase = tmp_path / "cb"
codebase.mkdir()
f = codebase / "mod.py"
plan_file = tmp_path / "plan.json"
plan_file.write_text(json.dumps({"codebase_path": str(codebase)}), encoding="utf-8")
result = _check_plan_file(plan_file, f)
assert result == codebase
def test_check_plan_file_value_error(tmp_path: Path) -> None:
codebase = tmp_path / "cb"
codebase.mkdir()
other_file = tmp_path / "other" / "mod.py"
plan_file = tmp_path / "plan.json"
plan_file.write_text(json.dumps({"codebase_path": str(codebase)}), encoding="utf-8")
# other_file is not relative to codebase → ValueError
result = _check_plan_file(plan_file, other_file)
assert result is None
def test_check_plan_file_oserror(tmp_path: Path) -> None:
plan_file = tmp_path / "missing_plan.json"
result = _check_plan_file(plan_file, tmp_path / "mod.py")
assert result is None
def test_check_plan_file_json_error(tmp_path: Path) -> None:
plan_file = tmp_path / "plan.json"
plan_file.write_text("not valid json {{{", encoding="utf-8")
result = _check_plan_file(plan_file, tmp_path / "mod.py")
assert result is None

View File

@ -0,0 +1,159 @@
"""Tests for the code_tutor status and drill commands."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from typer.testing import CliRunner
from python_pkg.code_tutor.cli import app
if TYPE_CHECKING:
from pathlib import Path
runner = CliRunner()
def _make_plan(codebase: Path, fingerprint: str = "abc") -> dict:
return {
"codebase_path": str(codebase),
"created_at": "2026-01-01T00:00:00+00:00",
"total_items": 2,
"source_fingerprint": fingerprint,
"sessions": [
{
"id": 1,
"title": "mod",
"items": [
{
"id": "mod.fn",
"file": "mod.py",
"type": "function",
"name": "fn",
"start_line": 1,
"end_line": 3,
"class_name": "",
"depends_on": [],
}
],
}
],
}
# ---------------------------------------------------------------------------
# status command
# ---------------------------------------------------------------------------
def test_status_no_plan(tmp_path: Path) -> None:
with patch("python_pkg.code_tutor.cli.load_plan", return_value=None):
result = runner.invoke(app, ["status", str(tmp_path)])
assert result.exit_code == 1
def test_status_with_plan(tmp_path: Path) -> None:
plan = _make_plan(tmp_path)
progress = {"learned": [], "struggled": [], "skipped": [], "last_session": ""}
with (
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli.load_progress", return_value=progress),
):
result = runner.invoke(app, ["status", str(tmp_path)])
assert result.exit_code == 0
# ---------------------------------------------------------------------------
# drill command
# ---------------------------------------------------------------------------
def test_drill_no_plan_for_file(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
with patch("python_pkg.code_tutor.cli._find_codebase_for_file", return_value=None):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 1
def test_drill_plan_disappears(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=None),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 1
def test_drill_no_items_in_plan(tmp_path: Path) -> None:
f = tmp_path / "other.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan = _make_plan(tmp_path) # plan has mod.py items, not other.py
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 0
def test_drill_ollama_fails(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan = _make_plan(tmp_path)
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=False),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 1
def test_drill_runs_lesson(tmp_path: Path) -> None:
from python_pkg.code_tutor._progress import LessonRecord
f = tmp_path / "mod.py"
f.write_text("def fn(): pass\n", encoding="utf-8")
plan = _make_plan(tmp_path)
record = LessonRecord(
timestamp="t",
item_id="mod.fn",
file="mod.py",
lines="1-3",
snippet="code",
outcome="learned",
answers={},
improvement="",
verdict="PASS",
attempt=1,
)
mock_verifier = MagicMock()
mock_verifier.run_lesson.return_value = record
with (
patch(
"python_pkg.code_tutor.cli._find_codebase_for_file", return_value=tmp_path
),
patch("python_pkg.code_tutor.cli.load_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_fresh_plan", return_value=plan),
patch("python_pkg.code_tutor.cli._ensure_ollama_running", return_value=True),
patch("python_pkg.code_tutor.cli.Verifier", return_value=mock_verifier),
patch("python_pkg.code_tutor.cli.append_session_record"),
):
result = runner.invoke(app, ["drill", str(f)])
assert result.exit_code == 0
mock_verifier.run_lesson.assert_called_once()

View File

@ -0,0 +1,246 @@
"""Tests for python_pkg.code_tutor._deps."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import patch
from python_pkg.code_tutor._analyzer import (
CodeItem,
extract_items,
)
from python_pkg.code_tutor._deps import (
_build_dotted_map,
_match_deps,
codebase_fingerprint,
get_file_imports,
get_python_files,
)
# ---------------------------------------------------------------------------
# get_python_files
# ---------------------------------------------------------------------------
def test_get_python_files(tmp_path: Path) -> None:
(tmp_path / "a.py").write_text("x = 1", encoding="utf-8")
(tmp_path / "b.py").write_text("y = 2", encoding="utf-8")
skip_dir = tmp_path / ".venv"
skip_dir.mkdir()
(skip_dir / "c.py").write_text("z = 3", encoding="utf-8")
files = get_python_files(tmp_path)
names = {f.name for f in files}
assert "a.py" in names
assert "b.py" in names
assert "c.py" not in names
# ---------------------------------------------------------------------------
# _build_dotted_map
# ---------------------------------------------------------------------------
def test_build_dotted_map_normal(tmp_path: Path) -> None:
f = tmp_path / "pkg" / "mod.py"
f.parent.mkdir()
f.write_text("x = 1", encoding="utf-8")
result = _build_dotted_map(tmp_path, [f])
assert result[f] == "pkg.mod"
def test_build_dotted_map_value_error(tmp_path: Path) -> None:
other = tmp_path.parent / "other.py"
result = _build_dotted_map(tmp_path, [other])
assert other not in result
# ---------------------------------------------------------------------------
# _match_deps
# ---------------------------------------------------------------------------
def test_match_deps_exact(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
dotted_map = {f: "mod"}
path = tmp_path / "main.py"
result = _match_deps({"mod"}, dotted_map, path)
assert f in result
def test_match_deps_prefix(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
dotted_map = {f: "mod"}
path = tmp_path / "main.py"
result = _match_deps({"pkg.mod"}, dotted_map, path)
assert f in result
def test_match_deps_suffix(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
dotted_map = {f: "pkg.mod"}
path = tmp_path / "main.py"
result = _match_deps({"mod"}, dotted_map, path)
assert f in result
def test_match_deps_excludes_self(tmp_path: Path) -> None:
path = tmp_path / "mod.py"
dotted_map = {path: "mod"}
result = _match_deps({"mod"}, dotted_map, path)
assert path not in result
def test_match_deps_no_match(tmp_path: Path) -> None:
f = tmp_path / "other.py"
dotted_map = {f: "other"}
path = tmp_path / "main.py"
result = _match_deps({"unrelated"}, dotted_map, path)
assert f not in result
# ---------------------------------------------------------------------------
# Tests for get_file_imports
# ---------------------------------------------------------------------------
def test_get_file_imports_import(tmp_path: Path) -> None:
f = tmp_path / "main.py"
dep = tmp_path / "utils.py"
f.write_text("import utils\n", encoding="utf-8")
dep.write_text("x = 1", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f, dep])
assert dep in result
def test_get_file_imports_from_import(tmp_path: Path) -> None:
f = tmp_path / "main.py"
dep = tmp_path / "utils.py"
f.write_text("from utils import helper\n", encoding="utf-8")
dep.write_text("def helper(): pass\n", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f, dep])
assert dep in result
def test_get_file_imports_from_import_none_module(tmp_path: Path) -> None:
# Relative import: node.module is None
f = tmp_path / "main.py"
f.write_text("from . import helper\n", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f])
assert result == set()
def test_get_file_imports_syntax_error(tmp_path: Path) -> None:
f = tmp_path / "bad.py"
f.write_text("def (broken):\n", encoding="utf-8")
result = get_file_imports(f, tmp_path, [f])
assert result == set()
# ---------------------------------------------------------------------------
# codebase_fingerprint
# ---------------------------------------------------------------------------
def test_codebase_fingerprint_basic(tmp_path: Path) -> None:
(tmp_path / "a.py").write_text("x = 1", encoding="utf-8")
result = codebase_fingerprint(tmp_path)
assert len(result) == 16
assert result.isalnum()
def test_codebase_fingerprint_skips_dir(tmp_path: Path) -> None:
sub = tmp_path / "sub"
sub.mkdir()
result = codebase_fingerprint(tmp_path)
assert len(result) == 16
def test_codebase_fingerprint_skips_should_skip(tmp_path: Path) -> None:
venv = tmp_path / ".venv"
venv.mkdir()
(venv / "lib.py").write_text("x = 1", encoding="utf-8")
result_without = codebase_fingerprint(tmp_path)
(tmp_path / "real.py").write_text("y = 2", encoding="utf-8")
result_with = codebase_fingerprint(tmp_path)
assert result_without != result_with
def test_codebase_fingerprint_stat_oserror(tmp_path: Path) -> None:
(tmp_path / "source.py").write_text("x = 1", encoding="utf-8")
stat_calls: dict[str, int] = {}
real_stat = Path.stat
def patched_stat(self: Path, **kwargs: object) -> object:
key = str(self)
stat_calls[key] = stat_calls.get(key, 0) + 1
if stat_calls[key] >= 2 and key.endswith(".py"):
msg = "simulated stat failure"
raise OSError(msg)
return real_stat(self, **kwargs)
with patch.object(Path, "stat", patched_stat):
result = codebase_fingerprint(tmp_path)
assert len(result) == 16
def test_codebase_fingerprint_changes_on_modification(tmp_path: Path) -> None:
f = tmp_path / "mod.py"
f.write_text("x = 1", encoding="utf-8")
fp1 = codebase_fingerprint(tmp_path)
f.write_text("x = 2", encoding="utf-8")
fp2 = codebase_fingerprint(tmp_path)
assert fp1 != fp2
def test_extract_items_image_suffix(tmp_path: Path) -> None:
(tmp_path / "logo.png").write_bytes(b"\x89PNG\r\n")
items = extract_items(tmp_path)
assert items == []
def test_code_item_defaults() -> None:
item = CodeItem(
id="mod.fn",
file="mod.py",
type="function",
name="fn",
start_line=1,
end_line=5,
)
assert item.class_name == ""
assert item.depends_on == []
def test_codebase_fingerprint_stat_oserror_raises(tmp_path: Path) -> None:
"""Skip a file whose ``stat`` raises ``OSError`` (except branch).
``is_file()`` is forced True for the target so the loop reaches the
explicit ``path.stat()`` at fingerprint time; that stat then raises and
the ``except OSError`` handler drops the unreadable entry. Patching both
keeps this deterministic across Python versions (on some, ``is_file``
itself calls ``stat`` and would otherwise re-raise before line reached).
"""
(tmp_path / "source.py").write_text("x = 1", encoding="utf-8")
real_stat = Path.stat
real_is_file = Path.is_file
def failing_stat(self: Path, **kwargs: object) -> object:
"""Raise for the target file, delegate to the real stat otherwise."""
if str(self).endswith("source.py"):
msg = "simulated stat failure"
raise OSError(msg)
return real_stat(self, **kwargs)
def always_file(self: Path) -> bool:
"""Report the target as a regular file without calling stat."""
return str(self).endswith("source.py") or real_is_file(self)
with (
patch.object(Path, "stat", failing_stat),
patch.object(Path, "is_file", always_file),
):
result = codebase_fingerprint(tmp_path)
assert len(result) == 16

View File

@ -5,13 +5,8 @@ from __future__ import annotations
import json
from unittest.mock import MagicMock, patch
import pytest
from python_pkg.code_tutor._llm import (
ClaudeBackend,
OllamaBackend,
_is_weak,
complete_with_fallback,
)
# ---------------------------------------------------------------------------
@ -77,244 +72,3 @@ def test_ollama_stream_empty_token_not_appended() -> None:
assert result == "ok"
assert tokens == ["ok"]
# ---------------------------------------------------------------------------
# ClaudeBackend.complete
# ---------------------------------------------------------------------------
def test_claude_complete_with_text_block() -> None:
mock_block = MagicMock()
mock_block.text = "answer"
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client = MagicMock()
mock_client.messages.create.return_value = mock_message
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
backend = ClaudeBackend()
result = backend.complete("sys", "user")
assert result == "answer"
def test_claude_complete_no_text_attr() -> None:
mock_block = MagicMock(spec=[]) # no .text attribute
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client = MagicMock()
mock_client.messages.create.return_value = mock_message
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
backend = ClaudeBackend()
result = backend.complete("sys", "user")
assert result == ""
# ---------------------------------------------------------------------------
# ClaudeBackend.stream
# ---------------------------------------------------------------------------
def test_claude_stream_success() -> None:
mock_stream_ctx = MagicMock()
mock_stream_ctx.__enter__ = MagicMock(return_value=mock_stream_ctx)
mock_stream_ctx.__exit__ = MagicMock(return_value=False)
mock_stream_ctx.text_stream = iter(["hello", " world"])
mock_client = MagicMock()
mock_client.messages.stream.return_value = mock_stream_ctx
tokens: list[str] = []
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
backend = ClaudeBackend()
result = backend.stream("sys", "user", tokens.append)
assert result == "hello world"
assert tokens == ["hello", " world"]
def test_claude_stream_api_error_fallback() -> None:
import anthropic as anthropic_lib
mock_client = MagicMock()
mock_client.messages.stream.side_effect = anthropic_lib.APIError(
message="fail",
request=MagicMock(),
body=None,
)
mock_block = MagicMock()
mock_block.text = "fallback"
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client.messages.create.return_value = mock_message
tokens: list[str] = []
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
backend = ClaudeBackend()
result = backend.stream("sys", "user", tokens.append)
assert result == "fallback"
# ---------------------------------------------------------------------------
# _is_weak
# ---------------------------------------------------------------------------
def test_is_weak_short() -> None:
assert _is_weak("ok") is True
def test_is_weak_phrase() -> None:
assert _is_weak("I don't know what this code does at all honestly") is True
def test_is_weak_strong_response() -> None:
long_response = (
"This function reads the first 512 bytes of a file and checks for"
" null bytes to determine if the file is binary."
)
assert _is_weak(long_response) is False
# ---------------------------------------------------------------------------
# complete_with_fallback
# ---------------------------------------------------------------------------
def test_complete_with_fallback_strong() -> None:
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.return_value = (
"This is a detailed response explaining the code in full."
)
mock_console = MagicMock()
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: ""
)
assert result == "This is a detailed response explaining the code in full."
mock_primary.complete.assert_called_once()
def test_complete_with_fallback_weak_user_says_yes_claude_ok() -> None:
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.return_value = "ok" # short → weak
mock_block = MagicMock()
mock_block.text = "claude response is great"
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client = MagicMock()
mock_client.messages.create.return_value = mock_message
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: "y"
)
assert result == "claude response is great"
def test_complete_with_fallback_weak_user_says_yes_claude_fails() -> None:
import anthropic as anthropic_lib
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.side_effect = [
"ok", # first call → weak
"retry response from ollama", # retry after claude failure
]
mock_client = MagicMock()
mock_client.messages.create.side_effect = anthropic_lib.APIError(
message="fail",
request=MagicMock(),
body=None,
)
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: "y"
)
assert result == "retry response from ollama"
assert mock_primary.complete.call_count == 2
def test_complete_with_fallback_weak_user_says_no() -> None:
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.side_effect = [
"ok", # first call → weak
"second ollama response here too", # retry
]
mock_console = MagicMock()
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: "n"
)
assert result == "second ollama response here too"
assert mock_primary.complete.call_count == 2
def test_ollama_backend_defaults() -> None:
backend = OllamaBackend()
assert "11434" in backend._url
assert backend._timeout > 0
@pytest.mark.parametrize(
"phrase",
[
"i cannot help with that request really",
"it is unclear what you mean by that",
"i'm not sure about this code",
],
)
def test_is_weak_various_phrases(phrase: str) -> None:
assert _is_weak(phrase) is True
def test_ollama_stream_no_done_marker() -> None:
"""Exhaust the stream loop without a ``done`` marker (no ``break``).
When no line carries ``done: true`` the loop runs to exhaustion and
falls through to ``return "".join(parts)`` rather than breaking early.
"""
lines = [
json.dumps({"response": "foo", "done": False}).encode(),
json.dumps({"response": "bar", "done": False}).encode(),
]
mock_resp = MagicMock()
mock_resp.iter_lines.return_value = iter(lines)
tokens: list[str] = []
with patch("python_pkg.code_tutor._llm.requests.post", return_value=mock_resp):
backend = OllamaBackend()
result = backend.stream("sys", "user", tokens.append)
assert result == "foobar"
assert tokens == ["foo", "bar"]

View File

@ -0,0 +1,164 @@
"""Tests for weak-response detection and the Claude fallback."""
from __future__ import annotations
import json
from unittest.mock import MagicMock, patch
import pytest
from python_pkg.code_tutor._llm import (
OllamaBackend,
_is_weak,
complete_with_fallback,
)
# ---------------------------------------------------------------------------
# _is_weak
# ---------------------------------------------------------------------------
def test_is_weak_short() -> None:
assert _is_weak("ok") is True
def test_is_weak_phrase() -> None:
assert _is_weak("I don't know what this code does at all honestly") is True
def test_is_weak_strong_response() -> None:
long_response = (
"This function reads the first 512 bytes of a file and checks for"
" null bytes to determine if the file is binary."
)
assert _is_weak(long_response) is False
# ---------------------------------------------------------------------------
# complete_with_fallback
# ---------------------------------------------------------------------------
def test_complete_with_fallback_strong() -> None:
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.return_value = (
"This is a detailed response explaining the code in full."
)
mock_console = MagicMock()
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: ""
)
assert result == "This is a detailed response explaining the code in full."
mock_primary.complete.assert_called_once()
def test_complete_with_fallback_weak_user_says_yes_claude_ok() -> None:
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.return_value = "ok" # short → weak
mock_block = MagicMock()
mock_block.text = "claude response is great"
mock_message = MagicMock()
mock_message.content = [mock_block]
mock_client = MagicMock()
mock_client.messages.create.return_value = mock_message
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: "y"
)
assert result == "claude response is great"
def test_complete_with_fallback_weak_user_says_yes_claude_fails() -> None:
import anthropic as anthropic_lib
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.side_effect = [
"ok", # first call → weak
"retry response from ollama", # retry after claude failure
]
mock_client = MagicMock()
mock_client.messages.create.side_effect = anthropic_lib.APIError(
message="fail",
request=MagicMock(),
body=None,
)
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._llm.anthropic.Anthropic", return_value=mock_client
):
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: "y"
)
assert result == "retry response from ollama"
assert mock_primary.complete.call_count == 2
def test_complete_with_fallback_weak_user_says_no() -> None:
mock_primary = MagicMock(spec=OllamaBackend)
mock_primary.complete.side_effect = [
"ok", # first call → weak
"second ollama response here too", # retry
]
mock_console = MagicMock()
result = complete_with_fallback(
mock_primary, "sys", "user", console=mock_console, input_fn=lambda _: "n"
)
assert result == "second ollama response here too"
assert mock_primary.complete.call_count == 2
def test_ollama_backend_defaults() -> None:
backend = OllamaBackend()
assert "11434" in backend._url
assert backend._timeout > 0
@pytest.mark.parametrize(
"phrase",
[
"i cannot help with that request really",
"it is unclear what you mean by that",
"i'm not sure about this code",
],
)
def test_is_weak_various_phrases(phrase: str) -> None:
assert _is_weak(phrase) is True
def test_ollama_stream_no_done_marker() -> None:
"""Exhaust the stream loop without a ``done`` marker (no ``break``).
When no line carries ``done: true`` the loop runs to exhaustion and
falls through to ``return "".join(parts)`` rather than breaking early.
"""
lines = [
json.dumps({"response": "foo", "done": False}).encode(),
json.dumps({"response": "bar", "done": False}).encode(),
]
mock_resp = MagicMock()
mock_resp.iter_lines.return_value = iter(lines)
tokens: list[str] = []
with patch("python_pkg.code_tutor._llm.requests.post", return_value=mock_resp):
backend = OllamaBackend()
result = backend.stream("sys", "user", tokens.append)
assert result == "foobar"
assert tokens == ["foo", "bar"]

View File

@ -0,0 +1,163 @@
"""Tests for python_pkg.code_tutor._pytest_runner."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import MagicMock, patch
from python_pkg.code_tutor._challenge_support import (
_scan_test_file,
_show_test_panels,
)
from python_pkg.code_tutor._pytest_runner import _patch_and_test, _pytest_clean
from python_pkg.code_tutor.tests.conftest import _item
# ---------------------------------------------------------------------------
# _pytest_clean
# ---------------------------------------------------------------------------
def test_pytest_clean_pass() -> None:
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = "1 passed"
mock_result.stderr = ""
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner.subprocess.run",
return_value=mock_result,
):
assert (
_pytest_clean(["test_mod.py::test_fn"], Path("/proj"), mock_console) is True
)
def test_pytest_clean_fail() -> None:
mock_result = MagicMock()
mock_result.returncode = 1
mock_result.stdout = ""
mock_result.stderr = "FAILED"
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner.subprocess.run",
return_value=mock_result,
):
assert (
_pytest_clean(["test_mod.py::test_fn"], Path("/proj"), mock_console)
is False
)
def test_pytest_clean_no_output() -> None:
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = ""
mock_result.stderr = ""
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner.subprocess.run",
return_value=mock_result,
):
_pytest_clean([], Path("/proj"), mock_console)
mock_console.print.assert_not_called()
# ---------------------------------------------------------------------------
# _patch_and_test
# ---------------------------------------------------------------------------
def test_patch_and_test_syntax_error(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
mock_console = MagicMock()
result = _patch_and_test(
_item(file="mod.py", start=1, end=2),
str(tmp_path),
"def fn(\n broken syntax",
[],
mock_console,
)
assert result is False
# Original file should be restored
assert (tmp_path / "mod.py").read_text(encoding="utf-8") == source
def test_patch_and_test_passes(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._pytest_runner._pytest_clean", return_value=True):
result = _patch_and_test(
_item(file="mod.py", start=1, end=2),
str(tmp_path),
"def fn():\n return 99",
[(test_file, ["test_fn"])],
mock_console,
)
assert result is True
# File restored
assert (tmp_path / "mod.py").read_text(encoding="utf-8") == source
def test_patch_and_test_fails(tmp_path: Path) -> None:
source = "def fn():\n return 1\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
mock_console = MagicMock()
with patch(
"python_pkg.code_tutor._pytest_runner._pytest_clean", return_value=False
):
result = _patch_and_test(
_item(file="mod.py", start=1, end=2),
str(tmp_path),
"def fn():\n return 0",
[(test_file, ["test_fn"])],
mock_console,
)
assert result is False
assert (tmp_path / "mod.py").read_text(encoding="utf-8") == source
def test_scan_test_file_non_func_non_class_toplevel() -> None:
"""Skip a top-level node that is neither a function nor a class def.
A module-level ``import`` fails both ``isinstance`` checks, exercising
the branch that falls through the ``elif ClassDef`` back to the loop.
"""
source = "import os\ndef test_fn_uses_fn():\n fn()\n"
result = _scan_test_file(source, "fn")
assert result == ["test_fn_uses_fn"]
def test_show_test_panels_non_func_non_class_toplevel(tmp_path: Path) -> None:
"""Skip a top-level node that is neither a function nor a class def.
A module-level ``import`` yields an empty ``nodes`` list, so the
``elif ClassDef`` branch is not taken before the inner render loop.
"""
source = "import os\ndef test_fn():\n fn(1)\n"
test_file = tmp_path / "test_mod.py"
test_file.write_text(source, encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge_support.Syntax"):
_show_test_panels([(test_file, ["test_fn"])], mock_console)
assert mock_console.print.called
def test_show_test_panels_class_non_func_member(tmp_path: Path) -> None:
"""Skip a class-body member that is not a function definition.
The class-level ``attr = 1`` assignment fails the member ``isinstance``
check, exercising the branch that loops back to the next body member.
"""
source = "class TestFoo:\n attr = 1\n def test_fn(self):\n fn()\n"
test_file = tmp_path / "test_mod.py"
test_file.write_text(source, encoding="utf-8")
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge_support.Syntax"):
_show_test_panels([(test_file, ["TestFoo::test_fn"])], mock_console)
assert mock_console.print.called

View File

@ -0,0 +1,71 @@
"""Tests for the run_coding_challenge entry point."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from python_pkg.code_tutor._challenge_flows import (
run_coding_challenge,
)
from python_pkg.code_tutor.tests.conftest import _item
if TYPE_CHECKING:
from pathlib import Path
# ---------------------------------------------------------------------------
# run_coding_challenge
# ---------------------------------------------------------------------------
def test_run_coding_challenge_non_python() -> None:
mock_console = MagicMock()
mock_backend = MagicMock()
result = run_coding_challenge(
_item(file="main.go"),
"/codebase",
"explanation",
mock_backend,
mock_console,
)
assert result == "skipped"
def test_run_coding_challenge_with_existing_tests(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
test_file = tmp_path / "test_mod.py"
test_file.write_text("def test_fn(): fn()\n", encoding="utf-8")
mock_console = MagicMock()
mock_backend = MagicMock()
with patch(
"python_pkg.code_tutor._challenge_flows._existing_tests_flow",
return_value="passed",
):
result = run_coding_challenge(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
)
assert result == "passed"
def test_run_coding_challenge_no_tests(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn(): pass\n", encoding="utf-8")
mock_console = MagicMock()
mock_backend = MagicMock()
with patch(
"python_pkg.code_tutor._challenge_flows._write_tests_first_flow",
return_value="skipped",
):
result = run_coding_challenge(
_item(file="mod.py"),
str(tmp_path),
"explanation",
mock_backend,
mock_console,
)
assert result == "skipped"

View File

@ -0,0 +1,224 @@
"""Tests for signature-block extraction and import hints."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import MagicMock, patch
from python_pkg.code_tutor._challenge import (
_collect_and_rate_tests,
_validate_tests_against_real,
)
from python_pkg.code_tutor._challenge_support import (
_extract_signature_block,
_import_hint,
)
from python_pkg.code_tutor.tests.conftest import _item, _make_live_mock
# ---------------------------------------------------------------------------
# _extract_signature_block
# ---------------------------------------------------------------------------
def test_extract_signature_block_with_docstring(tmp_path: Path) -> None:
source = 'def fn(x):\n """Do thing."""\n return x\n'
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py"), str(tmp_path))
assert "def fn" in result
assert '"""Do thing."""' in result
def test_extract_signature_block_without_docstring(tmp_path: Path) -> None:
source = "def fn(x):\n return x\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py"), str(tmp_path))
assert "def fn" in result
assert "return" not in result
def test_extract_signature_block_oserror(tmp_path: Path) -> None:
result = _extract_signature_block(_item(file="missing.py"), str(tmp_path))
assert "def fn(...):" in result
def test_extract_signature_block_no_match(tmp_path: Path) -> None:
source = "def other(): pass\n"
(tmp_path / "mod.py").write_text(source, encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py", name="fn"), str(tmp_path))
assert "def fn(...):" in result
def test_extract_signature_block_syntax_error(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def (broken):\n", encoding="utf-8")
result = _extract_signature_block(_item(file="mod.py"), str(tmp_path))
assert "def fn(...):" in result
# ---------------------------------------------------------------------------
# Tests for _import_hint
# ---------------------------------------------------------------------------
def test_import_hint_relative_to_project(tmp_path: Path) -> None:
(tmp_path / "src").mkdir()
result = _import_hint(
_item(file="src/mod.py", name="fn"),
str(tmp_path),
tmp_path,
)
assert result == "from src.mod import fn"
def test_import_hint_value_error(tmp_path: Path) -> None:
# project_root is different from codebase_path
other_root = tmp_path / "other"
other_root.mkdir()
result = _import_hint(
_item(file="src/mod.py", name="fn"),
str(tmp_path),
other_root,
)
assert result == "from mod import fn"
# ---------------------------------------------------------------------------
# _validate_tests_against_real
# ---------------------------------------------------------------------------
def test_validate_tests_syntax_error() -> None:
mock_console = MagicMock()
result = _validate_tests_against_real(
"def (broken):", "import fn", Path("/proj"), mock_console
)
assert result is False
def test_validate_tests_passes() -> None:
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge._pytest_clean", return_value=True):
result = _validate_tests_against_real(
"def test_fn():\n assert True\n",
"# import",
Path("/proj"),
mock_console,
)
assert result is True
def test_validate_tests_fails() -> None:
mock_console = MagicMock()
with patch("python_pkg.code_tutor._challenge._pytest_clean", return_value=False):
result = _validate_tests_against_real(
"def test_fn():\n assert False\n",
"# import",
Path("/proj"),
mock_console,
)
assert result is False
# ---------------------------------------------------------------------------
# _collect_and_rate_tests
# ---------------------------------------------------------------------------
def test_collect_and_rate_tests_skip() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: "skip",
)
assert result is None
def test_collect_and_rate_tests_pass_first() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
on_token('{"verdict": "PASS", "gap": ""}')
return ""
mock_backend.stream.side_effect = fake_stream
lines_iter = iter(["test code line", "END"])
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: next(lines_iter),
)
assert result == "test code line"
def test_collect_and_rate_tests_fail_twice() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
mock_backend.stream.return_value = '{"verdict": "FAIL", "gap": "bad"}'
attempt_inputs = [
# attempt 1: provide code, then END
"test code",
"END",
# attempt 2: provide code, then END
"test code again",
"END",
]
inputs_iter = iter(attempt_inputs)
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: next(inputs_iter),
)
assert result is None
def test_collect_and_rate_tests_fail_then_pass() -> None:
mock_backend = MagicMock()
mock_console = MagicMock()
live_mock = _make_live_mock()
call_count = [0]
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
call_count[0] += 1
verdict = (
'{"verdict": "FAIL", "gap": "not enough"}'
if call_count[0] == 1
else '{"verdict": "PASS", "gap": ""}'
)
on_token(verdict)
return ""
mock_backend.stream.side_effect = fake_stream
inputs = iter(["bad test", "END", "good test", "END"])
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
result = _collect_and_rate_tests(
"def fn():",
"explanation",
mock_backend,
mock_console,
lambda _: next(inputs),
)
assert result == "good test"

View File

@ -3,15 +3,15 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from unittest.mock import patch
from python_pkg.code_tutor._analyzer import CodeItem
from python_pkg.code_tutor._verifier import (
Verifier,
from python_pkg.code_tutor._verifier_support import (
_class_header,
_parse_verdict,
_read_snippet,
)
from python_pkg.code_tutor.tests.conftest import _make_live_mock, _make_verifier
if TYPE_CHECKING:
from pathlib import Path
@ -152,20 +152,6 @@ def test_parse_verdict_strips_markdown_fence() -> None:
# ---------------------------------------------------------------------------
def _make_live_mock() -> MagicMock:
live = MagicMock()
live.__enter__ = MagicMock(return_value=live)
live.__exit__ = MagicMock(return_value=False)
return live
def _make_verifier() -> tuple[Verifier, MagicMock, MagicMock]:
mock_backend = MagicMock()
mock_console = MagicMock()
verifier = Verifier(mock_backend, mock_console)
return verifier, mock_backend, mock_console
def test_judge_calls_stream_and_parses(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, mock_backend, _ = _make_verifier()
@ -235,127 +221,3 @@ def test_ask_improvement_empty() -> None:
verifier, _, _ = _make_verifier()
result = verifier._ask_improvement(lambda _: "")
assert result == ""
# ---------------------------------------------------------------------------
# Verifier.run_lesson
# ---------------------------------------------------------------------------
def _four_answers() -> list[str]:
return ["purpose", "inputs", "outputs", "why"]
def test_run_lesson_pass_first_attempt(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, mock_backend, _ = _make_verifier()
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
on_token('{"verdict": "PASS", "gap": ""}')
return ""
mock_backend.stream.side_effect = fake_stream
answers_iter = iter(_four_answers())
live_mock = _make_live_mock()
with (
patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock),
patch(
"python_pkg.code_tutor._verifier.run_coding_challenge",
return_value="skipped",
),
):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=lambda _: next(answers_iter, ""),
)
assert record.outcome == "learned"
assert record.verdict == "PASS"
assert record.attempt == 1
def test_run_lesson_skip_on_first_question(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, _, _ = _make_verifier()
live_mock = _make_live_mock()
with patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=lambda _: "skip",
)
assert record.outcome == "skipped"
assert record.verdict == "skipped"
def test_run_lesson_all_attempts_fail(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, mock_backend, _ = _make_verifier()
call_count = [0]
def fail_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
on_token('{"verdict": "FAIL", "gap": "Missing detail."}')
return ""
mock_backend.stream.side_effect = fail_stream
def input_fn(_: str) -> str:
call_count[0] += 1
# Each "round" of 4 questions: return an answer
return "my answer"
live_mock = _make_live_mock()
with patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=input_fn,
)
assert record.outcome == "struggled"
assert record.verdict == "FAIL"
assert record.attempt == 3
def test_run_lesson_pass_on_second_attempt(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, mock_backend, _ = _make_verifier()
stream_calls = [0]
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
stream_calls[0] += 1
verdict = (
'{"verdict": "FAIL", "gap": "gap"}'
if stream_calls[0] == 1
else '{"verdict": "PASS", "gap": ""}'
)
on_token(verdict)
return ""
mock_backend.stream.side_effect = fake_stream
live_mock = _make_live_mock()
with (
patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock),
patch(
"python_pkg.code_tutor._verifier.run_coding_challenge",
return_value="passed",
),
):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=lambda _: "my answer",
)
assert record.outcome == "learned"
assert record.attempt == 2

View File

@ -0,0 +1,154 @@
"""Tests for Verifier.run_lesson."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import patch
from python_pkg.code_tutor._analyzer import CodeItem
from python_pkg.code_tutor.tests.conftest import _make_live_mock, _make_verifier
if TYPE_CHECKING:
from pathlib import Path
def _make_item(
file: str = "mod.py",
name: str = "fn",
start: int = 1,
end: int = 3,
class_name: str = "",
) -> CodeItem:
return CodeItem(
id=f"{file}.{name}",
file=file,
type="function",
name=name,
start_line=start,
end_line=end,
class_name=class_name,
)
# ---------------------------------------------------------------------------
# Verifier.run_lesson
# ---------------------------------------------------------------------------
def _four_answers() -> list[str]:
return ["purpose", "inputs", "outputs", "why"]
def test_run_lesson_pass_first_attempt(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, mock_backend, _ = _make_verifier()
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
on_token('{"verdict": "PASS", "gap": ""}')
return ""
mock_backend.stream.side_effect = fake_stream
answers_iter = iter(_four_answers())
live_mock = _make_live_mock()
with (
patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock),
patch(
"python_pkg.code_tutor._verifier.run_coding_challenge",
return_value="skipped",
),
):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=lambda _: next(answers_iter, ""),
)
assert record.outcome == "learned"
assert record.verdict == "PASS"
assert record.attempt == 1
def test_run_lesson_skip_on_first_question(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, _, _ = _make_verifier()
live_mock = _make_live_mock()
with patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=lambda _: "skip",
)
assert record.outcome == "skipped"
assert record.verdict == "skipped"
def test_run_lesson_all_attempts_fail(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, mock_backend, _ = _make_verifier()
call_count = [0]
def fail_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
on_token('{"verdict": "FAIL", "gap": "Missing detail."}')
return ""
mock_backend.stream.side_effect = fail_stream
def input_fn(_: str) -> str:
call_count[0] += 1
# Each "round" of 4 questions: return an answer
return "my answer"
live_mock = _make_live_mock()
with patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=input_fn,
)
assert record.outcome == "struggled"
assert record.verdict == "FAIL"
assert record.attempt == 3
def test_run_lesson_pass_on_second_attempt(tmp_path: Path) -> None:
(tmp_path / "mod.py").write_text("def fn():\n pass\n", encoding="utf-8")
verifier, mock_backend, _ = _make_verifier()
stream_calls = [0]
def fake_stream(system: str, user: str, on_token: object) -> str:
assert callable(on_token)
stream_calls[0] += 1
verdict = (
'{"verdict": "FAIL", "gap": "gap"}'
if stream_calls[0] == 1
else '{"verdict": "PASS", "gap": ""}'
)
on_token(verdict)
return ""
mock_backend.stream.side_effect = fake_stream
live_mock = _make_live_mock()
with (
patch("python_pkg.code_tutor._verifier.Live", return_value=live_mock),
patch(
"python_pkg.code_tutor._verifier.run_coding_challenge",
return_value="passed",
),
):
record = verifier.run_lesson(
_make_item(file="mod.py"),
str(tmp_path),
input_fn=lambda _: "my answer",
)
assert record.outcome == "learned"
assert record.attempt == 2