Download tests/test_patterns.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/main/tests/test_patterns.py
- Command line
-
hf download hf://datasets/tailot/codex-python/tests/test_patterns.py
-
curl -L -o test_patterns.py https://huggingface.co/datasets/tailot/codex-python/resolve/main/tests/test_patterns.py
14.3 kB
| """Tests for the pattern catalog: what a card claims, and what a plan reports.""" | |
| from __future__ import annotations | |
| import json | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| from typing import Any, Dict, List | |
| from lingologos_codex.casecorpus import read_rows, validate_case_rows | |
| from lingologos_python.patterns import ( | |
| FAMILIES, | |
| PATTERNS, | |
| PATTERN_IDS, | |
| SHARED_REFUSALS, | |
| PatternSpec, | |
| pattern_card, | |
| plan_pattern, | |
| render_card, | |
| scan_pattern, | |
| split_target, | |
| TARGET_SEPARATOR, | |
| ) | |
| from lingologos_python.rules import RULE_IDS | |
| ROOT = Path(__file__).resolve().parents[1] | |
| LAB = ROOT / "fixtures" / "pattern_lab" | |
| CASES = ROOT / "patterns" / "pattern_cases.jsonl" | |
| COVERAGE = ROOT / "patterns" / "coverage.json" | |
| POSITIVE = { | |
| "annotate-literal-defaults": "src/tokens.py::count_words", | |
| "bare-assert-to-explicit-raise": "src/guards.py::open_ticket", | |
| "bare-except-to-narrow-exception": "src/retries.py::call_or_none", | |
| "chain-to-registry": "src/registry.py::render", | |
| "drop-unused-imports": "src/legacy.py::read_size", | |
| "empty-len-to-truthiness": "src/baskets.py::describe", | |
| "init-missing-super": "src/widgets.py::Box.__init__", | |
| "mutable-default-to-none": "src/slugify.py::add_tag", | |
| "none-comparison-to-identity": "src/labels.py::label_for", | |
| "open-to-context-manager": "src/notes.py::read_note", | |
| } | |
| NEGATIVE = { | |
| "annotate-literal-defaults": "src/tokens.py::count_lines", | |
| "bare-assert-to-explicit-raise": "src/guards.py::close_ticket", | |
| "bare-except-to-narrow-exception": "src/retries.py::call_or_note", | |
| "chain-to-registry": "src/registry.py::render_pair", | |
| "drop-unused-imports": "src/tokens.py::count_words", | |
| "empty-len-to-truthiness": "src/baskets.py::first_or_none", | |
| "init-missing-super": "src/widgets.py::Shutter.__init__", | |
| "mutable-default-to-none": "src/slugify.py::join_parts", | |
| "none-comparison-to-identity": "src/labels.py::is_missing", | |
| "open-to-context-manager": "src/notes.py::write_note", | |
| } | |
| # The five cards that vouch for coroutines carry a second pair over an async def; the | |
| # other five answer ASYNC_TARGET for one and say so on the card. | |
| COROUTINE_POSITIVE = { | |
| "annotate-literal-defaults": "src/asyncops.py::render_page", | |
| "bare-assert-to-explicit-raise": "src/asyncops.py::check_name", | |
| "empty-len-to-truthiness": "src/asyncops.py::word_total", | |
| "mutable-default-to-none": "src/asyncops.py::gather", | |
| "none-comparison-to-identity": "src/asyncops.py::describe", | |
| } | |
| COROUTINE_NEGATIVE = { | |
| "annotate-literal-defaults": "src/asyncops.py::sized", | |
| "bare-assert-to-explicit-raise": "src/asyncops.py::check_after", | |
| "empty-len-to-truthiness": "src/asyncops.py::item_count", | |
| "mutable-default-to-none": "src/asyncops.py::plain", | |
| "none-comparison-to-identity": "src/asyncops.py::present", | |
| } | |
| COROUTINE_LOCKED = {"mutable-default-to-none", "bare-assert-to-explicit-raise"} | |
| def _card(pattern_id: str) -> PatternSpec: | |
| return pattern_card(pattern_id) | |
| def _reason_codes() -> List[str]: | |
| from lingologos_python import rules | |
| return [name for name in dir(rules) if name.isupper() and "_" in name] | |
| def test_each_card_states_the_shape_it_claims_and_the_lock_it_writes() -> None: | |
| assert sorted(PATTERNS) == list(PATTERN_IDS) | |
| for pattern_id in PATTERN_IDS: | |
| spec = _card(pattern_id) | |
| assert spec.family in FAMILIES | |
| assert spec.rule in RULE_IDS | |
| assert spec.shape and spec.rationale and spec.lock_claims | |
| assert spec.preconditions, "%s claims a shape with no stated precondition" % pattern_id | |
| assert spec.intent_tags and spec.companions | |
| assert spec.min_assurance >= 2 | |
| def test_the_refusals_a_card_lists_are_codes_its_rule_can_give() -> None: | |
| known = set(_reason_codes()) | |
| for pattern_id in PATTERN_IDS: | |
| spec = _card(pattern_id) | |
| assert spec.refuses_as, "%s states no refusal" % pattern_id | |
| for code in spec.refuses_as: | |
| assert code in known, "%s names %s, which no rule of this bundle gives" % (pattern_id, code) | |
| def test_a_target_label_splits_into_the_file_and_the_function_it_names() -> None: | |
| assert split_target("src/notes.py::read_note") == ("src/notes.py", "read_note") | |
| assert split_target("src\\notes.py::read_note") == ("src/notes.py", "read_note") | |
| for broken in ("src/notes.py", "src/notes.py::", "::read_note"): | |
| try: | |
| split_target(broken) | |
| except ValueError: | |
| continue | |
| raise AssertionError("'%s' is not a target label" % broken) | |
| assert TARGET_SEPARATOR == "::" | |
| def test_a_card_that_is_not_in_the_catalog_is_named_as_missing() -> None: | |
| try: | |
| pattern_card("rename-the-module") | |
| except KeyError as exc: | |
| assert "rename-the-module" in str(exc) | |
| return | |
| raise AssertionError("an unknown card was accepted") | |
| def test_a_plan_that_applies_reports_the_files_it_would_write() -> None: | |
| for pattern_id in PATTERN_IDS: | |
| plan = plan_pattern(LAB, pattern_id, POSITIVE[pattern_id]) | |
| assert not plan.refused, plan.detail | |
| assert plan.min_assurance == _card(pattern_id).min_assurance | |
| assert plan.evidence, "%s applied without saying why" % pattern_id | |
| assert len(plan.edits) == 2 | |
| assert plan.primary().file in plan.files | |
| assert plan.files == tuple(edit.file for edit in plan.edits) | |
| assert plan.target.endswith(TARGET_SEPARATOR + POSITIVE[pattern_id].split(TARGET_SEPARATOR)[1]) | |
| summary = plan.summary() | |
| assert pattern_id in summary and "writes" in summary | |
| def test_a_plan_that_refuses_reports_the_code_its_rule_gave() -> None: | |
| for pattern_id in PATTERN_IDS: | |
| plan = plan_pattern(LAB, pattern_id, NEGATIVE[pattern_id]) | |
| assert plan.refused | |
| assert plan.edits == () | |
| assert plan.files == () | |
| assert plan.reason_code in _card(pattern_id).refuses_as | |
| assert plan.detail, "%s refused without a sentence explaining it" % pattern_id | |
| try: | |
| plan.primary() | |
| except ValueError: | |
| pass | |
| else: | |
| raise AssertionError("a refused plan claimed an edit") | |
| def test_the_catalog_refuses_to_choose_between_two_functions_of_the_same_shape() -> None: | |
| plan = plan_pattern(LAB, "annotate-literal-defaults") | |
| assert plan.refused | |
| assert plan.reason_code == "AMBIGUOUS_TARGET" | |
| for target in [label for label, _hit in scan_pattern(LAB, "annotate-literal-defaults")]: | |
| assert target in plan.detail | |
| def test_scan_names_every_function_of_a_workspace_a_card_claims() -> None: | |
| for pattern_id in PATTERN_IDS: | |
| found = [label for label, _hit in scan_pattern(LAB, pattern_id)] | |
| assert POSITIVE[pattern_id] in found, "%s does not find the function planted for it" % pattern_id | |
| assert NEGATIVE[pattern_id] not in found, "%s finds the function planted to be refused" % pattern_id | |
| if pattern_id in COROUTINE_POSITIVE: | |
| assert COROUTINE_POSITIVE[pattern_id] in found, "%s misses the coroutine planted for it" % pattern_id | |
| assert COROUTINE_NEGATIVE[pattern_id] not in found | |
| only_one = scan_pattern(LAB, "open-to-context-manager") | |
| assert [label for label, _hit in only_one] == ["src/notes.py::read_note"] | |
| def test_a_card_written_as_a_row_validates_against_the_kernel_schema() -> None: | |
| rows: List[Dict[str, object]] = [] | |
| for pattern_id in PATTERN_IDS: | |
| rows.append(plan_pattern(LAB, pattern_id, POSITIVE[pattern_id]).to_row("pos-%s" % pattern_id)) | |
| rows.append(plan_pattern(LAB, pattern_id, NEGATIVE[pattern_id]).to_row("neg-%s" % pattern_id)) | |
| assert validate_case_rows(rows) == [] | |
| for row in rows[:1] + rows[1:2]: | |
| assert row["language"] == "python" | |
| assert row["pattern_id"] in PATTERN_IDS | |
| assert row["rule"] == row["pattern_id"] | |
| assert row["intent_tags"] == sorted(_card(str(row["pattern_id"])).intent_tags) | |
| assert row["note"] == _card(str(row["pattern_id"])).shape | |
| assert int(row["min_assurance"]) == _card(str(row["pattern_id"])).min_assurance | |
| for row in rows: | |
| if row["expect"] == "REFUSED": | |
| assert row["edits"] == [] | |
| assert str(row["reason_code"]) in _card(str(row["pattern_id"])).refuses_as | |
| else: | |
| assert len(row["edits"]) == 2 | |
| assert row.get("reason_code", "") == "" | |
| def test_a_card_renders_as_a_card_a_person_can_read() -> None: | |
| text = render_card(_card("chain-to-registry")) | |
| assert text.startswith("chain-to-registry") | |
| for part in ("family", "shape", "why", "needs", "companion", "lock", "refuses", "assurance"): | |
| assert part in text | |
| assert "adding a kind means editing the middle of a chain" in text | |
| def test_the_corpus_on_disk_is_what_the_rules_generate() -> None: | |
| proc = subprocess.run( | |
| [sys.executable, "-B", str(ROOT / "tools" / "build_patterns.py"), "--check"], | |
| cwd=str(ROOT), | |
| capture_output=True, | |
| text=True, | |
| ) | |
| assert proc.returncode == 0, proc.stdout + proc.stderr | |
| assert "PATTERNS: CONFIRMED" in proc.stdout | |
| def test_the_corpus_holds_a_pair_for_every_card_and_validates() -> None: | |
| rows = read_rows(CASES) | |
| assert validate_case_rows(rows) == [] | |
| assert len(rows) == 2 * len(PATTERNS) + 2 * len(COROUTINE_POSITIVE) | |
| for pattern_id in PATTERN_IDS: | |
| positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"] | |
| negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"] | |
| expected = [POSITIVE[pattern_id]] | |
| expected_negative = [NEGATIVE[pattern_id]] | |
| if pattern_id in COROUTINE_POSITIVE: | |
| expected.append(COROUTINE_POSITIVE[pattern_id]) | |
| expected_negative.append(COROUTINE_NEGATIVE[pattern_id]) | |
| assert [str(row["targets"][0]) for row in positive] == expected | |
| assert [str(row["targets"][0]) for row in negative] == expected_negative | |
| for row in positive: | |
| assert len(row["edits"]) == 2 | |
| def test_the_coroutine_pairs_plan_over_coroutines_and_the_lock_waits_where_it_calls() -> None: | |
| for pattern_id in COROUTINE_POSITIVE: | |
| plan = plan_pattern(LAB, pattern_id, COROUTINE_POSITIVE[pattern_id]) | |
| assert not plan.refused, plan.detail | |
| assert len(plan.edits) == 2 | |
| companion = plan.edits[1] | |
| if pattern_id in COROUTINE_LOCKED: | |
| assert "asyncio.run(" in companion.replace | |
| assert "import asyncio" in companion.replace | |
| for pattern_id, target in COROUTINE_NEGATIVE.items(): | |
| plan = plan_pattern(LAB, pattern_id, target) | |
| assert plan.refused | |
| def test_the_cards_without_a_coroutine_pair_answer_async_target() -> None: | |
| for pattern_id in ("chain-to-registry", "open-to-context-manager", "bare-except-to-narrow-exception"): | |
| plan = plan_pattern(LAB, pattern_id, "src/asyncops.py::describe") | |
| assert plan.refused | |
| assert plan.reason_code == "ASYNC_TARGET" | |
| assert "ASYNC_TARGET" in _card(pattern_id).refuses_as | |
| def test_the_constructor_card_claims_only_a_self_only_constructor_without_the_chain() -> None: | |
| for target, code in ( | |
| ("src/widgets.py::Grille.__init__", "INIT_TAKES_MORE_THAN_SELF"), | |
| ("src/widgets.py::NoSuch.__init__", "NO_SUCH_CLASS"), | |
| ("src/widgets.py::Box.area", "NOT_A_METHOD"), | |
| ): | |
| plan = plan_pattern(LAB, "init-missing-super", target) | |
| assert plan.refused, "%s was applied" % target | |
| assert plan.reason_code == code, "%s refused with %s" % (target, plan.reason_code) | |
| def test_the_unused_import_card_removes_only_the_line_no_other_line_reads() -> None: | |
| plan = plan_pattern(LAB, "drop-unused-imports", "src/legacy.py::read_size") | |
| assert not plan.refused, plan.detail | |
| assert plan.primary().replace == "" | |
| assert "json" in plan.primary().search | |
| assert "os" not in plan.primary().search | |
| assert plan.edits[1].replace.count("def test_read_size_keeps_no_unread_imports") == 1 | |
| def test_coverage_states_the_fixture_as_its_denominator() -> None: | |
| payload = json.loads(COVERAGE.read_text(encoding="utf-8")) | |
| assert payload["fixture"] == "fixtures/pattern_lab" | |
| assert "not over Python" in payload["denominator"] | |
| assert payload["rows"] == len(read_rows(CASES)) | |
| assert sorted(str(entry["pattern_id"]) for entry in payload["patterns"]) == list(PATTERN_IDS) | |
| for entry in payload["patterns"]: | |
| pattern_id = str(entry["pattern_id"]) | |
| pair_count = 2 if pattern_id in COROUTINE_POSITIVE else 1 | |
| assert entry["positive_rows"] == pair_count and entry["negative_rows"] == pair_count | |
| assert POSITIVE[pattern_id] in entry["targets_in_shape"] | |
| rows_for_card = [ | |
| row for row in read_rows(CASES) | |
| if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED" | |
| ] | |
| assert entry["refusals_recorded"] == sorted(str(row.get("reason_code", "")) for row in rows_for_card) | |
| for code in entry["refusals_recorded"]: | |
| assert code in _card(pattern_id).refuses_as | |
| def test_every_card_lists_the_refusals_a_plan_can_answer_with() -> None: | |
| for pattern_id in PATTERN_IDS: | |
| card = _card(pattern_id) | |
| for code in SHARED_REFUSALS: | |
| assert code in card.refuses_as | |
| assert len(set(card.refuses_as)) == len(card.refuses_as) | |
| def test_a_rule_that_breaks_while_building_its_anchors_ends_in_a_named_refusal(tmp_path: Path, monkeypatch) -> None: | |
| from lingologos_python import rules | |
| root = tmp_path / "ws" | |
| (root / "src").mkdir(parents=True) | |
| (root / "tests").mkdir(parents=True) | |
| (root / "src" / "widget.py").write_text("def pick(items=[]):\n return items\n", encoding="utf-8", newline="\n") | |
| (root / "tests" / "test_widget.py").write_text( | |
| "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n", | |
| encoding="utf-8", | |
| newline="\n", | |
| ) | |
| def colliding(target: Any) -> Any: | |
| raise ValueError("the anchors of this rule overlap") | |
| monkeypatch.setitem(rules.RULES, "mutable-default-to-none", colliding) | |
| plan = plan_pattern(root, "mutable-default-to-none", "src/widget.py::pick") | |
| assert plan.refused | |
| assert plan.reason_code == rules.ANCHOR_OVERLAP | |