mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-28 19:29:12 +01:00
Compare commits
3 Commits
2c01a0267e
...
6c999e3242
| Author | SHA1 | Date | |
|---|---|---|---|
| 6c999e3242 | |||
| 277cb9fd6f | |||
| 40a4eaf5b5 |
@ -76,6 +76,36 @@ every delegate needs a full docstring with `Args:`, so a 25-line function
|
|||||||
leaves a 12-line stub. Eight of those to make a line count is the cap-gaming
|
leaves a 12-line stub. Eight of those to make a line count is the cap-gaming
|
||||||
the spec forbids.
|
the spec forbids.
|
||||||
|
|
||||||
|
### A mispointed patch can HANG rather than fail
|
||||||
|
|
||||||
|
In `brother_printer` a stale patch target raised `AttributeError` or made a
|
||||||
|
real `subprocess` call — loud, or at worst a side effect you could check for
|
||||||
|
afterwards. In `code_tutor` it **spins**: `_write_tests_first_flow` reads from
|
||||||
|
an `input_fn` in a retry loop, so an unintercepted `_collect_and_rate_tests`
|
||||||
|
ran the real interactive flow and the suite hung for two minutes with no
|
||||||
|
output. `ps` showed it `State: R`, not blocked on I/O.
|
||||||
|
|
||||||
|
Two consequences for any package whose code prompts, retries or shells out:
|
||||||
|
|
||||||
|
- **Run the suite under `timeout`.** A hang is indistinguishable from a slow
|
||||||
|
run until you have waited longer than you should.
|
||||||
|
- **Assert the patch targets resolve before invoking pytest**, since a missing
|
||||||
|
one is exactly what causes the hang:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PYTHONPATH=. python3 -c "
|
||||||
|
from python_pkg.pkg import mod_a as a, mod_b as b
|
||||||
|
for n in ('_helper', 'Thing'): assert hasattr(a, n), n
|
||||||
|
"
|
||||||
|
```
|
||||||
|
|
||||||
|
`code_tutor` also patches by **absolute string with no `MOD` constant**, so a
|
||||||
|
seam there costs one rewrite per patch string rather than one `sed`. Prefer
|
||||||
|
seams whose moved block has few patched names, even at slightly worse line
|
||||||
|
arithmetic. Watch out for a `sed` with escaped alternation silently matching
|
||||||
|
nothing — a no-op rewrite looks exactly like a successful one at the shell, so
|
||||||
|
`grep` the result before trusting it.
|
||||||
|
|
||||||
### You may edit the tests to follow the code (agreed 2026-08-16)
|
### You may edit the tests to follow the code (agreed 2026-08-16)
|
||||||
|
|
||||||
When a patch target moves, **update the patch target**. Bounded by:
|
When a patch target moves, **update the patch target**. Bounded by:
|
||||||
|
|||||||
@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"title": "Split code_tutor/_challenge.py under the 250-line cap",
|
||||||
|
"objective": "Bring python_pkg/code_tutor/_challenge.py (467 lines) under the repo-wide 250-line cap by moving the two challenge flows and the public entry point into _challenge_flows.py, and the static prompt strings into _challenge_prompts.py.",
|
||||||
|
"acceptance_criteria": [
|
||||||
|
"_challenge.py, _challenge_flows.py and _challenge_prompts.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.",
|
||||||
|
"Every patch string in test_challenge_part3.py names the module its function-under-test now resolves collaborators through, decided per test rather than by a blanket substitution: the _run_user_impl tests keep _challenge, the flow and entry-point tests move to _challenge_flows.",
|
||||||
|
"The suite completes in seconds. A patch that no longer intercepts here does not fail - it lets the real interactive flow run and the suite spins, so wall-clock time is part of the pass condition.",
|
||||||
|
"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 any prompt text.",
|
||||||
|
"Splitting cli.py, _analyzer.py, _verifier.py, _llm.py or the code_tutor test modules, which are separate commits.",
|
||||||
|
"Adding a re-export shim in _challenge; _verifier.py points at _challenge_flows directly."
|
||||||
|
],
|
||||||
|
"verifier": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (expects exactly 216 passed, well inside the timeout), plus an import-time assertion that every patched name resolves on the module its test names, plus pre-commit run --files on the touched files."
|
||||||
|
}
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"title": "Split code_tutor/_challenge_support.py under the 250-line cap",
|
||||||
|
"objective": "Bring python_pkg/code_tutor/_challenge_support.py (402 lines) under the repo-wide 250-line cap by moving the isolated pytest runner and the LLM verdict streaming into their own modules.",
|
||||||
|
"acceptance_criteria": [
|
||||||
|
"_challenge_support.py, _pytest_runner.py and _verdict.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.",
|
||||||
|
"Every patch string naming a moved function or one of its plain-import collaborators is repointed at the module the code actually lives in now. code_tutor uses absolute patch strings rather than a MOD constant, so this is a per-string edit and cannot be done with one substitution.",
|
||||||
|
"_challenge.py imports _patch_and_test, _pytest_clean, _parse_verdict and _stream_verdict back, because test_challenge_part3.py patches the first two on _challenge.",
|
||||||
|
"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 any pytest invocation flags.",
|
||||||
|
"Splitting _challenge.py, cli.py, _analyzer.py or the code_tutor test modules, which are separate commits.",
|
||||||
|
"Adding a re-export shim in _challenge_support; importers point at the new modules directly to keep the dependency direction one-way."
|
||||||
|
],
|
||||||
|
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (expects exactly 216 passed), plus an import-time attribute probe over the four modules, plus pre-commit run --files on the touched files."
|
||||||
|
}
|
||||||
@ -0,0 +1,52 @@
|
|||||||
|
{
|
||||||
|
"intent": "Bring code_tutor/_challenge.py under the 250-line cap by moving the two challenge flows, the entry point and the static prompt strings into their own modules, with no behaviour change.",
|
||||||
|
"scope": [
|
||||||
|
"python_pkg/code_tutor/_challenge_flows.py, _challenge_prompts.py (new)",
|
||||||
|
"python_pkg/code_tutor/_challenge.py (467 -> 236)",
|
||||||
|
"python_pkg/code_tutor/_verifier.py (import path only)",
|
||||||
|
"python_pkg/code_tutor/tests/test_challenge_part3.py (import and patch paths only)",
|
||||||
|
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
"Moved _write_tests_first_flow, _existing_tests_flow and run_coding_challenge into _challenge_flows.py, which imports the three interactive stages back from _challenge.",
|
||||||
|
"Moved _NO_AI_NOTICE, _MAX_TEST_ATTEMPTS and _TEST_JUDGE_SYSTEM into _challenge_prompts.py. The first cut left _challenge.py at 261, eleven over; these three constants are pure data with no patch targets, which made them the cheapest remaining eleven lines.",
|
||||||
|
"_verifier.py imports run_coding_challenge from _challenge_flows directly rather than through a re-export shim.",
|
||||||
|
"Repointed 13 patch strings in test_challenge_part3.py from _challenge to _challenge_flows, decided per test by which function is under test: the four _run_user_impl tests keep _challenge, the eight flow and entry-point tests move. A blanket substitution would have broken the first group.",
|
||||||
|
"_challenge.py dropped four imports the moved code solely used, and its module docstring now names where the flows went."
|
||||||
|
],
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"command": "timeout 90 env PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "216 passed in 2.1s - identical to the baseline count, and comfortably inside the timeout."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (intermediate run, before the patch strings were repointed)",
|
||||||
|
"result": "hang",
|
||||||
|
"evidence": "The suite spun for over two minutes and had to be killed. test_write_tests_first_flow_tests_none patched _collect_and_rate_tests on _challenge while _write_tests_first_flow had moved to _challenge_flows, so the patch stopped intercepting and the real interactive flow ran against a stub input function. This is the silent failure mode docs/python-split-recipes.md warns about: not a red test, but real execution. Every subsequent run was given an explicit timeout."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "PYTHONPATH=. python3 -c \"<assert every patched name resolves on _challenge_flows and _challenge>\"",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "all patch targets resolve - run before the pytest invocation specifically because a missing target here spins rather than errors."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "wc -l python_pkg/code_tutor/_challenge.py python_pkg/code_tutor/_challenge_flows.py python_pkg/code_tutor/_challenge_prompts.py",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "236, 242 and 36 lines, all under the 250-line cap."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "pre-commit run --files <the touched files and artifacts>",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "ruff caught F821 Undefined name 'Callable' - the new module's TYPE_CHECKING block needed it. Fixed; ruff, ruff format, mypy, pylint, bandit and pytest-with-coverage then all pass."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"risks": [
|
||||||
|
"This package's failure mode on a mispointed patch is a hang, not an error, because the code under test reads from an input callable in a retry loop. Any future split here should assert the patch targets resolve before running the suite, and should always run it under a timeout.",
|
||||||
|
"_challenge_flows imports from _challenge, which imports from _challenge_prompts, _challenge_support, _pytest_runner and _verdict. That direction must hold; _challenge importing from _challenge_flows would be a cycle."
|
||||||
|
],
|
||||||
|
"rollback": [
|
||||||
|
"git revert the commit; _challenge.py returns to 467 lines and the two new modules disappear.",
|
||||||
|
"After rollback, re-run the package suite and confirm it still reports 216 passed."
|
||||||
|
]
|
||||||
|
}
|
||||||
@ -0,0 +1,52 @@
|
|||||||
|
{
|
||||||
|
"intent": "Bring code_tutor/_challenge_support.py under the 250-line cap by moving the isolated pytest runner and the LLM verdict streaming into their own modules, with no behaviour change.",
|
||||||
|
"scope": [
|
||||||
|
"python_pkg/code_tutor/_pytest_runner.py, _verdict.py (new)",
|
||||||
|
"python_pkg/code_tutor/_challenge_support.py (402 -> 237)",
|
||||||
|
"python_pkg/code_tutor/_challenge.py (import paths only)",
|
||||||
|
"python_pkg/code_tutor/tests/test_challenge.py, test_challenge_part2.py, test_challenge_part3.py (import and patch paths only)",
|
||||||
|
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
"Moved _pytest_clean and _patch_and_test into _pytest_runner.py, which now owns the subprocess, os and sys imports they were the only users of, and imports _project_root back from _challenge_support.",
|
||||||
|
"Moved _stream_verdict and _parse_verdict into _verdict.py, which owns rich.live.Live, Text, time, json and re. Live was used at exactly one call site, so nothing else in _challenge_support needed it.",
|
||||||
|
"_challenge_support.py dropped seven now-dead imports (Live, Text, time, json, os, subprocess, sys, re) and keeps ast, Path, Panel and Syntax, which its remaining source-inspection helpers use.",
|
||||||
|
"_challenge.py imports the four moved functions back from their new homes, preserving the patch targets test_challenge_part3.py names on _challenge.",
|
||||||
|
"Repointed the test patch strings per name: ten occurrences of _challenge_support.Live to _verdict.Live, three of _challenge_support.subprocess.run and two of _challenge_support._pytest_clean to _pytest_runner. Also repointed the direct imports in test_challenge.py and test_challenge_part2.py."
|
||||||
|
],
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"command": "PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "216 passed before the split and 216 passed after it - identical pass count, not merely a green run."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "PYTHONPATH=. python3 -m pytest python_pkg/code_tutor/tests -q (intermediate runs)",
|
||||||
|
"result": "fail then pass",
|
||||||
|
"evidence": "Two intermediate failures, both caught by running rather than by reading: first 2 collection ImportErrors because test_challenge.py and test_challenge_part2.py import the moved functions directly, then 5 failures with 'does not have the attribute _pytest_clean' and 'no attribute subprocess' from patch strings still naming the old module. Both fixed per name."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "PYTHONPATH=. python3 -c \"from python_pkg.code_tutor import _challenge as c, _challenge_support as s, _pytest_runner as r, _verdict as v; c._pytest_clean; c._patch_and_test; c._stream_verdict; s.Syntax; s.ast; r.subprocess; r.os; r.sys; v.Live; v.time\"",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "runtime probe OK - every patched name is a real attribute of the module its test names."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "wc -l python_pkg/code_tutor/_challenge_support.py python_pkg/code_tutor/_pytest_runner.py python_pkg/code_tutor/_verdict.py",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "237, 111 and 89 lines, all under the 250-line cap. The first cut alone left 313, so a second seam was needed - the budgeting warning in docs/python-split-recipes.md again."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "pre-commit run --files <the touched files and artifacts>",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "ruff, ruff format, mypy, pylint, bandit and pytest-with-coverage all pass on the touched files."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"risks": [
|
||||||
|
"A sed with escaped alternation silently matched nothing and left the patch strings unchanged while reporting success; the failing test run caught it and the replacement was redone in Python. Worth remembering that a no-op rewrite looks identical to a successful one at the shell.",
|
||||||
|
"_pytest_runner runs the user's tests in a subprocess. Its subprocess import is patched by test_challenge.py, so a future move of that import would let the suite really invoke pytest - the same silent-failure shape as the CUPS restart in brother_printer."
|
||||||
|
],
|
||||||
|
"rollback": [
|
||||||
|
"git revert the commit; _challenge_support.py returns to 402 lines and the two new modules disappear.",
|
||||||
|
"After rollback, re-run the package suite and confirm it still reports 216 passed."
|
||||||
|
]
|
||||||
|
}
|
||||||
@ -11,9 +11,10 @@ to implement.
|
|||||||
In both cases the original implementation is hidden during the challenge.
|
In both cases the original implementation is hidden during the challenge.
|
||||||
|
|
||||||
The lower-level discovery / pytest / verdict helpers live in
|
The lower-level discovery / pytest / verdict helpers live in
|
||||||
:mod:`python_pkg.code_tutor._challenge_support`; this module keeps the
|
:mod:`python_pkg.code_tutor._challenge_support`, and the two flows plus the
|
||||||
interactive validation, rating and flow orchestration plus the public
|
public ``run_coding_challenge`` entry point in
|
||||||
``run_coding_challenge`` entry point.
|
:mod:`python_pkg.code_tutor._challenge_flows`. This module keeps the three
|
||||||
|
interactive stages those flows are built from.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -26,18 +27,17 @@ from typing import TYPE_CHECKING
|
|||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.syntax import Syntax
|
from rich.syntax import Syntax
|
||||||
|
|
||||||
|
from python_pkg.code_tutor._challenge_prompts import (
|
||||||
|
_MAX_TEST_ATTEMPTS,
|
||||||
|
_TEST_JUDGE_SYSTEM,
|
||||||
|
)
|
||||||
from python_pkg.code_tutor._challenge_support import (
|
from python_pkg.code_tutor._challenge_support import (
|
||||||
_collect_lines,
|
_collect_lines,
|
||||||
_extract_signature_block,
|
_extract_signature_block,
|
||||||
_find_tests,
|
|
||||||
_import_hint,
|
|
||||||
_parse_verdict,
|
|
||||||
_patch_and_test,
|
|
||||||
_project_root,
|
_project_root,
|
||||||
_pytest_clean,
|
|
||||||
_show_test_panels,
|
|
||||||
_stream_verdict,
|
|
||||||
)
|
)
|
||||||
|
from python_pkg.code_tutor._pytest_runner import _pytest_clean
|
||||||
|
from python_pkg.code_tutor._verdict import _parse_verdict, _stream_verdict
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
@ -47,34 +47,6 @@ if TYPE_CHECKING:
|
|||||||
from python_pkg.code_tutor._analyzer import CodeItem
|
from python_pkg.code_tutor._analyzer import CodeItem
|
||||||
from python_pkg.code_tutor._llm import Backend
|
from python_pkg.code_tutor._llm import Backend
|
||||||
|
|
||||||
_NO_AI_NOTICE = (
|
|
||||||
"[bold yellow]⚠ No AI assistance -- write this yourself.[/bold yellow]\n"
|
|
||||||
"Your own explanation (and the tests below) are your only reference."
|
|
||||||
)
|
|
||||||
|
|
||||||
_MAX_TEST_ATTEMPTS = 2
|
|
||||||
|
|
||||||
_TEST_JUDGE_SYSTEM = (
|
|
||||||
"You are a code tutor evaluating whether a student's tests adequately"
|
|
||||||
" cover a function.\n\n"
|
|
||||||
"PASS if the tests:\n"
|
|
||||||
" - Include at least 2 meaningfully different test cases with distinct inputs\n"
|
|
||||||
" - Use assertions that verify the actual return value or observable behavior\n"
|
|
||||||
" - Would catch an obviously wrong implementation (e.g. one that always"
|
|
||||||
' returns "")\n\n'
|
|
||||||
"FAIL only if:\n"
|
|
||||||
" - There is only one trivial test case\n"
|
|
||||||
" - Assertions are always-true or don't check the function's real output\n"
|
|
||||||
" - All tests are essentially the same scenario with trivially different data\n\n"
|
|
||||||
"Do NOT require error/edge-case tests for pure transformation functions that"
|
|
||||||
" have no error handling. 2+ meaningful happy-path cases with distinct"
|
|
||||||
" inputs is enough.\n\n"
|
|
||||||
"Respond with valid JSON only, no other text:\n"
|
|
||||||
'{"verdict": "PASS" | "FAIL",'
|
|
||||||
' "gap": "<one sentence on the specific missing scenario,'
|
|
||||||
' or empty string on PASS>"}'
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_tests_against_real(
|
def _validate_tests_against_real(
|
||||||
test_code: str,
|
test_code: str,
|
||||||
@ -263,207 +235,3 @@ def _run_user_impl(
|
|||||||
return "passed"
|
return "passed"
|
||||||
console.print("[red]✗ Your implementation didn't pass your own tests.[/red]")
|
console.print("[red]✗ Your implementation didn't pass your own tests.[/red]")
|
||||||
return "failed"
|
return "failed"
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# "Write tests first" flow -- orchestrator
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _write_tests_first_flow(
|
|
||||||
item: CodeItem,
|
|
||||||
codebase_path: str,
|
|
||||||
user_explanation: str,
|
|
||||||
backend: Backend,
|
|
||||||
console: Console,
|
|
||||||
input_fn: Callable[[str], str],
|
|
||||||
) -> str:
|
|
||||||
"""Challenge flow used when no existing tests are found.
|
|
||||||
|
|
||||||
Asks the user to write tests first, rates them with the LLM, validates
|
|
||||||
them against the real implementation, then asks the user to write their
|
|
||||||
own implementation.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
item: Code item being challenged.
|
|
||||||
codebase_path: Absolute codebase root path.
|
|
||||||
user_explanation: User's earlier explanation, shown as reference.
|
|
||||||
backend: LLM backend for test quality rating.
|
|
||||||
console: Rich console for output.
|
|
||||||
input_fn: Callable for reading user input.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``"passed"``, ``"failed"``, or ``"skipped"``.
|
|
||||||
"""
|
|
||||||
project_root = _project_root(Path(codebase_path))
|
|
||||||
import_hint = _import_hint(item, codebase_path, project_root)
|
|
||||||
sig_block = _extract_signature_block(item, codebase_path)
|
|
||||||
|
|
||||||
console.print(
|
|
||||||
"\n[bold cyan]Coding challenge (tests first):[/bold cyan] "
|
|
||||||
"No existing tests found -- write them before implementing.\n"
|
|
||||||
)
|
|
||||||
answer = input_fn("Take the challenge? [y/N] ").strip().lower()
|
|
||||||
if answer != "y":
|
|
||||||
return "skipped"
|
|
||||||
|
|
||||||
console.print(
|
|
||||||
Panel(
|
|
||||||
user_explanation,
|
|
||||||
title="Your explanation (your only reference)",
|
|
||||||
border_style="dim",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
console.print(_NO_AI_NOTICE)
|
|
||||||
console.print(
|
|
||||||
Panel(
|
|
||||||
Syntax(sig_block, "python", theme="monokai"),
|
|
||||||
title="[blue]Function signature + contract[/blue]",
|
|
||||||
border_style="blue",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
console.print(
|
|
||||||
f"\n[dim]Auto-import that will be prepended to your tests:[/dim]\n"
|
|
||||||
f"[cyan]{import_hint}[/cyan]\n"
|
|
||||||
"[dim]Add any other imports (pytest, MagicMock, etc.) yourself.[/dim]\n"
|
|
||||||
)
|
|
||||||
|
|
||||||
test_code = _collect_and_rate_tests(
|
|
||||||
sig_block, user_explanation, backend, console, input_fn
|
|
||||||
)
|
|
||||||
if test_code is None:
|
|
||||||
return "skipped"
|
|
||||||
|
|
||||||
console.print(
|
|
||||||
"\n[dim]Validating your tests against the real implementation...[/dim]"
|
|
||||||
)
|
|
||||||
if not _validate_tests_against_real(test_code, import_hint, project_root, console):
|
|
||||||
console.print(
|
|
||||||
"[red]Your tests fail on the correct implementation -- "
|
|
||||||
"they may be testing the wrong behavior. Skipping.[/red]"
|
|
||||||
)
|
|
||||||
return "skipped"
|
|
||||||
|
|
||||||
console.print(
|
|
||||||
"[green]Tests look good -- they pass on the real implementation.[/green]"
|
|
||||||
)
|
|
||||||
return _run_user_impl(
|
|
||||||
item, codebase_path, test_code, import_hint, console, input_fn
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# "Existing tests" flow
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _existing_tests_flow(
|
|
||||||
item: CodeItem,
|
|
||||||
codebase_path: str,
|
|
||||||
user_explanation: str,
|
|
||||||
test_entries: list[tuple[Path, list[str]]],
|
|
||||||
console: Console,
|
|
||||||
input_fn: Callable[[str], str],
|
|
||||||
) -> str:
|
|
||||||
"""Challenge flow used when existing tests are found.
|
|
||||||
|
|
||||||
Shows the tests, asks user to implement from scratch.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
item: Code item being challenged.
|
|
||||||
codebase_path: Absolute codebase root path.
|
|
||||||
user_explanation: User's earlier explanation.
|
|
||||||
test_entries: Existing test file/node-id pairs.
|
|
||||||
console: Rich console for output.
|
|
||||||
input_fn: Callable for reading user input.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``"passed"``, ``"failed"``, or ``"skipped"``.
|
|
||||||
"""
|
|
||||||
n_tests = sum(len(ids) for _, ids in test_entries)
|
|
||||||
console.print(
|
|
||||||
"\n[bold cyan]Coding challenge:[/bold cyan] "
|
|
||||||
f"Can you rewrite this function from scratch? "
|
|
||||||
f"[dim]({n_tests} test(s) will validate it)[/dim]"
|
|
||||||
)
|
|
||||||
answer = input_fn("Take the challenge? [y/N] ").strip().lower()
|
|
||||||
if answer != "y":
|
|
||||||
return "skipped"
|
|
||||||
|
|
||||||
console.print(
|
|
||||||
Panel(
|
|
||||||
user_explanation,
|
|
||||||
title="Your explanation (your only reference)",
|
|
||||||
border_style="dim",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
console.print(_NO_AI_NOTICE)
|
|
||||||
_show_test_panels(test_entries, console)
|
|
||||||
|
|
||||||
user_code = _collect_lines(
|
|
||||||
f"\n[bold]Write [cyan]{item.name}[/cyan] from scratch.[/bold] "
|
|
||||||
"Finish with [dim]END[/dim] on a blank line, or [dim]skip[/dim] to skip.",
|
|
||||||
console,
|
|
||||||
input_fn,
|
|
||||||
)
|
|
||||||
if user_code is None:
|
|
||||||
console.print("[yellow]Challenge skipped.[/yellow]")
|
|
||||||
return "skipped"
|
|
||||||
|
|
||||||
console.print("\n[dim]Running tests against your implementation...[/dim]")
|
|
||||||
passed = _patch_and_test(item, codebase_path, user_code, test_entries, console)
|
|
||||||
|
|
||||||
if passed:
|
|
||||||
console.print(
|
|
||||||
"[green bold]✓ All tests passed -- you really understand it![/green bold]"
|
|
||||||
)
|
|
||||||
return "passed"
|
|
||||||
console.print("[red]✗ Some tests failed -- try again next session.[/red]")
|
|
||||||
return "failed"
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Public entry point
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def run_coding_challenge(
|
|
||||||
item: CodeItem,
|
|
||||||
codebase_path: str,
|
|
||||||
user_explanation: str,
|
|
||||||
backend: Backend,
|
|
||||||
console: Console,
|
|
||||||
input_fn: Callable[[str], str] = input,
|
|
||||||
) -> str:
|
|
||||||
"""Offer the user a coding challenge after a PASS verdict.
|
|
||||||
|
|
||||||
Routes to one of two flows:
|
|
||||||
- **Existing tests found**: show tests, user writes implementation.
|
|
||||||
- **No tests found**: user writes tests first (LLM-rated), then implementation.
|
|
||||||
|
|
||||||
Only offered for ``.py`` files.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
item: The code item to challenge on.
|
|
||||||
codebase_path: Absolute path of the codebase root.
|
|
||||||
user_explanation: The explanation the user gave during the lesson.
|
|
||||||
backend: LLM backend (used for test quality rating in the no-tests flow).
|
|
||||||
console: Rich console for output.
|
|
||||||
input_fn: Callable for reading user input.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``"passed"``, ``"failed"``, or ``"skipped"``.
|
|
||||||
"""
|
|
||||||
if not item.file.endswith(".py"):
|
|
||||||
return "skipped"
|
|
||||||
|
|
||||||
codebase = Path(codebase_path)
|
|
||||||
test_entries = _find_tests(item, codebase)
|
|
||||||
|
|
||||||
if test_entries:
|
|
||||||
return _existing_tests_flow(
|
|
||||||
item, codebase_path, user_explanation, test_entries, console, input_fn
|
|
||||||
)
|
|
||||||
return _write_tests_first_flow(
|
|
||||||
item, codebase_path, user_explanation, backend, console, input_fn
|
|
||||||
)
|
|
||||||
|
|||||||
242
python_pkg/code_tutor/_challenge_flows.py
Normal file
242
python_pkg/code_tutor/_challenge_flows.py
Normal file
@ -0,0 +1,242 @@
|
|||||||
|
"""The two challenge flows and the entry point that picks between them.
|
||||||
|
|
||||||
|
Split out of :mod:`python_pkg.code_tutor._challenge` to keep it under the
|
||||||
|
250-line cap. The three stage helpers stay there and are imported back, because
|
||||||
|
``tests/test_challenge_part3.py`` patches them on ``_challenge``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from rich.panel import Panel
|
||||||
|
from rich.syntax import Syntax
|
||||||
|
|
||||||
|
from python_pkg.code_tutor._challenge import (
|
||||||
|
_collect_and_rate_tests,
|
||||||
|
_run_user_impl,
|
||||||
|
_validate_tests_against_real,
|
||||||
|
)
|
||||||
|
from python_pkg.code_tutor._challenge_prompts import _NO_AI_NOTICE
|
||||||
|
from python_pkg.code_tutor._challenge_support import (
|
||||||
|
_collect_lines,
|
||||||
|
_extract_signature_block,
|
||||||
|
_find_tests,
|
||||||
|
_import_hint,
|
||||||
|
_project_root,
|
||||||
|
_show_test_panels,
|
||||||
|
)
|
||||||
|
from python_pkg.code_tutor._pytest_runner import _patch_and_test
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from rich.console import Console
|
||||||
|
|
||||||
|
from python_pkg.code_tutor._analyzer import CodeItem
|
||||||
|
from python_pkg.code_tutor._llm import Backend
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# "Write tests first" flow -- orchestrator
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _write_tests_first_flow(
|
||||||
|
item: CodeItem,
|
||||||
|
codebase_path: str,
|
||||||
|
user_explanation: str,
|
||||||
|
backend: Backend,
|
||||||
|
console: Console,
|
||||||
|
input_fn: Callable[[str], str],
|
||||||
|
) -> str:
|
||||||
|
"""Challenge flow used when no existing tests are found.
|
||||||
|
|
||||||
|
Asks the user to write tests first, rates them with the LLM, validates
|
||||||
|
them against the real implementation, then asks the user to write their
|
||||||
|
own implementation.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
item: Code item being challenged.
|
||||||
|
codebase_path: Absolute codebase root path.
|
||||||
|
user_explanation: User's earlier explanation, shown as reference.
|
||||||
|
backend: LLM backend for test quality rating.
|
||||||
|
console: Rich console for output.
|
||||||
|
input_fn: Callable for reading user input.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``"passed"``, ``"failed"``, or ``"skipped"``.
|
||||||
|
"""
|
||||||
|
project_root = _project_root(Path(codebase_path))
|
||||||
|
import_hint = _import_hint(item, codebase_path, project_root)
|
||||||
|
sig_block = _extract_signature_block(item, codebase_path)
|
||||||
|
|
||||||
|
console.print(
|
||||||
|
"\n[bold cyan]Coding challenge (tests first):[/bold cyan] "
|
||||||
|
"No existing tests found -- write them before implementing.\n"
|
||||||
|
)
|
||||||
|
answer = input_fn("Take the challenge? [y/N] ").strip().lower()
|
||||||
|
if answer != "y":
|
||||||
|
return "skipped"
|
||||||
|
|
||||||
|
console.print(
|
||||||
|
Panel(
|
||||||
|
user_explanation,
|
||||||
|
title="Your explanation (your only reference)",
|
||||||
|
border_style="dim",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
console.print(_NO_AI_NOTICE)
|
||||||
|
console.print(
|
||||||
|
Panel(
|
||||||
|
Syntax(sig_block, "python", theme="monokai"),
|
||||||
|
title="[blue]Function signature + contract[/blue]",
|
||||||
|
border_style="blue",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
console.print(
|
||||||
|
f"\n[dim]Auto-import that will be prepended to your tests:[/dim]\n"
|
||||||
|
f"[cyan]{import_hint}[/cyan]\n"
|
||||||
|
"[dim]Add any other imports (pytest, MagicMock, etc.) yourself.[/dim]\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
test_code = _collect_and_rate_tests(
|
||||||
|
sig_block, user_explanation, backend, console, input_fn
|
||||||
|
)
|
||||||
|
if test_code is None:
|
||||||
|
return "skipped"
|
||||||
|
|
||||||
|
console.print(
|
||||||
|
"\n[dim]Validating your tests against the real implementation...[/dim]"
|
||||||
|
)
|
||||||
|
if not _validate_tests_against_real(test_code, import_hint, project_root, console):
|
||||||
|
console.print(
|
||||||
|
"[red]Your tests fail on the correct implementation -- "
|
||||||
|
"they may be testing the wrong behavior. Skipping.[/red]"
|
||||||
|
)
|
||||||
|
return "skipped"
|
||||||
|
|
||||||
|
console.print(
|
||||||
|
"[green]Tests look good -- they pass on the real implementation.[/green]"
|
||||||
|
)
|
||||||
|
return _run_user_impl(
|
||||||
|
item, codebase_path, test_code, import_hint, console, input_fn
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# "Existing tests" flow
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _existing_tests_flow(
|
||||||
|
item: CodeItem,
|
||||||
|
codebase_path: str,
|
||||||
|
user_explanation: str,
|
||||||
|
test_entries: list[tuple[Path, list[str]]],
|
||||||
|
console: Console,
|
||||||
|
input_fn: Callable[[str], str],
|
||||||
|
) -> str:
|
||||||
|
"""Challenge flow used when existing tests are found.
|
||||||
|
|
||||||
|
Shows the tests, asks user to implement from scratch.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
item: Code item being challenged.
|
||||||
|
codebase_path: Absolute codebase root path.
|
||||||
|
user_explanation: User's earlier explanation.
|
||||||
|
test_entries: Existing test file/node-id pairs.
|
||||||
|
console: Rich console for output.
|
||||||
|
input_fn: Callable for reading user input.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``"passed"``, ``"failed"``, or ``"skipped"``.
|
||||||
|
"""
|
||||||
|
n_tests = sum(len(ids) for _, ids in test_entries)
|
||||||
|
console.print(
|
||||||
|
"\n[bold cyan]Coding challenge:[/bold cyan] "
|
||||||
|
f"Can you rewrite this function from scratch? "
|
||||||
|
f"[dim]({n_tests} test(s) will validate it)[/dim]"
|
||||||
|
)
|
||||||
|
answer = input_fn("Take the challenge? [y/N] ").strip().lower()
|
||||||
|
if answer != "y":
|
||||||
|
return "skipped"
|
||||||
|
|
||||||
|
console.print(
|
||||||
|
Panel(
|
||||||
|
user_explanation,
|
||||||
|
title="Your explanation (your only reference)",
|
||||||
|
border_style="dim",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
console.print(_NO_AI_NOTICE)
|
||||||
|
_show_test_panels(test_entries, console)
|
||||||
|
|
||||||
|
user_code = _collect_lines(
|
||||||
|
f"\n[bold]Write [cyan]{item.name}[/cyan] from scratch.[/bold] "
|
||||||
|
"Finish with [dim]END[/dim] on a blank line, or [dim]skip[/dim] to skip.",
|
||||||
|
console,
|
||||||
|
input_fn,
|
||||||
|
)
|
||||||
|
if user_code is None:
|
||||||
|
console.print("[yellow]Challenge skipped.[/yellow]")
|
||||||
|
return "skipped"
|
||||||
|
|
||||||
|
console.print("\n[dim]Running tests against your implementation...[/dim]")
|
||||||
|
passed = _patch_and_test(item, codebase_path, user_code, test_entries, console)
|
||||||
|
|
||||||
|
if passed:
|
||||||
|
console.print(
|
||||||
|
"[green bold]✓ All tests passed -- you really understand it![/green bold]"
|
||||||
|
)
|
||||||
|
return "passed"
|
||||||
|
console.print("[red]✗ Some tests failed -- try again next session.[/red]")
|
||||||
|
return "failed"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Public entry point
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def run_coding_challenge(
|
||||||
|
item: CodeItem,
|
||||||
|
codebase_path: str,
|
||||||
|
user_explanation: str,
|
||||||
|
backend: Backend,
|
||||||
|
console: Console,
|
||||||
|
input_fn: Callable[[str], str] = input,
|
||||||
|
) -> str:
|
||||||
|
"""Offer the user a coding challenge after a PASS verdict.
|
||||||
|
|
||||||
|
Routes to one of two flows:
|
||||||
|
- **Existing tests found**: show tests, user writes implementation.
|
||||||
|
- **No tests found**: user writes tests first (LLM-rated), then implementation.
|
||||||
|
|
||||||
|
Only offered for ``.py`` files.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
item: The code item to challenge on.
|
||||||
|
codebase_path: Absolute path of the codebase root.
|
||||||
|
user_explanation: The explanation the user gave during the lesson.
|
||||||
|
backend: LLM backend (used for test quality rating in the no-tests flow).
|
||||||
|
console: Rich console for output.
|
||||||
|
input_fn: Callable for reading user input.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``"passed"``, ``"failed"``, or ``"skipped"``.
|
||||||
|
"""
|
||||||
|
if not item.file.endswith(".py"):
|
||||||
|
return "skipped"
|
||||||
|
|
||||||
|
codebase = Path(codebase_path)
|
||||||
|
test_entries = _find_tests(item, codebase)
|
||||||
|
|
||||||
|
if test_entries:
|
||||||
|
return _existing_tests_flow(
|
||||||
|
item, codebase_path, user_explanation, test_entries, console, input_fn
|
||||||
|
)
|
||||||
|
return _write_tests_first_flow(
|
||||||
|
item, codebase_path, user_explanation, backend, console, input_fn
|
||||||
|
)
|
||||||
36
python_pkg/code_tutor/_challenge_prompts.py
Normal file
36
python_pkg/code_tutor/_challenge_prompts.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
"""Static prompt and notice strings for the coding challenge.
|
||||||
|
|
||||||
|
Split out of :mod:`python_pkg.code_tutor._challenge` to keep it under the
|
||||||
|
250-line cap. These are pure data with no collaborators, so nothing patches
|
||||||
|
them and they can live anywhere.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
_NO_AI_NOTICE = (
|
||||||
|
"[bold yellow]⚠ No AI assistance -- write this yourself.[/bold yellow]\n"
|
||||||
|
"Your own explanation (and the tests below) are your only reference."
|
||||||
|
)
|
||||||
|
|
||||||
|
_MAX_TEST_ATTEMPTS = 2
|
||||||
|
|
||||||
|
_TEST_JUDGE_SYSTEM = (
|
||||||
|
"You are a code tutor evaluating whether a student's tests adequately"
|
||||||
|
" cover a function.\n\n"
|
||||||
|
"PASS if the tests:\n"
|
||||||
|
" - Include at least 2 meaningfully different test cases with distinct inputs\n"
|
||||||
|
" - Use assertions that verify the actual return value or observable behavior\n"
|
||||||
|
" - Would catch an obviously wrong implementation (e.g. one that always"
|
||||||
|
' returns "")\n\n'
|
||||||
|
"FAIL only if:\n"
|
||||||
|
" - There is only one trivial test case\n"
|
||||||
|
" - Assertions are always-true or don't check the function's real output\n"
|
||||||
|
" - All tests are essentially the same scenario with trivially different data\n\n"
|
||||||
|
"Do NOT require error/edge-case tests for pure transformation functions that"
|
||||||
|
" have no error handling. 2+ meaningful happy-path cases with distinct"
|
||||||
|
" inputs is enough.\n\n"
|
||||||
|
"Respond with valid JSON only, no other text:\n"
|
||||||
|
'{"verdict": "PASS" | "FAIL",'
|
||||||
|
' "gap": "<one sentence on the specific missing scenario,'
|
||||||
|
' or empty string on PASS>"}'
|
||||||
|
)
|
||||||
@ -11,19 +11,11 @@ challenge flows that consume it.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ast
|
import ast
|
||||||
import json
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import re
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from rich.live import Live
|
|
||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.syntax import Syntax
|
from rich.syntax import Syntax
|
||||||
from rich.text import Text
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
@ -31,7 +23,6 @@ if TYPE_CHECKING:
|
|||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
|
||||||
from python_pkg.code_tutor._analyzer import CodeItem
|
from python_pkg.code_tutor._analyzer import CodeItem
|
||||||
from python_pkg.code_tutor._llm import Backend
|
|
||||||
|
|
||||||
|
|
||||||
def _scan_test_file(source: str, item_name: str) -> list[str]:
|
def _scan_test_file(source: str, item_name: str) -> list[str]:
|
||||||
@ -186,162 +177,6 @@ def _project_root(start: Path) -> Path:
|
|||||||
return start.resolve()
|
return start.resolve()
|
||||||
|
|
||||||
|
|
||||||
def _pytest_clean(
|
|
||||||
test_ids_or_file: list[str],
|
|
||||||
project_root: Path,
|
|
||||||
console: Console,
|
|
||||||
extra_env: dict[str, str] | None = None,
|
|
||||||
) -> bool:
|
|
||||||
"""Run pytest on *test_ids_or_file* and return True if all pass.
|
|
||||||
|
|
||||||
Coverage is disabled so the project's ``fail_under`` threshold does not
|
|
||||||
interfere with isolated challenge runs.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
test_ids_or_file: Pytest node IDs or a single temp-file path.
|
|
||||||
project_root: Working directory for the pytest subprocess.
|
|
||||||
console: Rich console for output.
|
|
||||||
extra_env: Extra environment variables (e.g. PYTHONPATH override).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``True`` when all collected tests pass.
|
|
||||||
"""
|
|
||||||
env = {**os.environ, **(extra_env or {})}
|
|
||||||
result = subprocess.run(
|
|
||||||
[
|
|
||||||
sys.executable,
|
|
||||||
"-m",
|
|
||||||
"pytest",
|
|
||||||
*test_ids_or_file,
|
|
||||||
"-v",
|
|
||||||
"--tb=short",
|
|
||||||
"--no-header",
|
|
||||||
"-p",
|
|
||||||
"no:cov",
|
|
||||||
"--override-ini=addopts=",
|
|
||||||
],
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
cwd=str(project_root),
|
|
||||||
env=env,
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
output = (result.stdout + result.stderr).strip()
|
|
||||||
if output:
|
|
||||||
console.print(output)
|
|
||||||
return result.returncode == 0
|
|
||||||
|
|
||||||
|
|
||||||
def _patch_and_test(
|
|
||||||
item: CodeItem,
|
|
||||||
codebase_path: str,
|
|
||||||
user_code: str,
|
|
||||||
test_entries: list[tuple[Path, list[str]]],
|
|
||||||
console: Console,
|
|
||||||
) -> bool:
|
|
||||||
"""Replace *item* in source with *user_code*, run tests, then restore.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
item: Code item to patch.
|
|
||||||
codebase_path: Absolute codebase root path.
|
|
||||||
user_code: User's implementation text.
|
|
||||||
test_entries: ``(test_file, node_ids)`` pairs to run.
|
|
||||||
console: Rich console for output.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``True`` if all tests passed.
|
|
||||||
"""
|
|
||||||
source_file = Path(codebase_path) / item.file
|
|
||||||
original = source_file.read_text(encoding="utf-8")
|
|
||||||
orig_lines = original.splitlines()
|
|
||||||
|
|
||||||
before = orig_lines[: item.start_line - 1]
|
|
||||||
after = orig_lines[item.end_line :]
|
|
||||||
new_source = "\n".join(before + user_code.splitlines() + after) + "\n"
|
|
||||||
|
|
||||||
try:
|
|
||||||
ast.parse(new_source)
|
|
||||||
except SyntaxError as exc:
|
|
||||||
console.print(f"[red]Syntax error in your implementation: {exc}[/red]")
|
|
||||||
return False
|
|
||||||
|
|
||||||
test_ids = [f"{tf}::{nid}" for tf, nids in test_entries for nid in nids]
|
|
||||||
project_root = _project_root(Path(codebase_path))
|
|
||||||
|
|
||||||
try:
|
|
||||||
source_file.write_text(new_source, encoding="utf-8")
|
|
||||||
return _pytest_clean(test_ids, project_root, console)
|
|
||||||
finally:
|
|
||||||
source_file.write_text(original, encoding="utf-8")
|
|
||||||
|
|
||||||
|
|
||||||
def _stream_verdict(
|
|
||||||
system: str,
|
|
||||||
user_msg: str,
|
|
||||||
backend: Backend,
|
|
||||||
console: Console,
|
|
||||||
label: str = "Rating",
|
|
||||||
) -> str:
|
|
||||||
"""Stream an LLM call silently while showing an elapsed timer.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
system: System prompt for the judge.
|
|
||||||
user_msg: User message to judge.
|
|
||||||
backend: LLM backend with a ``stream(system, user, callback)`` method.
|
|
||||||
console: Rich console for the live timer.
|
|
||||||
label: Label prefix shown in the timer (e.g. ``"Rating"``).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Accumulated response text.
|
|
||||||
"""
|
|
||||||
parts: list[str] = []
|
|
||||||
start = time.monotonic()
|
|
||||||
|
|
||||||
def _on_token(token: str) -> None:
|
|
||||||
parts.append(token)
|
|
||||||
elapsed = int(time.monotonic() - start)
|
|
||||||
live.update(Text(f"{label}... {elapsed}s", style="yellow"))
|
|
||||||
|
|
||||||
with Live(
|
|
||||||
Text(f"{label}... 0s", style="yellow"),
|
|
||||||
console=console,
|
|
||||||
refresh_per_second=4,
|
|
||||||
transient=True,
|
|
||||||
) as live:
|
|
||||||
backend.stream(system, user_msg, _on_token)
|
|
||||||
|
|
||||||
return "".join(parts)
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_verdict(raw: str) -> tuple[str, str]:
|
|
||||||
"""Parse ``{"verdict": ..., "gap": ...}`` JSON from *raw*, tolerating fences.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
raw: Raw LLM response text.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``(verdict, gap)`` where verdict is ``"PASS"`` or ``"FAIL"``.
|
|
||||||
"""
|
|
||||||
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 judge response."
|
|
||||||
try:
|
|
||||||
data = json.loads(clean[start:end])
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
return "FAIL", "Could not parse judge response."
|
|
||||||
verdict = str(data.get("verdict", "FAIL")).upper()
|
|
||||||
if verdict not in {"PASS", "FAIL"}:
|
|
||||||
verdict = "FAIL"
|
|
||||||
return verdict, str(data.get("gap", ""))
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# "Write tests first" flow -- helpers
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _extract_signature_block(item: CodeItem, codebase_path: str) -> str:
|
def _extract_signature_block(item: CodeItem, codebase_path: str) -> str:
|
||||||
"""Return the function signature plus docstring, without the body.
|
"""Return the function signature plus docstring, without the body.
|
||||||
|
|
||||||
|
|||||||
111
python_pkg/code_tutor/_pytest_runner.py
Normal file
111
python_pkg/code_tutor/_pytest_runner.py
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
"""Running the user's tests in an isolated pytest subprocess.
|
||||||
|
|
||||||
|
Split out of :mod:`python_pkg.code_tutor._challenge_support` to keep it under
|
||||||
|
the 250-line cap. ``_challenge`` imports both entry points back, because
|
||||||
|
``tests/test_challenge_part3.py`` patches them on that module.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from python_pkg.code_tutor._challenge_support import _project_root
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from rich.console import Console
|
||||||
|
|
||||||
|
from python_pkg.code_tutor._analyzer import CodeItem
|
||||||
|
|
||||||
|
|
||||||
|
def _pytest_clean(
|
||||||
|
test_ids_or_file: list[str],
|
||||||
|
project_root: Path,
|
||||||
|
console: Console,
|
||||||
|
extra_env: dict[str, str] | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""Run pytest on *test_ids_or_file* and return True if all pass.
|
||||||
|
|
||||||
|
Coverage is disabled so the project's ``fail_under`` threshold does not
|
||||||
|
interfere with isolated challenge runs.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
test_ids_or_file: Pytest node IDs or a single temp-file path.
|
||||||
|
project_root: Working directory for the pytest subprocess.
|
||||||
|
console: Rich console for output.
|
||||||
|
extra_env: Extra environment variables (e.g. PYTHONPATH override).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``True`` when all collected tests pass.
|
||||||
|
"""
|
||||||
|
env = {**os.environ, **(extra_env or {})}
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
sys.executable,
|
||||||
|
"-m",
|
||||||
|
"pytest",
|
||||||
|
*test_ids_or_file,
|
||||||
|
"-v",
|
||||||
|
"--tb=short",
|
||||||
|
"--no-header",
|
||||||
|
"-p",
|
||||||
|
"no:cov",
|
||||||
|
"--override-ini=addopts=",
|
||||||
|
],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
cwd=str(project_root),
|
||||||
|
env=env,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
output = (result.stdout + result.stderr).strip()
|
||||||
|
if output:
|
||||||
|
console.print(output)
|
||||||
|
return result.returncode == 0
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_and_test(
|
||||||
|
item: CodeItem,
|
||||||
|
codebase_path: str,
|
||||||
|
user_code: str,
|
||||||
|
test_entries: list[tuple[Path, list[str]]],
|
||||||
|
console: Console,
|
||||||
|
) -> bool:
|
||||||
|
"""Replace *item* in source with *user_code*, run tests, then restore.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
item: Code item to patch.
|
||||||
|
codebase_path: Absolute codebase root path.
|
||||||
|
user_code: User's implementation text.
|
||||||
|
test_entries: ``(test_file, node_ids)`` pairs to run.
|
||||||
|
console: Rich console for output.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``True`` if all tests passed.
|
||||||
|
"""
|
||||||
|
source_file = Path(codebase_path) / item.file
|
||||||
|
original = source_file.read_text(encoding="utf-8")
|
||||||
|
orig_lines = original.splitlines()
|
||||||
|
|
||||||
|
before = orig_lines[: item.start_line - 1]
|
||||||
|
after = orig_lines[item.end_line :]
|
||||||
|
new_source = "\n".join(before + user_code.splitlines() + after) + "\n"
|
||||||
|
|
||||||
|
try:
|
||||||
|
ast.parse(new_source)
|
||||||
|
except SyntaxError as exc:
|
||||||
|
console.print(f"[red]Syntax error in your implementation: {exc}[/red]")
|
||||||
|
return False
|
||||||
|
|
||||||
|
test_ids = [f"{tf}::{nid}" for tf, nids in test_entries for nid in nids]
|
||||||
|
project_root = _project_root(Path(codebase_path))
|
||||||
|
|
||||||
|
try:
|
||||||
|
source_file.write_text(new_source, encoding="utf-8")
|
||||||
|
return _pytest_clean(test_ids, project_root, console)
|
||||||
|
finally:
|
||||||
|
source_file.write_text(original, encoding="utf-8")
|
||||||
89
python_pkg/code_tutor/_verdict.py
Normal file
89
python_pkg/code_tutor/_verdict.py
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
"""Streaming an LLM verdict behind an elapsed-time display, and parsing it.
|
||||||
|
|
||||||
|
Split out of :mod:`python_pkg.code_tutor._challenge_support` to keep it under
|
||||||
|
the 250-line cap. ``Live`` is imported here rather than there because this is
|
||||||
|
the only code that used it, and the tests patch it on whichever module the
|
||||||
|
call resolves through.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from rich.live import Live
|
||||||
|
from rich.text import Text
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from rich.console import Console
|
||||||
|
|
||||||
|
from python_pkg.code_tutor._llm import Backend
|
||||||
|
|
||||||
|
|
||||||
|
def _stream_verdict(
|
||||||
|
system: str,
|
||||||
|
user_msg: str,
|
||||||
|
backend: Backend,
|
||||||
|
console: Console,
|
||||||
|
label: str = "Rating",
|
||||||
|
) -> str:
|
||||||
|
"""Stream an LLM call silently while showing an elapsed timer.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
system: System prompt for the judge.
|
||||||
|
user_msg: User message to judge.
|
||||||
|
backend: LLM backend with a ``stream(system, user, callback)`` method.
|
||||||
|
console: Rich console for the live timer.
|
||||||
|
label: Label prefix shown in the timer (e.g. ``"Rating"``).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Accumulated response text.
|
||||||
|
"""
|
||||||
|
parts: list[str] = []
|
||||||
|
start = time.monotonic()
|
||||||
|
|
||||||
|
def _on_token(token: str) -> None:
|
||||||
|
parts.append(token)
|
||||||
|
elapsed = int(time.monotonic() - start)
|
||||||
|
live.update(Text(f"{label}... {elapsed}s", style="yellow"))
|
||||||
|
|
||||||
|
with Live(
|
||||||
|
Text(f"{label}... 0s", style="yellow"),
|
||||||
|
console=console,
|
||||||
|
refresh_per_second=4,
|
||||||
|
transient=True,
|
||||||
|
) as live:
|
||||||
|
backend.stream(system, user_msg, _on_token)
|
||||||
|
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_verdict(raw: str) -> tuple[str, str]:
|
||||||
|
"""Parse ``{"verdict": ..., "gap": ...}`` JSON from *raw*, tolerating fences.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
raw: Raw LLM response text.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``(verdict, gap)`` where verdict is ``"PASS"`` or ``"FAIL"``.
|
||||||
|
"""
|
||||||
|
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 judge response."
|
||||||
|
try:
|
||||||
|
data = json.loads(clean[start:end])
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return "FAIL", "Could not parse judge response."
|
||||||
|
verdict = str(data.get("verdict", "FAIL")).upper()
|
||||||
|
if verdict not in {"PASS", "FAIL"}:
|
||||||
|
verdict = "FAIL"
|
||||||
|
return verdict, str(data.get("gap", ""))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# "Write tests first" flow -- helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
@ -16,7 +16,7 @@ from rich.live import Live
|
|||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.text import Text
|
from rich.text import Text
|
||||||
|
|
||||||
from python_pkg.code_tutor._challenge import run_coding_challenge
|
from python_pkg.code_tutor._challenge_flows import run_coding_challenge
|
||||||
from python_pkg.code_tutor._progress import LessonRecord
|
from python_pkg.code_tutor._progress import LessonRecord
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
|||||||
@ -14,12 +14,11 @@ from unittest.mock import MagicMock, patch
|
|||||||
from python_pkg.code_tutor._challenge_support import (
|
from python_pkg.code_tutor._challenge_support import (
|
||||||
_collect_lines,
|
_collect_lines,
|
||||||
_find_tests,
|
_find_tests,
|
||||||
_patch_and_test,
|
|
||||||
_project_root,
|
_project_root,
|
||||||
_pytest_clean,
|
|
||||||
_scan_test_file,
|
_scan_test_file,
|
||||||
_show_test_panels,
|
_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
|
from python_pkg.code_tutor.tests.conftest import _item
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@ -205,7 +204,7 @@ def test_pytest_clean_pass() -> None:
|
|||||||
mock_result.stderr = ""
|
mock_result.stderr = ""
|
||||||
mock_console = MagicMock()
|
mock_console = MagicMock()
|
||||||
with patch(
|
with patch(
|
||||||
"python_pkg.code_tutor._challenge_support.subprocess.run",
|
"python_pkg.code_tutor._pytest_runner.subprocess.run",
|
||||||
return_value=mock_result,
|
return_value=mock_result,
|
||||||
):
|
):
|
||||||
assert (
|
assert (
|
||||||
@ -220,7 +219,7 @@ def test_pytest_clean_fail() -> None:
|
|||||||
mock_result.stderr = "FAILED"
|
mock_result.stderr = "FAILED"
|
||||||
mock_console = MagicMock()
|
mock_console = MagicMock()
|
||||||
with patch(
|
with patch(
|
||||||
"python_pkg.code_tutor._challenge_support.subprocess.run",
|
"python_pkg.code_tutor._pytest_runner.subprocess.run",
|
||||||
return_value=mock_result,
|
return_value=mock_result,
|
||||||
):
|
):
|
||||||
assert (
|
assert (
|
||||||
@ -236,7 +235,7 @@ def test_pytest_clean_no_output() -> None:
|
|||||||
mock_result.stderr = ""
|
mock_result.stderr = ""
|
||||||
mock_console = MagicMock()
|
mock_console = MagicMock()
|
||||||
with patch(
|
with patch(
|
||||||
"python_pkg.code_tutor._challenge_support.subprocess.run",
|
"python_pkg.code_tutor._pytest_runner.subprocess.run",
|
||||||
return_value=mock_result,
|
return_value=mock_result,
|
||||||
):
|
):
|
||||||
_pytest_clean([], Path("/proj"), mock_console)
|
_pytest_clean([], Path("/proj"), mock_console)
|
||||||
@ -270,9 +269,7 @@ def test_patch_and_test_passes(tmp_path: Path) -> None:
|
|||||||
test_file = tmp_path / "test_mod.py"
|
test_file = tmp_path / "test_mod.py"
|
||||||
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
|
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
|
||||||
mock_console = MagicMock()
|
mock_console = MagicMock()
|
||||||
with patch(
|
with patch("python_pkg.code_tutor._pytest_runner._pytest_clean", return_value=True):
|
||||||
"python_pkg.code_tutor._challenge_support._pytest_clean", return_value=True
|
|
||||||
):
|
|
||||||
result = _patch_and_test(
|
result = _patch_and_test(
|
||||||
_item(file="mod.py", start=1, end=2),
|
_item(file="mod.py", start=1, end=2),
|
||||||
str(tmp_path),
|
str(tmp_path),
|
||||||
@ -292,7 +289,7 @@ def test_patch_and_test_fails(tmp_path: Path) -> None:
|
|||||||
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
|
test_file.write_text("def test_fn(): pass\n", encoding="utf-8")
|
||||||
mock_console = MagicMock()
|
mock_console = MagicMock()
|
||||||
with patch(
|
with patch(
|
||||||
"python_pkg.code_tutor._challenge_support._pytest_clean", return_value=False
|
"python_pkg.code_tutor._pytest_runner._pytest_clean", return_value=False
|
||||||
):
|
):
|
||||||
result = _patch_and_test(
|
result = _patch_and_test(
|
||||||
_item(file="mod.py", start=1, end=2),
|
_item(file="mod.py", start=1, end=2),
|
||||||
|
|||||||
@ -18,9 +18,8 @@ from python_pkg.code_tutor._challenge import (
|
|||||||
from python_pkg.code_tutor._challenge_support import (
|
from python_pkg.code_tutor._challenge_support import (
|
||||||
_extract_signature_block,
|
_extract_signature_block,
|
||||||
_import_hint,
|
_import_hint,
|
||||||
_parse_verdict,
|
|
||||||
_stream_verdict,
|
|
||||||
)
|
)
|
||||||
|
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 _item, _make_live_mock
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@ -39,7 +38,7 @@ def test_stream_verdict_accumulates_tokens() -> None:
|
|||||||
|
|
||||||
mock_backend.stream.side_effect = fake_stream
|
mock_backend.stream.side_effect = fake_stream
|
||||||
|
|
||||||
with patch("python_pkg.code_tutor._challenge_support.Live", return_value=live_mock):
|
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
|
||||||
result = _stream_verdict("sys", "user", mock_backend, mock_console)
|
result = _stream_verdict("sys", "user", mock_backend, mock_console)
|
||||||
|
|
||||||
assert result == "" # parts is empty since on_token was never called by stream
|
assert result == "" # parts is empty since on_token was never called by stream
|
||||||
@ -59,7 +58,7 @@ def test_stream_verdict_on_token_called() -> None:
|
|||||||
|
|
||||||
mock_backend.stream.side_effect = fake_stream
|
mock_backend.stream.side_effect = fake_stream
|
||||||
|
|
||||||
with patch("python_pkg.code_tutor._challenge_support.Live", return_value=live_mock):
|
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
|
||||||
result = _stream_verdict(
|
result = _stream_verdict(
|
||||||
"sys", "user", mock_backend, mock_console, label="Test"
|
"sys", "user", mock_backend, mock_console, label="Test"
|
||||||
)
|
)
|
||||||
@ -212,7 +211,7 @@ def test_collect_and_rate_tests_skip() -> None:
|
|||||||
mock_console = MagicMock()
|
mock_console = MagicMock()
|
||||||
live_mock = _make_live_mock()
|
live_mock = _make_live_mock()
|
||||||
|
|
||||||
with patch("python_pkg.code_tutor._challenge_support.Live", return_value=live_mock):
|
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
|
||||||
result = _collect_and_rate_tests(
|
result = _collect_and_rate_tests(
|
||||||
"def fn():",
|
"def fn():",
|
||||||
"explanation",
|
"explanation",
|
||||||
@ -236,7 +235,7 @@ def test_collect_and_rate_tests_pass_first() -> None:
|
|||||||
mock_backend.stream.side_effect = fake_stream
|
mock_backend.stream.side_effect = fake_stream
|
||||||
lines_iter = iter(["test code line", "END"])
|
lines_iter = iter(["test code line", "END"])
|
||||||
|
|
||||||
with patch("python_pkg.code_tutor._challenge_support.Live", return_value=live_mock):
|
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
|
||||||
result = _collect_and_rate_tests(
|
result = _collect_and_rate_tests(
|
||||||
"def fn():",
|
"def fn():",
|
||||||
"explanation",
|
"explanation",
|
||||||
@ -264,7 +263,7 @@ def test_collect_and_rate_tests_fail_twice() -> None:
|
|||||||
]
|
]
|
||||||
inputs_iter = iter(attempt_inputs)
|
inputs_iter = iter(attempt_inputs)
|
||||||
|
|
||||||
with patch("python_pkg.code_tutor._challenge_support.Live", return_value=live_mock):
|
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
|
||||||
result = _collect_and_rate_tests(
|
result = _collect_and_rate_tests(
|
||||||
"def fn():",
|
"def fn():",
|
||||||
"explanation",
|
"explanation",
|
||||||
@ -297,7 +296,7 @@ def test_collect_and_rate_tests_fail_then_pass() -> None:
|
|||||||
|
|
||||||
inputs = iter(["bad test", "END", "good test", "END"])
|
inputs = iter(["bad test", "END", "good test", "END"])
|
||||||
|
|
||||||
with patch("python_pkg.code_tutor._challenge_support.Live", return_value=live_mock):
|
with patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock):
|
||||||
result = _collect_and_rate_tests(
|
result = _collect_and_rate_tests(
|
||||||
"def fn():",
|
"def fn():",
|
||||||
"explanation",
|
"explanation",
|
||||||
|
|||||||
@ -10,9 +10,9 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from python_pkg.code_tutor._challenge import (
|
from python_pkg.code_tutor._challenge import _run_user_impl
|
||||||
|
from python_pkg.code_tutor._challenge_flows import (
|
||||||
_existing_tests_flow,
|
_existing_tests_flow,
|
||||||
_run_user_impl,
|
|
||||||
_write_tests_first_flow,
|
_write_tests_first_flow,
|
||||||
run_coding_challenge,
|
run_coding_challenge,
|
||||||
)
|
)
|
||||||
@ -33,7 +33,7 @@ def test_run_user_impl_skip(tmp_path: Path) -> None:
|
|||||||
live_mock = _make_live_mock()
|
live_mock = _make_live_mock()
|
||||||
|
|
||||||
with (
|
with (
|
||||||
patch("python_pkg.code_tutor._challenge_support.Live", return_value=live_mock),
|
patch("python_pkg.code_tutor._verdict.Live", return_value=live_mock),
|
||||||
patch("python_pkg.code_tutor._challenge.Syntax"),
|
patch("python_pkg.code_tutor._challenge.Syntax"),
|
||||||
):
|
):
|
||||||
result = _run_user_impl(
|
result = _run_user_impl(
|
||||||
@ -151,10 +151,10 @@ def test_write_tests_first_flow_tests_none(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
with (
|
with (
|
||||||
patch(
|
patch(
|
||||||
"python_pkg.code_tutor._challenge._collect_and_rate_tests",
|
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
|
||||||
return_value=None,
|
return_value=None,
|
||||||
),
|
),
|
||||||
patch("python_pkg.code_tutor._challenge.Syntax"),
|
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
|
||||||
):
|
):
|
||||||
result = _write_tests_first_flow(
|
result = _write_tests_first_flow(
|
||||||
_item(file="mod.py"),
|
_item(file="mod.py"),
|
||||||
@ -174,14 +174,14 @@ def test_write_tests_first_flow_tests_fail_real(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
with (
|
with (
|
||||||
patch(
|
patch(
|
||||||
"python_pkg.code_tutor._challenge._collect_and_rate_tests",
|
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
|
||||||
return_value="test code",
|
return_value="test code",
|
||||||
),
|
),
|
||||||
patch(
|
patch(
|
||||||
"python_pkg.code_tutor._challenge._validate_tests_against_real",
|
"python_pkg.code_tutor._challenge_flows._validate_tests_against_real",
|
||||||
return_value=False,
|
return_value=False,
|
||||||
),
|
),
|
||||||
patch("python_pkg.code_tutor._challenge.Syntax"),
|
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
|
||||||
):
|
):
|
||||||
result = _write_tests_first_flow(
|
result = _write_tests_first_flow(
|
||||||
_item(file="mod.py"),
|
_item(file="mod.py"),
|
||||||
@ -201,18 +201,18 @@ def test_write_tests_first_flow_success(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
with (
|
with (
|
||||||
patch(
|
patch(
|
||||||
"python_pkg.code_tutor._challenge._collect_and_rate_tests",
|
"python_pkg.code_tutor._challenge_flows._collect_and_rate_tests",
|
||||||
return_value="test code",
|
return_value="test code",
|
||||||
),
|
),
|
||||||
patch(
|
patch(
|
||||||
"python_pkg.code_tutor._challenge._validate_tests_against_real",
|
"python_pkg.code_tutor._challenge_flows._validate_tests_against_real",
|
||||||
return_value=True,
|
return_value=True,
|
||||||
),
|
),
|
||||||
patch(
|
patch(
|
||||||
"python_pkg.code_tutor._challenge._run_user_impl",
|
"python_pkg.code_tutor._challenge_flows._run_user_impl",
|
||||||
return_value="passed",
|
return_value="passed",
|
||||||
),
|
),
|
||||||
patch("python_pkg.code_tutor._challenge.Syntax"),
|
patch("python_pkg.code_tutor._challenge_flows.Syntax"),
|
||||||
):
|
):
|
||||||
result = _write_tests_first_flow(
|
result = _write_tests_first_flow(
|
||||||
_item(file="mod.py"),
|
_item(file="mod.py"),
|
||||||
@ -279,7 +279,9 @@ def test_existing_tests_flow_passes(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
with (
|
with (
|
||||||
patch("python_pkg.code_tutor._challenge_support.Syntax"),
|
patch("python_pkg.code_tutor._challenge_support.Syntax"),
|
||||||
patch("python_pkg.code_tutor._challenge._patch_and_test", return_value=True),
|
patch(
|
||||||
|
"python_pkg.code_tutor._challenge_flows._patch_and_test", return_value=True
|
||||||
|
),
|
||||||
):
|
):
|
||||||
result = _existing_tests_flow(
|
result = _existing_tests_flow(
|
||||||
_item(file="mod.py"),
|
_item(file="mod.py"),
|
||||||
@ -303,7 +305,9 @@ def test_existing_tests_flow_fails(tmp_path: Path) -> None:
|
|||||||
|
|
||||||
with (
|
with (
|
||||||
patch("python_pkg.code_tutor._challenge_support.Syntax"),
|
patch("python_pkg.code_tutor._challenge_support.Syntax"),
|
||||||
patch("python_pkg.code_tutor._challenge._patch_and_test", return_value=False),
|
patch(
|
||||||
|
"python_pkg.code_tutor._challenge_flows._patch_and_test", return_value=False
|
||||||
|
),
|
||||||
):
|
):
|
||||||
result = _existing_tests_flow(
|
result = _existing_tests_flow(
|
||||||
_item(file="mod.py"),
|
_item(file="mod.py"),
|
||||||
@ -342,7 +346,8 @@ def test_run_coding_challenge_with_existing_tests(tmp_path: Path) -> None:
|
|||||||
mock_backend = MagicMock()
|
mock_backend = MagicMock()
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"python_pkg.code_tutor._challenge._existing_tests_flow", return_value="passed"
|
"python_pkg.code_tutor._challenge_flows._existing_tests_flow",
|
||||||
|
return_value="passed",
|
||||||
):
|
):
|
||||||
result = run_coding_challenge(
|
result = run_coding_challenge(
|
||||||
_item(file="mod.py"),
|
_item(file="mod.py"),
|
||||||
@ -360,7 +365,7 @@ def test_run_coding_challenge_no_tests(tmp_path: Path) -> None:
|
|||||||
mock_backend = MagicMock()
|
mock_backend = MagicMock()
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"python_pkg.code_tutor._challenge._write_tests_first_flow",
|
"python_pkg.code_tutor._challenge_flows._write_tests_first_flow",
|
||||||
return_value="skipped",
|
return_value="skipped",
|
||||||
):
|
):
|
||||||
result = run_coding_challenge(
|
result = run_coding_challenge(
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user