File size: 7,461 Bytes
339ddd8
 
 
 
e1de134
 
339ddd8
 
 
 
2a9dc4c
339ddd8
 
 
 
 
 
 
e1de134
339ddd8
e1de134
c35ac38
 
 
 
 
2a9dc4c
 
339ddd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
339ddd8
 
2a9dc4c
339ddd8
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""Tests for PythonLanguageAdapter, StrictPythonLanguageAdapter, and codex loading."""

from __future__ import annotations

import codecs
import sys
from pathlib import Path

import pytest

from lingologos_codex.adapter_contract import (
    ADAPTER_SPEC_VERSION,
    CommandLanguageAdapter,
    WorkspaceBoundaryError,
    check_adapter_contract,
    load_adapter_from_file,
    load_adapter_from_ref,
)
from lingologos_codex.types import ABSTAIN, CONFIRMED, GateResult, REJECTED

from lingologos_python import gates as gates_module
from lingologos_python.adapter import (
    GATE_TIMEOUT_ENV,
    PythonLanguageAdapter,
    StrictPythonLanguageAdapter,
)
from lingologos_python.ast_graph import discover_python_files
from lingologos_python.gates import resolve_tool_gate_prefix


def test_python_adapter_passes_full_codex_contract(sample_pkg: Path) -> None:
    adapter = PythonLanguageAdapter(sample_pkg)
    files = discover_python_files(sample_pkg)
    violations = check_adapter_contract(adapter, str(sample_pkg), files)
    assert violations == []


def test_adapter_metadata_and_env(sample_pkg: Path) -> None:
    adapter = PythonLanguageAdapter(sample_pkg)
    meta = adapter.meta()
    assert meta.name == "lingologos-python"
    assert meta.languages == ("python",)
    assert ".py" in meta.extensions
    assert meta.spec_version == ADAPTER_SPEC_VERSION
    env = adapter.command_env()
    assert env["PYTHONDONTWRITEBYTECODE"] == "1"
    assert str(sample_pkg.resolve()) in env["PYTHONPATH"]


def test_syntax_gate_rejects_broken_python_file(sample_pkg: Path) -> None:
    broken = sample_pkg / "src" / "broken.py"
    broken.write_text("def bad(:\n    return 1\n", encoding="utf-8")

    adapter = PythonLanguageAdapter(sample_pkg)
    gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/broken.py"])
    assert len(gates) == 1
    assert gates[0].verdict == REJECTED
    assert "src/broken.py" in gates[0].failed_targets


def test_strict_adapter_abstains_when_tool_is_missing(sample_pkg: Path) -> None:
    adapter = StrictPythonLanguageAdapter(sample_pkg)
    gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/mathops.py"])
    assert gates[0].verdict == CONFIRMED
    for tool_name, gate in zip(("mypy", "ruff"), gates[1:]):
        if resolve_tool_gate_prefix(tool_name) is None:
            assert gate.verdict == ABSTAIN
            assert tool_name in gate.note


def test_custom_missing_tool_always_abstains(sample_pkg: Path) -> None:
    adapter = PythonLanguageAdapter(sample_pkg, require_tools=("nonexistent_checker_xyz",))
    gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/mathops.py"])
    assert gates[0].verdict == CONFIRMED
    assert gates[1].verdict == ABSTAIN
    assert "nonexistent_checker_xyz" in gates[1].note


def test_workspace_escape_is_refused(sample_pkg: Path) -> None:
    adapter = PythonLanguageAdapter(sample_pkg)
    with pytest.raises(WorkspaceBoundaryError):
        adapter.run_tests("..", [], full_suite=True)


def test_load_adapter_via_codex_ref_and_declarative_spec(sample_pkg: Path) -> None:
    python_root = Path(__file__).resolve().parent.parent

    by_module = load_adapter_from_ref("lingologos_python.adapter:PythonLanguageAdapter", sample_pkg)
    assert isinstance(by_module, PythonLanguageAdapter)

    adapter_file = python_root / "lingologos_python" / "adapter.py"
    by_file = load_adapter_from_ref(f"{adapter_file}:PythonLanguageAdapter", sample_pkg)
    assert by_file.meta().name == "lingologos-python"

    spec_adapter = load_adapter_from_file(python_root / "codex.python.json", sample_pkg)
    assert isinstance(spec_adapter, CommandLanguageAdapter)
    assert spec_adapter.meta().languages == ("python",)


def test_syntax_gate_compiles_a_file_that_starts_with_a_byte_order_mark(sample_pkg: Path) -> None:
    marked = sample_pkg / "src" / "marked.py"
    marked.write_bytes(codecs.BOM_UTF8 + b"def go() -> int:\n    return 1\n")

    adapter = PythonLanguageAdapter(sample_pkg)
    gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/marked.py"])
    assert gates[0].verdict == CONFIRMED, gates[0].output


def test_syntax_gate_abstains_on_a_file_that_is_not_utf8_text(sample_pkg: Path) -> None:
    garbled = sample_pkg / "src" / "garbled.py"
    garbled.write_bytes(b"def caf\xe9():\n    pass\n")

    adapter = PythonLanguageAdapter(sample_pkg)
    gates = adapter.run_typecheck_and_lint(str(sample_pkg), ["src/garbled.py"])
    assert gates[0].verdict == ABSTAIN
    assert "UTF-8" in gates[0].note


class _RecordingRunner:
    """A stand-in adapter that records the argv the gate chose for the fallback runner."""

    def __init__(self, output: str) -> None:
        self.argvs = []
        self._output = output

    def run_command(self, cwd: str, argv, gate_name: str = "") -> GateResult:
        self.argvs.append(list(argv))
        return GateResult(REJECTED, " ".join(argv), output=self._output)


def test_unittest_fallback_imports_test_modules_and_abstains_on_an_empty_run(
    sample_pkg: Path, monkeypatch
) -> None:
    """Paths are not import names, and an empty unittest run carries no verdict.

    On this host the fallback received tests/test_mathops.py, could not import it,
    and the gate reported a failure the code never caused. Importable names and a
    named abstention are the honest shape of that fallback.
    """
    monkeypatch.setattr(gates_module.shutil, "which", lambda name: None)
    monkeypatch.setattr(gates_module, "has_python_module", lambda name: name == "unittest")
    runner = _RecordingRunner("Ran 0 tests in 0.000s\nNO TESTS RAN\n")

    gate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test_mathops.py"])
    assert runner.argvs == [[sys.executable, "-m", "unittest", "-q", "tests.test_mathops"]]
    assert gate.verdict == ABSTAIN


def test_unittest_fallback_refuses_targets_it_cannot_name(sample_pkg: Path, monkeypatch) -> None:
    monkeypatch.setattr(gates_module.shutil, "which", lambda name: None)
    monkeypatch.setattr(gates_module, "has_python_module", lambda name: name == "unittest")
    runner = _RecordingRunner("")

    gate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test-mathops.py"])
    assert runner.argvs == []
    assert gate.verdict == ABSTAIN
    assert "not importable module names" in gate.note


def test_a_runner_that_collected_nothing_abstains_under_pytest_too(
    sample_pkg: Path, monkeypatch
) -> None:
    monkeypatch.setattr(gates_module, "has_python_module", lambda name: name == "pytest")
    runner = _RecordingRunner("no tests ran in 0.01s\n")

    gate = gates_module.run_python_tests(runner, sample_pkg, ["tests/test_mathops.py"])
    assert gate.verdict == ABSTAIN
    assert "collected no tests" in gate.note


def test_the_gate_budget_arrives_through_the_environment(sample_pkg: Path, monkeypatch) -> None:
    """The kernel builds the adapter from a ref string, so its budget comes from the environment."""
    monkeypatch.setenv(GATE_TIMEOUT_ENV, "7.5")
    assert PythonLanguageAdapter(sample_pkg).timeout_sec == 7.5
    assert StrictPythonLanguageAdapter(sample_pkg).timeout_sec == 7.5
    monkeypatch.delenv(GATE_TIMEOUT_ENV)
    assert PythonLanguageAdapter(sample_pkg).timeout_sec == 120.0
    assert PythonLanguageAdapter(sample_pkg, timeout_sec=5.0).timeout_sec == 5.0
    monkeypatch.setenv(GATE_TIMEOUT_ENV, "not a number")
    assert PythonLanguageAdapter(sample_pkg).timeout_sec == 120.0