From 672e71194acf1f9a7329a70aa9e00366cdcc4830 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 28 Oct 2026 14:50:37 +0000 Subject: [PATCH 1/3] Fail CI on dead code and pytest 7.4 attribute hedges The Oct 22 simplicity pass found an unread stderr ring buffer and getattr hedges on attributes pytest>=7.4 already guarantees. Vulture misses the buffer because append and len count as uses, and mypy --strict does not flag getattr-with-default. AST checks now fail on those examples and pass once the buffer is deleted and the attributes are read directly. Drop the remaining hedges that check still finds: item.name, report.failed, report.skipped, and report.nodeid. Co-authored-by: Nate Vick --- .github/workflows/ci.yml | 13 ++ AGENTS.md | 15 ++ src/selective_pytest/plugin.py | 9 +- src/selective_pytest/reporters.py | 2 +- tests/test_simplicity_checks.py | 207 ++++++++++++++++++++ tools/__init__.py | 0 tools/check_dead_code.py | 310 ++++++++++++++++++++++++++++++ tools/check_pytest_contract.py | 137 +++++++++++++ 8 files changed, 687 insertions(+), 6 deletions(-) create mode 100644 AGENTS.md create mode 100644 tests/test_simplicity_checks.py create mode 100644 tools/__init__.py create mode 100644 tools/check_dead_code.py create mode 100644 tools/check_pytest_contract.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c0f667..da218a5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,19 @@ on: schedule: - cron: "0 6 * * 1" jobs: + lint: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: dead code and pytest contract + run: | + python3 -m pip install "pytest==7.4.4" + python3 tools/check_dead_code.py + python3 tools/check_pytest_contract.py + python3 -m pytest tests/test_simplicity_checks.py transport: runs-on: ubuntu-24.04 env: diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b7742aa --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,15 @@ +# Agent rules + +Each rule is paired with the check that enforces it. Run the command locally; CI runs the same command. + +| Rule | Check | Command | Review finding | +| --- | --- | --- | --- | +| Do not keep code with no caller. An attribute that is only assigned, appended, or length-capped is dead. Do not duck-type `LogXML` or wrap `get_plugin` / `stash.get` in `try/except Exception: pass`, and do not call `get_plugin("html")`. | `tools/check_dead_code.py` | `python3 tools/check_dead_code.py` | Simplicity pass on selectiveci/selective-python-pytest#1 at `6fa455b`, finding #4 (`transport.py` stderr ring buffer) and finding #1 (dead plugin lookups) | +| Pin `pytest>=7.4`. Access attributes that version guarantees (`path`, `location`, `name`, `nodeid`, `duration`, `failed`, `skipped`, `passed`, `when`, `outcome`, `longrepr`, `keywords`) directly. Call `SetupState.teardown_exact` with one argument; do not catch `TypeError` to retry a pytest 6 arity. | `tools/check_pytest_contract.py` | `python3 tools/check_pytest_contract.py` | Same pass, finding #7 (`getattr` hedges on item and report) and finding #5 (pytest 6 arity shims) | + +An exception belongs on the offending line and must include a reason. `# noqa: dead-code ` or `# noqa: pytest-contract `. A bare marker does not suppress the finding. + +These hedges are judgment calls. Not enforced: + +- `getattr(item, "originalname", item.name)` — `originalname` is not on every item. +- `getattr(config.option, "numprocesses" / "stepwise" / "stepwise_skip" / "setuponly" / "cov_context", ...)` — those options exist only when the plugin is loaded. diff --git a/src/selective_pytest/plugin.py b/src/selective_pytest/plugin.py index fd7a754..8914293 100644 --- a/src/selective_pytest/plugin.py +++ b/src/selective_pytest/plugin.py @@ -88,17 +88,16 @@ def _line_number(item): def _description(item): - name = getattr(item, "name", "") or item.nodeid - return clean_text(name) + return clean_text(item.name or item.nodeid) def _fold(reports): phases = [reports.get("setup"), reports.get("call"), reports.get("teardown")] phases = [report for report in phases if report is not None] - failed = [report for report in phases if getattr(report, "failed", False)] + failed = [report for report in phases if report.failed] if failed: return "failed", failed[0] - skipped = [report for report in phases if getattr(report, "skipped", False)] + skipped = [report for report in phases if report.skipped] if skipped: return "pending", skipped[0] call = reports.get("call") @@ -185,7 +184,7 @@ def _silence_terminal(self): writer.write = lambda *args, **kwargs: None def pytest_collectreport(self, report): - if getattr(report, "failed", False): + if report.failed: self.collect_failures.append(report) @pytest.hookimpl(trylast=True) diff --git a/src/selective_pytest/reporters.py b/src/selective_pytest/reporters.py index 1af1ec0..331a90b 100644 --- a/src/selective_pytest/reporters.py +++ b/src/selective_pytest/reporters.py @@ -81,7 +81,7 @@ def forget_terminal(config, nodeid): return for key, reports in list(stats.items()): stats[key] = [ - report for report in reports if getattr(report, "nodeid", None) != nodeid + report for report in reports if report.nodeid != nodeid ] diff --git a/tests/test_simplicity_checks.py b/tests/test_simplicity_checks.py new file mode 100644 index 0000000..e485cc2 --- /dev/null +++ b/tests/test_simplicity_checks.py @@ -0,0 +1,207 @@ +import ast +import shutil +from pathlib import Path + +from tools import check_dead_code +from tools import check_pytest_contract +from tools.check_dead_code import dead_lookups +from tools.check_dead_code import findings_for +from tools.check_dead_code import write_only +from tools.check_pytest_contract import high_enough +from tools.check_pytest_contract import source_findings + +ROOT = Path(__file__).resolve().parents[1] + +JUNIT_BEFORE = """ +def junit_plugin(config): + try: + from _pytest.junitxml import xml_key + found = config.stash.get(xml_key, None) + if found is not None: + return found + except Exception: + pass + for plugin in config.pluginmanager.get_plugins(): + if hasattr(plugin, "node_reporters") and hasattr(plugin, "stats"): + return plugin + return None + +def html_plugin(config): + plugin = config.pluginmanager.get_plugin("html") + reports = getattr(plugin, "_reports", None) + if reports is not None: + return plugin + return None + +def use(config): + return junit_plugin(config), html_plugin(config) + +def main(): + return use(None) +""" + +JUNIT_AFTER = """ +from _pytest.junitxml import xml_key + +def junit_plugin(config): + return config.stash.get(xml_key, None) + +def html_plugin(config): + for plugin in config.pluginmanager.get_plugins(): + if hasattr(plugin, "_reports") and hasattr(plugin, "_report"): + return plugin + return None + +def use(config): + return junit_plugin(config), html_plugin(config) + +def main(): + return use(None) +""" + +HEDGE_BEFORE = """ +def _file_path(item, cwd): + path = getattr(item, "path", None) + if path is None: + path = item.location[0] + return path + +def _line_number(item): + location = getattr(item, "location", (None, None)) + lineno = location[1] + return 0 if lineno is None else lineno + 1 + +def _duration(reports): + return sum(getattr(report, "duration", 0) for report in reports.values()) + +def finish_hooks(self, item, nextitem): + try: + self.session._setupstate.teardown_exact(item, nextitem) + except TypeError: + self.session._setupstate.teardown_exact(nextitem) +""" + +HEDGE_AFTER = """ +def _file_path(item, cwd): + return item.path + +def _line_number(item): + lineno = item.location[1] + return 0 if lineno is None else lineno + 1 + +def _duration(reports): + return sum(report.duration for report in reports.values()) + +def finish_hooks(self): + try: + self.session._setupstate.teardown_exact(None) + except Exception: + self.hook_failed = True +""" + + +def parsed(text): + return ast.parse(text), text.splitlines() + + +def ring_buffer(original): + injected = original.replace( + " self.closed = False\n", + " self.closed = False\n" + " self.stderr_lines = []\n" + " self._stderr = threading.Thread(target=self._drain_stderr, daemon=True)\n" + " self._stderr.start()\n", + 1, + ) + drain = ( + " def _drain_stderr(self):\n" + " try:\n" + " for line in self.proc.stderr:\n" + ' self.stderr_lines.append(line.rstrip("\\n"))\n' + " if len(self.stderr_lines) > 50:\n" + " del self.stderr_lines[:-50]\n" + " except Exception:\n" + " pass\n" + "\n" + ) + injected = injected.replace(" def _read_stdout(self):\n", drain + " def _read_stdout(self):\n", 1) + return injected.replace( + " stdout=subprocess.PIPE,\n", + " stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n", + 1, + ) + + +def test_unread_stderr_ring_buffer_fails_until_deleted(tmp_path): + original = (ROOT / "src" / "selective_pytest" / "transport.py").read_text() + tree, lines = parsed(ring_buffer(original)) + red = write_only(tree, lines, "transport.py") + assert any("stderr_lines" in item and "never read" in item for item in red), red + tree, lines = parsed(original) + assert write_only(tree, lines, "transport.py") == [] + src = tmp_path / "src" + shutil.copytree(ROOT / "src", src) + transport = src / "selective_pytest" / "transport.py" + transport.write_text(ring_buffer(original)) + cli_red = findings_for([str(src)], [str(src), str(ROOT / "tests")]) + assert len(cli_red) == 1 and "stderr_lines" in cli_red[0] and "never read" in cli_red[0] + transport.write_text(original) + assert findings_for([str(src)], [str(src), str(ROOT / "tests")]) == [] + + +def test_dead_plugin_lookups_fail_until_removed(): + tree, lines = parsed(JUNIT_BEFORE) + red = dead_lookups(tree, lines, "reporters.py") + assert any("node_reporters" in item for item in red), red + assert any("do not raise" in item for item in red), red + assert any("get_plugin('html')" in item for item in red), red + tree, lines = parsed(JUNIT_AFTER) + assert dead_lookups(tree, lines, "reporters.py") == [] + + +def test_framework_hedges_fail_until_direct_access(): + tree, lines = parsed(HEDGE_BEFORE) + red = source_findings(tree, lines, "plugin.py") + text = "\n".join(red) + assert "to access the attribute directly because pytest>=7.4 guarantees it (path)" in text + assert "to access the attribute directly because pytest>=7.4 guarantees it (location)" in text + assert "to access the attribute directly because pytest>=7.4 guarantees it (duration)" in text + assert "pytest-6 arity" in text + tree, lines = parsed(HEDGE_AFTER) + assert source_findings(tree, lines, "plugin.py") == [] + + +def test_pytest_floor_is_7_4(): + assert high_enough('dependencies = [\n "pytest>=7.4",\n]\n') + assert high_enough('dependencies = [\n "pytest>=8",\n]\n') + assert not high_enough('dependencies = [\n "pytest>=7",\n]\n') + assert not high_enough('dependencies = [\n "pytest>=6.2",\n]\n') + assert not high_enough("dependencies = []\n") + assert high_enough((ROOT / "pyproject.toml").read_text()) + + +def test_exception_on_the_line_needs_a_reason(): + bare = "class Box:\n def __init__(self):\n self.stderr_lines = [] # noqa: dead-code\n" + tree, lines = parsed(bare) + assert write_only(tree, lines, "box.py") + reasoned = ( + "class Box:\n" + " def __init__(self):\n" + " self.stderr_lines = [] # noqa: dead-code harness Popen, not the transport buffer\n" + ) + tree, lines = parsed(reasoned) + assert write_only(tree, lines, "box.py") == [] + hedge = 'def f(item):\n return getattr(item, "path", None) # noqa: pytest-contract\n' + tree, lines = parsed(hedge) + assert source_findings(tree, lines, "plugin.py") + hedge = ( + 'def f(item):\n' + ' return getattr(item, "path", None) # noqa: pytest-contract not a pytest Item\n' + ) + tree, lines = parsed(hedge) + assert source_findings(tree, lines, "plugin.py") == [] + + +def test_repository_sources_pass(): + assert check_dead_code.main([]) == 0 + assert check_pytest_contract.main([]) == 0 diff --git a/tools/__init__.py b/tools/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/check_dead_code.py b/tools/check_dead_code.py new file mode 100644 index 0000000..280ec96 --- /dev/null +++ b/tools/check_dead_code.py @@ -0,0 +1,310 @@ +import ast +import sys +from pathlib import Path + +MUTATORS = { + "append", + "extend", + "insert", + "remove", + "discard", + "add", + "update", + "clear", + "reverse", + "sort", + "put", + "put_nowait", + "pop", + "popleft", +} +MAINTENANCE = {"len"} +DUCK_ATTRS = {"node_reporters", "open_reports"} + + +def find_root(start=None): + current = Path(start or Path(__file__).resolve()).resolve() + if current.is_file(): + current = current.parent + for candidate in [current, *current.parents]: + if (candidate / "pyproject.toml").is_file() and (candidate / "src" / "selective_pytest").is_dir(): + return candidate + return Path.cwd() + + +def python_files(paths): + found = [] + for raw in paths: + path = Path(raw) + if path.is_dir(): + found.extend(sorted(item for item in path.rglob("*.py") if item.is_file())) + elif path.suffix == ".py" and path.is_file(): + found.append(path) + return found + + +def line_of(lines, lineno): + if lineno < 1 or lineno > len(lines): + return "" + return lines[lineno - 1] + + +def allowed(lines, lineno): + marker = "# noqa: dead-code" + text = line_of(lines, lineno) + if marker not in text: + return False + return bool(text.split(marker, 1)[1].strip()) + + +def parents_of(tree): + parents = {} + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + parents[child] = node + return parents + + +def ancestors(node, parents, limit): + found = [] + current = node + for _ in range(limit): + current = parents.get(current) + if current is None: + break + found.append(current) + return found + + +def self_attribute(node): + return ( + isinstance(node, ast.Attribute) + and isinstance(node.value, ast.Name) + and node.value.id == "self" + ) + + +def observed(node, parents): + above = ancestors(node, parents, 5) + parent = above[0] if above else None + if isinstance(parent, ast.Call) and parent.args and parent.args[0] is node: + func = parent.func + if isinstance(func, ast.Name) and func.id in MAINTENANCE: + return False + if isinstance(parent, ast.Attribute) and parent.value is node: + grand = above[1] if len(above) > 1 else None + great = above[2] if len(above) > 2 else None + if ( + isinstance(grand, ast.Call) + and grand.func is parent + and parent.attr in MUTATORS + and isinstance(great, ast.Expr) + ): + return False + return True + if isinstance(parent, ast.Subscript) and parent.value is node: + grand = above[1] if len(above) > 1 else None + if isinstance(parent.ctx, ast.Del) or isinstance(grand, ast.Delete): + return False + if isinstance(parent.ctx, ast.Store) and not isinstance(grand, ast.AugAssign): + return False + if isinstance(grand, ast.Assign) and len(grand.targets) == 1: + target = grand.targets[0] + if self_attribute(target) and target.attr == node.attr: + return False + return True + return True + + +def write_only(tree, lines, filename): + parents = parents_of(tree) + found = [] + for class_node in ast.walk(tree): + if not isinstance(class_node, ast.ClassDef): + continue + writes = {} + seen = set() + for node in ast.walk(class_node): + if not self_attribute(node): + continue + if isinstance(node.ctx, (ast.Store, ast.Del)): + writes.setdefault(node.attr, node.lineno) + elif isinstance(node.ctx, ast.Load) and observed(node, parents): + seen.add(node.attr) + elif isinstance(node.ctx, ast.Load): + writes.setdefault(node.attr, node.lineno) + for name, lineno in sorted(writes.items(), key=lambda item: item[1]): + if name in seen or allowed(lines, lineno): + continue + found.append( + filename + + ":" + + str(lineno) + + ": " + + class_node.name + + "." + + name + + " is written and never read. Delete it. Nothing reads this attribute," + + " so a capped buffer with no consumer is dead code (simplicity finding #4)." + ) + return found + + +def plugin_lookup(node): + if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute): + return False + if node.func.attr == "get_plugin": + return True + return ( + node.func.attr == "get" + and isinstance(node.func.value, ast.Attribute) + and node.func.value.attr == "stash" + ) + + +def bare_exception_pass(handler): + if not isinstance(handler.type, ast.Name) or handler.type.id != "Exception": + return False + return len(handler.body) == 1 and isinstance(handler.body[0], ast.Pass) + + +def dead_lookups(tree, lines, filename): + found = [] + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "hasattr" + and len(node.args) >= 2 + and isinstance(node.args[1], ast.Constant) + and node.args[1].value in DUCK_ATTRS + and not allowed(lines, node.lineno) + ): + found.append( + filename + + ":" + + str(node.lineno) + + ": hasattr(..., " + + repr(node.args[1].value) + + ") never matches. pytest>=7.0 keeps LogXML at config.stash.get(xml_key)." + + " Delete the duck scan (simplicity finding #1)." + ) + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "get_plugin" + and node.args + and isinstance(node.args[0], ast.Constant) + and node.args[0].value == "html" + and not allowed(lines, node.lineno) + ): + found.append( + filename + + ":" + + str(node.lineno) + + ": get_plugin('html') returns the pytest-html module, which has no _reports." + + " Find HTMLReport by its _reports and _report attributes (simplicity finding #1)." + ) + if isinstance(node, ast.Try): + for handler in node.handlers: + if not bare_exception_pass(handler) or allowed(lines, handler.lineno): + continue + if not any(plugin_lookup(child) for child in ast.walk(node)): + continue + found.append( + filename + + ":" + + str(handler.lineno) + + ": pluginmanager.get_plugin and config.stash.get return None and do not raise." + + " Delete the try/except Exception (simplicity finding #1)." + ) + return found + + +def defined_names(tree): + found = [] + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + found.append(node) + return found + + +def referenced_names(tree): + found = set() + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load): + found.add(node.id) + elif isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Load): + found.add(node.attr) + return found + + +def uncalled(parsed, lines_for, report_paths): + refs = set() + for _path, tree in parsed: + refs.update(referenced_names(tree)) + found = [] + for path, tree in parsed: + if path not in report_paths: + continue + lines = lines_for[path] + filename = str(path) + for node in defined_names(tree): + name = node.name + if name.startswith("__") and name.endswith("__"): + continue + if name.startswith("pytest_") or name == "main": + continue + if name in refs or allowed(lines, node.lineno): + continue + found.append( + filename + + ":" + + str(node.lineno) + + ": " + + name + + " has no caller. Delete it (simplicity finding #4, dead code)." + ) + return found + + +def findings_for(paths, reference_paths=None): + parsed = [] + lines_for = {} + found = [] + primary = python_files(paths) + report_paths = set(primary) + for path in primary: + text = path.read_text() + lines = text.splitlines() + tree = ast.parse(text, filename=str(path)) + parsed.append((path, tree)) + lines_for[path] = lines + found.extend(write_only(tree, lines, str(path))) + found.extend(dead_lookups(tree, lines, str(path))) + if reference_paths is not None: + for path in python_files(reference_paths): + if path in lines_for: + continue + text = path.read_text() + tree = ast.parse(text, filename=str(path)) + parsed.append((path, tree)) + lines_for[path] = text.splitlines() + found.extend(uncalled(parsed, lines_for, report_paths)) + return found + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + root = find_root() + if argv: + found = findings_for(argv) + else: + found = findings_for([str(root / "src")], [str(root / "src"), str(root / "tests")]) + for item in found: + print(item) + return 1 if found else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_pytest_contract.py b/tools/check_pytest_contract.py new file mode 100644 index 0000000..6c19d96 --- /dev/null +++ b/tools/check_pytest_contract.py @@ -0,0 +1,137 @@ +import ast +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from tools.check_dead_code import find_root +from tools.check_dead_code import line_of +from tools.check_dead_code import python_files + +GUARANTEED = { + "path", + "location", + "name", + "nodeid", + "duration", + "failed", + "skipped", + "passed", + "when", + "outcome", + "longrepr", + "keywords", +} +PIN = re.compile(r"pytest\s*(>=|~=)\s*(\d+)(?:\.(\d+))?") + + +def allowed(lines, lineno): + marker = "# noqa: pytest-contract" + text = line_of(lines, lineno) + if marker not in text: + return False + return bool(text.split(marker, 1)[1].strip()) + + +def attribute_name(node): + if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name) or node.func.id != "getattr": + return None + if len(node.args) >= 3 and isinstance(node.args[1], ast.Constant) and isinstance(node.args[1].value, str): + return node.args[1].value + if len(node.args) >= 2 and any(keyword.arg == "default" for keyword in node.keywords): + if isinstance(node.args[1], ast.Constant) and isinstance(node.args[1].value, str): + return node.args[1].value + return None + + +def typeerror_handler(handler): + type_node = handler.type + if isinstance(type_node, ast.Name): + return type_node.id == "TypeError" + if isinstance(type_node, ast.Tuple): + return any(isinstance(elt, ast.Name) and elt.id == "TypeError" for elt in type_node.elts) + return False + + +def calls_teardown_exact(node): + for child in ast.walk(node): + if isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute) and child.func.attr == "teardown_exact": + return True + return False + + +def high_enough(text): + matches = list(PIN.finditer(text)) + if not matches: + return False + for match in matches: + major = int(match.group(2)) + minor = int(match.group(3) or 0) + if major > 7 or (major == 7 and minor >= 4): + return True + return False + + +def pin_finding(text, filename): + if high_enough(text): + return [] + return [ + filename + + ":1: pin pytest>=7.4. Item.path, Report.duration, and" + + " SetupState.teardown_exact(nextitem) are only guaranteed from that version" + + " (simplicity findings #5 and #7)." + ] + + +def source_findings(tree, lines, filename): + found = [] + for node in ast.walk(tree): + attr = attribute_name(node) + if attr in GUARANTEED and not allowed(lines, node.lineno): + found.append( + filename + + ":" + + str(node.lineno) + + ": to access the attribute directly because pytest>=7.4 guarantees it (" + + attr + + ")" + ) + if isinstance(node, ast.Try) and any(typeerror_handler(handler) for handler in node.handlers): + if calls_teardown_exact(node) and not allowed(lines, node.lineno): + found.append( + filename + + ":" + + str(node.lineno) + + ": call teardown_exact with one argument because pytest>=7.4 guarantees" + + " that signature. Do not catch TypeError to retry a pytest-6 arity" + + " (simplicity finding #5)." + ) + return found + + +def findings_for(paths, project_text=None, project_name="pyproject.toml"): + found = [] + if project_text is not None: + found.extend(pin_finding(project_text, project_name)) + for path in python_files(paths): + text = path.read_text() + lines = text.splitlines() + tree = ast.parse(text, filename=str(path)) + found.extend(source_findings(tree, lines, str(path))) + return found + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + root = find_root() + paths = argv or [str(root / "src")] + text = (root / "pyproject.toml").read_text() + found = findings_for(paths, text, str(root / "pyproject.toml")) + for item in found: + print(item) + return 1 if found else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 7d4e37482d8c2c328a1a59cca0ba53ad5c611fda Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 28 Oct 2026 14:59:04 +0000 Subject: [PATCH 2/3] Keep rewritten node ids visible on pytest 9.2 pytest 9.2 reads nodeid from _id. Assigning _nodeid no longer changes the id, so the newest CI job collected the original ids and then raised KeyError in _full_description. Write both fields, and do the same in the tests that inject ids. Co-authored-by: Nate Vick --- src/selective_pytest/plugin.py | 8 +++++++- tests/harness.py | 2 ++ tests/test_client.py | 9 ++++++++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/selective_pytest/plugin.py b/src/selective_pytest/plugin.py index 8914293..3f9d816 100644 --- a/src/selective_pytest/plugin.py +++ b/src/selective_pytest/plugin.py @@ -87,6 +87,12 @@ def _line_number(item): return 0 if lineno is None else lineno + 1 +def _set_nodeid(item, nodeid): + item._nodeid = nodeid + if hasattr(item, "_id"): + item._id = type(item._id).parse(nodeid) + + def _description(item): return clean_text(item.name or item.nodeid) @@ -286,7 +292,7 @@ def _assign_ids(self, items): suffix += 1 if suffix > 2: warn("duplicate test id " + original + "; disambiguated as " + wired) - item._nodeid = wired + _set_nodeid(item, wired) self.native_ids[wired] = original seen.add(wired) self.ordered = list(items) diff --git a/tests/harness.py b/tests/harness.py index c5573fb..c4c8b69 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -480,6 +480,8 @@ def write_conformance_suite(root, flake_file, finish_mark): " for name in ORDER:\n" " item = by_name['test_' + name.replace('-', '_')]\n" " item._nodeid = name\n" + " if hasattr(item, '_id'):\n" + " item._id = type(item._id).parse(name)\n" " ordered.append(item)\n" " items[:] = ordered\n" "\n" diff --git a/tests/test_client.py b/tests/test_client.py index 850990a..c9dc6ac 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -792,6 +792,8 @@ def test_filters_and_duplicate_and_long_ids(tmp_path): " other = item\n" " if fast is not None and other is not None:\n" " other._nodeid = fast.nodeid\n" + " if hasattr(other, '_id'):\n" + " other._id = type(other._id).parse(fast.nodeid)\n" ) (root / "pytest.ini").write_text("[pytest]\nmarkers =\n slow: slow\n") server = MockServer() @@ -1170,6 +1172,8 @@ def test_long_duplicate_ids_stay_within_255(tmp_path): " native = " + repr(native) + "\n" " for item in items:\n" " item._nodeid = native\n" + " if hasattr(item, '_id'):\n" + " item._id = type(item._id).parse(native)\n" ) server = MockServer() proc = None @@ -1680,7 +1684,10 @@ def test_surrogate_nodeid_is_wire_safe(tmp_path): (root / "tests" / "conftest.py").write_text( "def pytest_collection_modifyitems(items):\n" " for item in items:\n" - " item._nodeid = item.nodeid + '\\ud800'\n" + " nodeid = item.nodeid + '\\ud800'\n" + " item._nodeid = nodeid\n" + " if hasattr(item, '_id'):\n" + " item._id = type(item._id).parse(nodeid)\n" ) env = os.environ.copy() for key in list(env): From 83ac639b3e3e0cd197edaa7736290f2418da8519 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 28 Oct 2026 15:01:08 +0000 Subject: [PATCH 3/3] Revert the pytest 9.2 nodeid workaround The newest-cell failure is on main too. pytest 9.2 reads nodeid from _id, and main still assigns _nodeid. That is a new pytest release, not this PR. Leave the breakage visible. Co-authored-by: Nate Vick --- src/selective_pytest/plugin.py | 8 +------- tests/harness.py | 2 -- tests/test_client.py | 9 +-------- 3 files changed, 2 insertions(+), 17 deletions(-) diff --git a/src/selective_pytest/plugin.py b/src/selective_pytest/plugin.py index 3f9d816..8914293 100644 --- a/src/selective_pytest/plugin.py +++ b/src/selective_pytest/plugin.py @@ -87,12 +87,6 @@ def _line_number(item): return 0 if lineno is None else lineno + 1 -def _set_nodeid(item, nodeid): - item._nodeid = nodeid - if hasattr(item, "_id"): - item._id = type(item._id).parse(nodeid) - - def _description(item): return clean_text(item.name or item.nodeid) @@ -292,7 +286,7 @@ def _assign_ids(self, items): suffix += 1 if suffix > 2: warn("duplicate test id " + original + "; disambiguated as " + wired) - _set_nodeid(item, wired) + item._nodeid = wired self.native_ids[wired] = original seen.add(wired) self.ordered = list(items) diff --git a/tests/harness.py b/tests/harness.py index c4c8b69..c5573fb 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -480,8 +480,6 @@ def write_conformance_suite(root, flake_file, finish_mark): " for name in ORDER:\n" " item = by_name['test_' + name.replace('-', '_')]\n" " item._nodeid = name\n" - " if hasattr(item, '_id'):\n" - " item._id = type(item._id).parse(name)\n" " ordered.append(item)\n" " items[:] = ordered\n" "\n" diff --git a/tests/test_client.py b/tests/test_client.py index c9dc6ac..850990a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -792,8 +792,6 @@ def test_filters_and_duplicate_and_long_ids(tmp_path): " other = item\n" " if fast is not None and other is not None:\n" " other._nodeid = fast.nodeid\n" - " if hasattr(other, '_id'):\n" - " other._id = type(other._id).parse(fast.nodeid)\n" ) (root / "pytest.ini").write_text("[pytest]\nmarkers =\n slow: slow\n") server = MockServer() @@ -1172,8 +1170,6 @@ def test_long_duplicate_ids_stay_within_255(tmp_path): " native = " + repr(native) + "\n" " for item in items:\n" " item._nodeid = native\n" - " if hasattr(item, '_id'):\n" - " item._id = type(item._id).parse(native)\n" ) server = MockServer() proc = None @@ -1684,10 +1680,7 @@ def test_surrogate_nodeid_is_wire_safe(tmp_path): (root / "tests" / "conftest.py").write_text( "def pytest_collection_modifyitems(items):\n" " for item in items:\n" - " nodeid = item.nodeid + '\\ud800'\n" - " item._nodeid = nodeid\n" - " if hasattr(item, '_id'):\n" - " item._id = type(item._id).parse(nodeid)\n" + " item._nodeid = item.nodeid + '\\ud800'\n" ) env = os.environ.copy() for key in list(env):