turnstile-select 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ node_modules
2
+ dist
3
+ .env
4
+ coverage
5
+ .pgdata
6
+ *.pem
7
+ .terraform/
8
+ *.tfstate
9
+ *.tfstate.*
10
+ terraform.tfvars
11
+ backend.hcl
12
+ .claude/settings.local.json
13
+ .claude/worktrees/
14
+ .DS_Store
15
+ __pycache__/
16
+ *.egg-info/
17
+ .coverage
18
+ .pytest_cache/
19
+ turnstile-map.json
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.5
2
+ Name: turnstile-select
3
+ Version: 0.1.0
4
+ Summary: Run only the tests a pull request can affect. pytest plugin and map builder for Turnstile Select.
5
+ Requires-Python: >=3.10
6
+ Provides-Extra: dev
7
+ Requires-Dist: coverage>=7.4; extra == 'dev'
8
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
9
+ Requires-Dist: pytest>=8; extra == 'dev'
10
+ Provides-Extra: map
11
+ Requires-Dist: coverage>=7.4; extra == 'map'
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "turnstile-select"
7
+ version = "0.1.0"
8
+ description = "Run only the tests a pull request can affect. pytest plugin and map builder for Turnstile Select."
9
+ requires-python = ">=3.10"
10
+ dependencies = []
11
+
12
+ [project.optional-dependencies]
13
+ map = ["coverage>=7.4"]
14
+ dev = ["pytest>=8", "coverage>=7.4", "pytest-cov>=5"]
15
+
16
+ [project.entry-points.pytest11]
17
+ turnstile_select = "turnstile_select.plugin"
18
+
19
+ [project.scripts]
20
+ tu-select = "turnstile_select.cli:main"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["turnstile_select"]
24
+
25
+ [tool.pytest.ini_options]
26
+ testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ pytest_plugins = ["pytester"]
@@ -0,0 +1,94 @@
1
+ import gzip
2
+ import json
3
+ import os
4
+ import re
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ from turnstile_select import cli, client
9
+
10
+
11
+ def test_init_writes_the_workflow_and_config_and_never_overwrites(tmp_path: Path, capsys):
12
+ assert cli.main(["init", "--repo-root", str(tmp_path), "--api", "https://select.test", "--branch", "trunk"]) == 0
13
+ wf = (tmp_path / ".github/workflows/turnstile-select-map.yml").read_text()
14
+ assert "branches: [trunk]" in wf and "TURNSTILE_SELECT_URL: https://select.test" in wf and "id-token: write" in wf
15
+ assert "mode: shadow" in (tmp_path / ".turnstile/select.yml").read_text()
16
+ assert "needs.plan.outputs.run_tests == 'true'" in capsys.readouterr().out
17
+ (tmp_path / ".turnstile/select.yml").write_text("mode: on\n")
18
+ cli.main(["init", "--repo-root", str(tmp_path)])
19
+ assert (tmp_path / ".turnstile/select.yml").read_text() == "mode: on\n"
20
+
21
+
22
+ def test_upload_sends_gzip(tmp_path: Path, monkeypatch):
23
+ sent = {}
24
+ monkeypatch.setattr(client, "upload_map", lambda data: sent.setdefault("body", data) and {"map_id": 1, "tests": 2})
25
+ (tmp_path / "m.json").write_text(json.dumps({"version": 1}))
26
+ assert cli.main(["upload", str(tmp_path / "m.json")]) == 0
27
+ assert json.loads(gzip.decompress(sent["body"])) == {"version": 1}
28
+
29
+
30
+ def test_plan_prints_a_github_output_line(monkeypatch, capsys):
31
+ monkeypatch.setattr(client, "fetch_plan", lambda: {"run_tests": False, "reason": "docs only"})
32
+ assert cli.main(["plan"]) == 0
33
+ assert capsys.readouterr().out.strip() == "run_tests=false"
34
+
35
+
36
+ def test_plan_runs_tests_when_anything_is_wrong():
37
+ assert client.fetch_plan({})["run_tests"] is True
38
+ assert client.fetch_plan({"TURNSTILE_SELECT_URL": "https://x.invalid"})["run_tests"] is True
39
+
40
+
41
+ def test_map_needs_a_commit(tmp_path: Path, monkeypatch):
42
+ monkeypatch.delenv("GITHUB_SHA", raising=False)
43
+ assert cli.main(["map", "--commit", "", "--coverage-db", str(tmp_path / "x")]) == 2
44
+
45
+
46
+ def test_upload_is_not_an_error_when_select_is_off(tmp_path: Path, monkeypatch, capsys):
47
+ (tmp_path / "m.json").write_text("{}")
48
+ monkeypatch.setattr(client, "upload_map", lambda data: {"map_id": None, "tests": 0, "skipped": "Turnstile Select is not enabled for this repository"})
49
+ assert cli.main(["upload", str(tmp_path / "m.json")]) == 0
50
+ assert "map not stored" in capsys.readouterr().out
51
+
52
+
53
+ def _summary_step(snippet: str) -> tuple[str, str]:
54
+ expr = re.search(r"FAILED: \$\{\{ (.+) \}\}", snippet)
55
+ run = re.search(r"\n\s+run: (test .+)", snippet[snippet.index("turnstile-tests:"):])
56
+ assert expr and run
57
+ return expr.group(1), run.group(1)
58
+
59
+
60
+ def _evaluate(expr: str, results: list[str]) -> str:
61
+ """The rendered expression's `contains(needs.*.result, 'x')` terms joined by ||, as GitHub evaluates them."""
62
+ terms = expr.split(" || ")
63
+ values = []
64
+ for term in terms:
65
+ m = re.fullmatch(r"contains\(needs\.\*\.result, '(\w+)'\)", term)
66
+ assert m, term
67
+ values.append(m.group(1) in results)
68
+ return "true" if any(values) else "false"
69
+
70
+
71
+ def _check_passes(snippet: str, results: list[str]) -> bool:
72
+ expr, run = _summary_step(snippet)
73
+ env = {**os.environ, "FAILED": _evaluate(expr, results)}
74
+ return subprocess.run(["bash", "-c", run], env=env).returncode == 0
75
+
76
+ def test_the_snippet_adds_one_always_running_check_to_require(tmp_path: Path, capsys):
77
+ cli.main(["init", "--repo-root", str(tmp_path)])
78
+ out = capsys.readouterr().out
79
+ assert "on: [pull_request, merge_group]" in out
80
+ summary = out[out.index(" turnstile-tests:"):]
81
+ assert "if: always()" in summary and "needs: [plan, tests]" in summary
82
+ assert "contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')" in summary
83
+ assert "matrix:" in out[out.index(" tests:"):out.index(" turnstile-tests:")]
84
+
85
+
86
+ def test_the_required_check_passes_on_skip_and_fails_on_any_failed_matrix_leg(tmp_path: Path, capsys):
87
+ cli.main(["init", "--repo-root", str(tmp_path)])
88
+ out = capsys.readouterr().out
89
+ # needs results are [plan, tests]; GitHub reports a matrix job as failure when any leg failed
90
+ assert _check_passes(out, ["success", "skipped"]) # plan said run_tests=false
91
+ assert _check_passes(out, ["success", "success"])
92
+ assert not _check_passes(out, ["success", "failure"]) # one matrix leg failed
93
+ assert not _check_passes(out, ["success", "cancelled"])
94
+ assert not _check_passes(out, ["failure", "skipped"]) # plan failed, so tests never ran
@@ -0,0 +1,83 @@
1
+ import json
2
+ import subprocess
3
+ import sys
4
+ import textwrap
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ from turnstile_select.selector.coverage_map import CoverageDbError, file_to_tests, node_id
10
+ from turnstile_select.selector.imports import imported_by, source_file_to_module
11
+ from turnstile_select.testmap import build_map
12
+
13
+
14
+ def write(root: Path, rel: str, body: str) -> None:
15
+ path = root / rel
16
+ path.parent.mkdir(parents=True, exist_ok=True)
17
+ path.write_text(textwrap.dedent(body))
18
+
19
+
20
+ @pytest.fixture()
21
+ def project(tmp_path: Path) -> Path:
22
+ write(tmp_path, "app/__init__.py", "")
23
+ write(tmp_path, "app/billing.py", "def charge(n):\n return n * 2\n")
24
+ write(tmp_path, "app/users.py", "def signup(name):\n return name.title()\n")
25
+ write(tmp_path, "app/models.py", "LIMIT = 3\n")
26
+ write(tmp_path, "tests/test_billing.py", "from app.billing import charge\n\ndef test_charge():\n assert charge(2) == 4\n")
27
+ write(tmp_path, "tests/test_users.py", "from app.users import signup\n\ndef test_signup():\n assert signup('a') == 'A'\n")
28
+ write(tmp_path, "tests/test_models.py", "from app.models import LIMIT\n\ndef test_limit():\n assert LIMIT == 3\n")
29
+ write(tmp_path, ".coveragerc", "[run]\nrelative_files = True\n")
30
+ subprocess.run(
31
+ [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "--cov=app", "--cov-context=test", "tests"],
32
+ cwd=tmp_path,
33
+ check=True,
34
+ capture_output=True,
35
+ )
36
+ return tmp_path
37
+
38
+
39
+ def test_node_id_strips_the_phase():
40
+ assert node_id("tests/test_a.py::test_a|run") == "tests/test_a.py::test_a"
41
+ assert node_id("tests/test_a.py::T::test_a|setup") == "tests/test_a.py::T::test_a"
42
+ assert node_id("") is None
43
+
44
+
45
+ def test_file_to_tests_maps_each_file_to_the_tests_that_ran_it(project: Path):
46
+ covers, tests = file_to_tests(str(project / ".coverage"), project)
47
+ assert covers["app/billing.py"] == ["tests/test_billing.py::test_charge"]
48
+ assert covers["app/users.py"] == ["tests/test_users.py::test_signup"]
49
+ assert covers["app/models.py"] == []
50
+ assert tests == ["tests/test_billing.py::test_charge", "tests/test_users.py::test_signup"]
51
+
52
+
53
+ def test_tests_that_run_no_measured_code_stay_out_of_the_map_so_they_always_run(project: Path):
54
+ _, tests = file_to_tests(str(project / ".coverage"), project)
55
+ assert not any(t.startswith("tests/test_models.py") for t in tests)
56
+
57
+
58
+ def test_import_scan_catches_import_time_only_modules(project: Path):
59
+ assert imported_by(["app/models.py"], ["tests/test_models.py", "tests/test_users.py"], project) == {"app/models.py": ["tests/test_models.py"]}
60
+
61
+
62
+ def test_module_names_for_src_layouts_and_packages():
63
+ assert source_file_to_module("src/pkg/mod.py", ("src/", "")) == "pkg.mod"
64
+ assert source_file_to_module("pkg/__init__.py", ("src/", "")) == "pkg"
65
+ assert source_file_to_module("README.md", ("",)) is None
66
+
67
+
68
+ def test_build_map_has_no_line_data_and_matches_the_server_schema(project: Path):
69
+ m = build_map(str(project / ".coverage"), project, "abc123")
70
+ assert set(m) == {"version", "suite", "language", "commit", "createdAt", "tests", "covers", "importedBy"}
71
+ assert (m["suite"], m["language"]) == ("default", "python")
72
+ assert m["version"] == 1 and m["commit"] == "abc123"
73
+ assert "tests/test_billing.py" not in m["covers"]
74
+ assert m["importedBy"]["app/models.py"] == ["tests/test_models.py"]
75
+ json.dumps(m)
76
+
77
+
78
+ def test_a_database_without_contexts_is_rejected(tmp_path: Path):
79
+ import sqlite3
80
+
81
+ sqlite3.connect(tmp_path / "empty.db").close()
82
+ with pytest.raises(CoverageDbError):
83
+ file_to_tests(str(tmp_path / "empty.db"), tmp_path)
@@ -0,0 +1,106 @@
1
+ import json
2
+
3
+ import pytest
4
+
5
+ from turnstile_select import client
6
+ from turnstile_select.client import Decision, parse_decision
7
+
8
+
9
+ @pytest.fixture()
10
+ def suite(pytester: pytest.Pytester):
11
+ pytester.makepyfile(test_a="def test_a():\n assert True\n", test_b="def test_b():\n assert False\n")
12
+ return pytester
13
+
14
+
15
+ def use(monkeypatch: pytest.MonkeyPatch, decision: Decision) -> None:
16
+ monkeypatch.setattr(client, "_post_json", lambda *a, **k: (_ for _ in ()).throw(AssertionError("unused")))
17
+ monkeypatch.setattr("turnstile_select.plugin.fetch_decision", lambda: decision)
18
+
19
+
20
+ def test_on_mode_deselects_skipped_files(suite, monkeypatch):
21
+ use(monkeypatch, Decision(mode="on", run_all=False, reason="1 of 2", skip_files={"test_b.py"}))
22
+ result = suite.runpytest("--turnstile-select")
23
+ result.assert_outcomes(passed=1, deselected=1)
24
+
25
+
26
+ def test_shadow_mode_runs_everything_and_reports_misses(suite, monkeypatch):
27
+ use(monkeypatch, Decision(mode="shadow", run_all=False, reason="1 of 2", skip_files={"test_b.py"}))
28
+ result = suite.runpytest("--turnstile-select")
29
+ result.assert_outcomes(passed=1, failed=1)
30
+ result.stdout.fnmatch_lines(["*MISS, would have skipped failing test test_b.py::test_b*"])
31
+
32
+
33
+ def test_disabled_plugin_does_nothing(suite, monkeypatch):
34
+ use(monkeypatch, Decision(mode="on", run_all=False, reason="", skip_files={"test_a.py", "test_b.py"}))
35
+ suite.runpytest().assert_outcomes(passed=1, failed=1)
36
+
37
+
38
+ def test_errors_run_everything(suite, monkeypatch):
39
+ def boom():
40
+ raise RuntimeError("down")
41
+
42
+ monkeypatch.setattr("turnstile_select.plugin.fetch_decision", boom)
43
+ result = suite.runpytest("--turnstile-select")
44
+ result.assert_outcomes(passed=1, failed=1)
45
+ result.stdout.fnmatch_lines(["*ran every test (unexpected error*"])
46
+
47
+
48
+ def test_no_api_url_runs_everything():
49
+ d = client.fetch_decision({})
50
+ assert d.run_all and "TURNSTILE_SELECT_URL" in d.reason
51
+
52
+
53
+ def test_no_oidc_token_runs_everything():
54
+ d = client.fetch_decision({"TURNSTILE_SELECT_URL": "https://example.invalid"})
55
+ assert d.run_all and "OIDC" in d.reason
56
+
57
+
58
+ def test_unreachable_api_runs_everything(monkeypatch):
59
+ monkeypatch.setattr(client, "actions_oidc_token", lambda env: "tok")
60
+ d = client.fetch_decision({"TURNSTILE_SELECT_URL": "http://127.0.0.1:9"})
61
+ assert d.run_all and "could not reach" in d.reason
62
+
63
+
64
+ @pytest.mark.parametrize("body", [None, [], {"mode": "weird"}, {"mode": "on", "kind": "subset", "skipFiles": "x"}])
65
+ def test_unexpected_responses_run_everything(body):
66
+ assert parse_decision(body).run_all
67
+
68
+
69
+ def test_parse_subset():
70
+ d = parse_decision({"mode": "on", "kind": "subset", "skipFiles": ["a.py"], "reason": "r"})
71
+ assert (d.run_all, d.skip_files, d.mode) == (False, {"a.py"}, "on")
72
+
73
+
74
+ def test_pr_number_from_event_file(tmp_path):
75
+ p = tmp_path / "event.json"
76
+ p.write_text(json.dumps({"pull_request": {"number": 12}}))
77
+ assert client.pr_number({"GITHUB_EVENT_PATH": str(p)}) == 12
78
+ assert client.pr_number({}) is None
79
+
80
+
81
+ def test_outcomes_are_reported_with_shadow_misses(suite, monkeypatch):
82
+ sent = []
83
+ use(monkeypatch, Decision(mode="shadow", run_all=False, reason="r", skip_files={"test_b.py"}))
84
+ monkeypatch.setattr("turnstile_select.plugin.post_outcome", lambda o: sent.append(o))
85
+ suite.runpytest("--turnstile-select")
86
+ assert sent == [{"mode": "shadow", "ran": 2, "skipped": 1, "failed": 1, "missed": ["test_b.py::test_b"]}]
87
+
88
+
89
+ def test_outcomes_in_on_mode_count_deselected_tests(suite, monkeypatch):
90
+ sent = []
91
+ use(monkeypatch, Decision(mode="on", run_all=False, reason="r", skip_files={"test_b.py"}))
92
+ monkeypatch.setattr("turnstile_select.plugin.post_outcome", lambda o: sent.append(o))
93
+ suite.runpytest("--turnstile-select")
94
+ assert sent == [{"mode": "on", "ran": 1, "skipped": 1, "failed": 0, "missed": []}]
95
+
96
+
97
+ def test_outcomes_count_test_files_not_test_cases(pytester, monkeypatch):
98
+ pytester.makepyfile(test_a="def test_1():\n pass\ndef test_2():\n pass\n", test_b="def test_3():\n assert False\ndef test_4():\n assert False\n")
99
+ sent = []
100
+ use(monkeypatch, Decision(mode="shadow", run_all=False, reason="r", skip_files={"test_b.py"}))
101
+ monkeypatch.setattr("turnstile_select.plugin.post_outcome", lambda o: sent.append(o))
102
+ pytester.runpytest("--turnstile-select")
103
+ assert sent[0]["ran"] == 2
104
+ assert sent[0]["skipped"] == 1
105
+ assert sent[0]["failed"] == 1
106
+ assert sent[0]["missed"] == ["test_b.py::test_3", "test_b.py::test_4"]
@@ -0,0 +1,3 @@
1
+ """Turnstile Select: run only the tests a pull request can affect."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,105 @@
1
+ """tu-select: build and upload the test map, plan a run, or set up a repository."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import gzip
7
+ import json
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from . import client
13
+ from .selector.coverage_map import CoverageDbError
14
+ from .templates import CONFIG, MAP_WORKFLOW, TEST_JOB_SNIPPET
15
+ from .testmap import build_map
16
+
17
+ MAP_WORKFLOW_PATH = ".github/workflows/turnstile-select-map.yml"
18
+ CONFIG_PATH = ".turnstile/select.yml"
19
+
20
+
21
+ def cmd_map(args: argparse.Namespace) -> int:
22
+ if not args.commit:
23
+ print("tu-select: --commit is required outside GitHub Actions", file=sys.stderr)
24
+ return 2
25
+ try:
26
+ test_map = build_map(args.coverage_db, Path(args.repo_root), args.commit, suite=args.suite)
27
+ except CoverageDbError as err:
28
+ print(f"tu-select: {err}", file=sys.stderr)
29
+ return 1
30
+ Path(args.out).write_text(json.dumps(test_map, separators=(",", ":")))
31
+ print(f"tu-select: wrote {args.out} with {len(test_map['tests'])} tests and {len(test_map['covers'])} source files")
32
+ return 0
33
+
34
+
35
+ def cmd_upload(args: argparse.Namespace) -> int:
36
+ data = gzip.compress(Path(args.path).read_bytes())
37
+ try:
38
+ res = client.upload_map(data)
39
+ except (RuntimeError, OSError, ValueError) as err:
40
+ print(f"tu-select: upload failed: {err}", file=sys.stderr)
41
+ return 1
42
+ if res.get("skipped"):
43
+ print(f"tu-select: map not stored: {res['skipped']}")
44
+ return 0
45
+ print(f"tu-select: uploaded map {res.get('map_id')} with {res.get('tests')} tests")
46
+ return 0
47
+
48
+
49
+ def cmd_plan(_args: argparse.Namespace) -> int:
50
+ decision = client.fetch_plan()
51
+ print(f"run_tests={'true' if decision['run_tests'] else 'false'}")
52
+ print(f"turnstile-select plan: {decision['reason']}", file=sys.stderr)
53
+ return 0
54
+
55
+
56
+ def _write(path: Path, text: str, force: bool) -> None:
57
+ if path.exists() and not force:
58
+ print(f"tu-select: {path} exists, left unchanged (use --force to overwrite)")
59
+ return
60
+ path.parent.mkdir(parents=True, exist_ok=True)
61
+ path.write_text(text)
62
+ print(f"tu-select: wrote {path}")
63
+
64
+
65
+ def cmd_init(args: argparse.Namespace) -> int:
66
+ root = Path(args.repo_root)
67
+ _write(root / MAP_WORKFLOW_PATH, MAP_WORKFLOW.format(branch=args.branch, api=args.api, python=args.python), args.force)
68
+ _write(root / CONFIG_PATH, CONFIG.format(), args.force)
69
+ print()
70
+ print(TEST_JOB_SNIPPET.format(api=args.api))
71
+ return 0
72
+
73
+
74
+ def parser() -> argparse.ArgumentParser:
75
+ p = argparse.ArgumentParser(prog="tu-select")
76
+ sub = p.add_subparsers(dest="command", required=True)
77
+ m = sub.add_parser("map", help="Build the file -> tests map from .coverage recorded with --cov-context=test")
78
+ m.add_argument("--coverage-db", default=".coverage")
79
+ m.add_argument("--repo-root", default=".")
80
+ m.add_argument("--commit", default=os.environ.get("GITHUB_SHA", ""))
81
+ m.add_argument("--out", default="turnstile-map.json")
82
+ m.add_argument("--suite", default=os.environ.get("TURNSTILE_SELECT_SUITE") or "default")
83
+ m.set_defaults(func=cmd_map)
84
+ u = sub.add_parser("upload", help="Upload a map built by `tu-select map` (GitHub Actions only)")
85
+ u.add_argument("path", nargs="?", default="turnstile-map.json")
86
+ u.set_defaults(func=cmd_upload)
87
+ pl = sub.add_parser("plan", help="Print run_tests=true|false for $GITHUB_OUTPUT")
88
+ pl.set_defaults(func=cmd_plan)
89
+ i = sub.add_parser("init", help="Write the map workflow and config into this repository")
90
+ i.add_argument("--repo-root", default=".")
91
+ i.add_argument("--branch", default="main")
92
+ i.add_argument("--api", default=os.environ.get("TURNSTILE_SELECT_URL", "https://select.example.com"))
93
+ i.add_argument("--python", default="3.12")
94
+ i.add_argument("--force", action="store_true")
95
+ i.set_defaults(func=cmd_init)
96
+ return p
97
+
98
+
99
+ def main(argv: list[str] | None = None) -> int:
100
+ args = parser().parse_args(argv)
101
+ return args.func(args)
102
+
103
+
104
+ if __name__ == "__main__":
105
+ sys.exit(main())
@@ -0,0 +1,133 @@
1
+ """Talks to the Turnstile Select API. Every failure means: run everything."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from dataclasses import dataclass, field
11
+
12
+ AUDIENCE = "turnstile-select"
13
+ TIMEOUT_S = 3.0
14
+
15
+
16
+ @dataclass
17
+ class Decision:
18
+ mode: str
19
+ run_all: bool
20
+ reason: str
21
+ skip_files: set[str] = field(default_factory=set)
22
+
23
+
24
+ def run_all(reason: str) -> Decision:
25
+ return Decision(mode="off", run_all=True, reason=reason)
26
+
27
+
28
+ def _post_json(url: str, payload: dict, token: str, timeout: float = TIMEOUT_S) -> dict:
29
+ return _post_bytes(url, json.dumps(payload).encode(), token, {}, timeout)
30
+
31
+
32
+ def _post_bytes(url: str, data: bytes, token: str, headers: dict[str, str], timeout: float) -> dict:
33
+ req = urllib.request.Request(
34
+ url,
35
+ data=data,
36
+ headers={"content-type": "application/json", "authorization": f"Bearer {token}", **headers},
37
+ method="POST",
38
+ )
39
+ with urllib.request.urlopen(req, timeout=timeout) as res:
40
+ return json.loads(res.read())
41
+
42
+
43
+ def actions_oidc_token(env: dict[str, str]) -> str | None:
44
+ url, bearer = env.get("ACTIONS_ID_TOKEN_REQUEST_URL"), env.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
45
+ if not url or not bearer:
46
+ return None
47
+ sep = "&" if "?" in url else "?"
48
+ req = urllib.request.Request(f"{url}{sep}audience={urllib.parse.quote(AUDIENCE)}", headers={"authorization": f"Bearer {bearer}"})
49
+ with urllib.request.urlopen(req, timeout=TIMEOUT_S) as res:
50
+ value = json.loads(res.read()).get("value")
51
+ return value if isinstance(value, str) else None
52
+
53
+
54
+ def pr_number(env: dict[str, str]) -> int | None:
55
+ path = env.get("GITHUB_EVENT_PATH")
56
+ if not path:
57
+ return None
58
+ try:
59
+ with open(path, encoding="utf-8") as f:
60
+ number = json.load(f).get("pull_request", {}).get("number")
61
+ except (OSError, ValueError):
62
+ return None
63
+ return number if isinstance(number, int) else None
64
+
65
+
66
+ def parse_decision(body: object) -> Decision:
67
+ if not isinstance(body, dict) or body.get("mode") not in ("off", "shadow", "on"):
68
+ return run_all("the selection response was not understood")
69
+ reason = str(body.get("reason", ""))
70
+ if body.get("kind") == "subset" and isinstance(body.get("skipFiles"), list):
71
+ return Decision(mode=body["mode"], run_all=False, reason=reason, skip_files={str(f) for f in body["skipFiles"]})
72
+ return Decision(mode=body["mode"], run_all=True, reason=reason)
73
+
74
+
75
+ def fetch_decision(env: dict[str, str] | None = None) -> Decision:
76
+ env = dict(os.environ) if env is None else env
77
+ api = env.get("TURNSTILE_SELECT_URL")
78
+ if not api:
79
+ return run_all("TURNSTILE_SELECT_URL is not set")
80
+ try:
81
+ token = actions_oidc_token(env)
82
+ if token is None:
83
+ return run_all("no GitHub Actions OIDC token (add `permissions: id-token: write`; fork PRs never get one)")
84
+ body = _post_json(f"{api.rstrip('/')}/v1/selection", {"pr_number": pr_number(env), "event": env.get("GITHUB_EVENT_NAME"), "suite": env.get("TURNSTILE_SELECT_SUITE") or "default"}, token)
85
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError) as err:
86
+ return run_all(f"could not reach Turnstile Select ({err})")
87
+ return parse_decision(body)
88
+
89
+
90
+ def post_outcome(outcome: dict, env: dict[str, str] | None = None) -> str | None:
91
+ """Best effort. Returns an error message, or None when the outcome was recorded."""
92
+ env = dict(os.environ) if env is None else env
93
+ api = env.get("TURNSTILE_SELECT_URL")
94
+ if not api:
95
+ return "TURNSTILE_SELECT_URL is not set"
96
+ try:
97
+ token = actions_oidc_token(env)
98
+ if token is None:
99
+ return "no OIDC token"
100
+ payload = {"pr_number": pr_number(env), "job": env.get("GITHUB_JOB", ""), "suite": env.get("TURNSTILE_SELECT_SUITE") or "default", **outcome}
101
+ _post_json(f"{api.rstrip('/')}/v1/outcomes", payload, token)
102
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError) as err:
103
+ return str(err)
104
+ return None
105
+
106
+
107
+ def upload_map(gzipped: bytes, env: dict[str, str] | None = None) -> dict:
108
+ env = dict(os.environ) if env is None else env
109
+ api = env.get("TURNSTILE_SELECT_URL")
110
+ if not api:
111
+ raise RuntimeError("TURNSTILE_SELECT_URL is not set")
112
+ token = actions_oidc_token(env)
113
+ if token is None:
114
+ raise RuntimeError("no GitHub Actions OIDC token: the job needs `permissions: id-token: write`")
115
+ return _post_bytes(f"{api.rstrip('/')}/v1/maps", gzipped, token, {"content-encoding": "gzip"}, 120.0)
116
+
117
+
118
+ def fetch_plan(env: dict[str, str] | None = None) -> dict:
119
+ """Always answers; any failure means run the tests."""
120
+ env = dict(os.environ) if env is None else env
121
+ api = env.get("TURNSTILE_SELECT_URL")
122
+ if not api:
123
+ return {"run_tests": True, "reason": "TURNSTILE_SELECT_URL is not set"}
124
+ try:
125
+ token = actions_oidc_token(env)
126
+ if token is None:
127
+ return {"run_tests": True, "reason": "no GitHub Actions OIDC token"}
128
+ body = _post_json(f"{api.rstrip('/')}/v1/plan", {"pr_number": pr_number(env), "event": env.get("GITHUB_EVENT_NAME"), "suite": env.get("TURNSTILE_SELECT_SUITE") or "default"}, token)
129
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError) as err:
130
+ return {"run_tests": True, "reason": f"could not reach Turnstile Select ({err})"}
131
+ if not isinstance(body, dict) or body.get("run_tests") is not False:
132
+ return {"run_tests": True, "reason": str(body.get("reason", "")) if isinstance(body, dict) else "unexpected response"}
133
+ return {"run_tests": False, "reason": str(body.get("reason", ""))}
@@ -0,0 +1,102 @@
1
+ """pytest plugin. Enable with TURNSTILE_SELECT=1 or --turnstile-select.
2
+
3
+ shadow: runs everything, reports what would have been skipped.
4
+ on: deselects test files the change cannot affect.
5
+ Anything unexpected: runs everything.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from pathlib import Path
12
+
13
+ import pytest
14
+
15
+ from .client import Decision, fetch_decision, post_outcome, run_all
16
+
17
+ _DECISION = pytest.StashKey[Decision]()
18
+ _WOULD_SKIP = pytest.StashKey[set]()
19
+
20
+
21
+ def pytest_addoption(parser: pytest.Parser) -> None:
22
+ group = parser.getgroup("turnstile-select")
23
+ group.addoption("--turnstile-select", action="store_true", default=False, help="Ask Turnstile Select which tests this change can affect.")
24
+
25
+
26
+ def _enabled(config: pytest.Config) -> bool:
27
+ return bool(config.getoption("--turnstile-select")) or os.environ.get("TURNSTILE_SELECT") == "1"
28
+
29
+
30
+ def _relpath(item: pytest.Item, root: Path) -> str:
31
+ try:
32
+ return Path(str(item.path)).resolve().relative_to(root.resolve()).as_posix()
33
+ except ValueError:
34
+ return item.nodeid.split("::", 1)[0]
35
+
36
+
37
+ def apply_decision(decision: Decision, items: list[pytest.Item], root: Path) -> tuple[list[pytest.Item], list[pytest.Item]]:
38
+ if decision.run_all:
39
+ return items, []
40
+ keep, skip = [], []
41
+ for item in items:
42
+ (skip if _relpath(item, root) in decision.skip_files else keep).append(item)
43
+ return keep, skip
44
+
45
+
46
+ @pytest.hookimpl(trylast=True)
47
+ def pytest_collection_modifyitems(session: pytest.Session, config: pytest.Config, items: list[pytest.Item]) -> None:
48
+ if not _enabled(config):
49
+ return
50
+ try:
51
+ decision = fetch_decision()
52
+ except Exception as err: # noqa: BLE001 - selection must never break a test run
53
+ decision = run_all(f"unexpected error: {err!r}")
54
+ config.stash[_DECISION] = decision
55
+ keep, skip = apply_decision(decision, items, config.rootpath)
56
+ config.stash[_WOULD_SKIP] = {i.nodeid for i in skip}
57
+ if decision.mode == "on" and skip:
58
+ config.hook.pytest_deselected(items=skip)
59
+ items[:] = keep
60
+
61
+
62
+ def pytest_report_header(config: pytest.Config) -> str | None:
63
+ return "turnstile-select: enabled" if _enabled(config) else None
64
+
65
+
66
+ def _file_of(nodeid: str) -> str:
67
+ return nodeid.split("::", 1)[0]
68
+
69
+
70
+ def _files_run(stats: dict, *keys: str) -> int:
71
+ return len({_file_of(r.nodeid) for k in keys for r in stats.get(k, []) if getattr(r, "when", "call") == "call"})
72
+
73
+
74
+ def pytest_terminal_summary(terminalreporter, exitstatus: int, config: pytest.Config) -> None:
75
+ decision = config.stash.get(_DECISION, None)
76
+ if decision is None:
77
+ return
78
+ would_skip = config.stash.get(_WOULD_SKIP, set())
79
+ stats = terminalreporter.stats
80
+ failed_ids = {r.nodeid for r in stats.get("failed", [])} | {r.nodeid for r in stats.get("error", [])}
81
+ missed = sorted(failed_ids & would_skip) if decision.mode == "shadow" else []
82
+ if decision.run_all:
83
+ terminalreporter.write_line(f"turnstile-select: ran every test ({decision.reason})")
84
+ elif decision.mode == "shadow":
85
+ terminalreporter.write_line(f"turnstile-select (shadow): would have skipped {len(would_skip)} tests; {decision.reason}")
86
+ for nodeid in missed:
87
+ terminalreporter.write_line(f"turnstile-select (shadow): MISS, would have skipped failing test {nodeid}")
88
+ else:
89
+ terminalreporter.write_line(f"turnstile-select: skipped {len(would_skip)} tests; {decision.reason}")
90
+ if decision.mode == "off":
91
+ return
92
+ # Counts are test files, the unit selection works in, so Python and Jest suites add up.
93
+ outcome = {
94
+ "mode": decision.mode,
95
+ "ran": _files_run(stats, "passed", "failed", "skipped", "xfailed", "xpassed"),
96
+ "skipped": 0 if decision.run_all else len({_file_of(n) for n in would_skip}),
97
+ "failed": len({_file_of(n) for n in failed_ids}),
98
+ "missed": missed,
99
+ }
100
+ error = post_outcome(outcome)
101
+ if error:
102
+ terminalreporter.write_line(f"turnstile-select: could not report results ({error})")
@@ -0,0 +1,6 @@
1
+ """Selection building blocks ported from getsentry/sentry @ 5799664c.
2
+
3
+ Sources: .github/workflows/scripts/selected_tests_common.py (coverage contexts)
4
+ and .github/workflows/scripts/find_test_imports.py (static imports), generalised
5
+ so they work for any repository layout instead of Sentry's.
6
+ """
@@ -0,0 +1,82 @@
1
+ """Turn a coverage.py database recorded with --cov-context=test into a file -> tests map.
2
+
3
+ Ported from Sentry's covering_contexts(): same tables and the same rule that a
4
+ context only counts when its numbits blob has at least one executed line. Instead
5
+ of querying one changed file at a time on the PR, we read every file once on the
6
+ default branch and upload the result, so the PR side never needs the database.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import sqlite3
13
+ from pathlib import Path
14
+
15
+ PHASE_SUFFIXES = ("|run", "|setup", "|teardown")
16
+
17
+
18
+ class CoverageDbError(ValueError):
19
+ pass
20
+
21
+
22
+ def node_id(context: str) -> str | None:
23
+ if "::" not in context:
24
+ return None
25
+ for suffix in PHASE_SUFFIXES:
26
+ if context.endswith(suffix):
27
+ return context[: -len(suffix)]
28
+ return context
29
+
30
+
31
+ def relative_path(path: str, repo_root: Path) -> str | None:
32
+ p = Path(path)
33
+ if not p.is_absolute():
34
+ return Path(os.path.normpath(p)).as_posix()
35
+ try:
36
+ return p.resolve().relative_to(repo_root.resolve()).as_posix()
37
+ except ValueError:
38
+ return None
39
+
40
+
41
+ def _check_tables(conn: sqlite3.Connection) -> None:
42
+ tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
43
+ if "line_bits" not in tables or "context" not in tables:
44
+ raise CoverageDbError(
45
+ "Coverage database is missing line_bits/context tables. "
46
+ "Record it with pytest --cov --cov-context=test."
47
+ )
48
+
49
+
50
+ def file_to_tests(coverage_db_path: str, repo_root: Path) -> tuple[dict[str, list[str]], list[str]]:
51
+ """Return ({source file: [node ids that executed it]}, [every test node id])."""
52
+ covers: dict[str, set[str]] = {}
53
+ tests: set[str] = set()
54
+ conn = sqlite3.connect(coverage_db_path)
55
+ try:
56
+ _check_tables(conn)
57
+ for (context,) in conn.execute("SELECT context FROM context"):
58
+ nid = node_id(context)
59
+ if nid:
60
+ tests.add(nid)
61
+ for (path,) in conn.execute("SELECT path FROM file"):
62
+ rel = relative_path(path, repo_root)
63
+ if rel is not None:
64
+ covers.setdefault(rel, set())
65
+ rows = conn.execute(
66
+ """
67
+ SELECT f.path, c.context, lb.numbits
68
+ FROM line_bits lb
69
+ JOIN file f ON lb.file_id = f.id
70
+ JOIN context c ON lb.context_id = c.id
71
+ WHERE c.context LIKE '%::%'
72
+ """
73
+ )
74
+ for path, context, numbits in rows:
75
+ rel = relative_path(path, repo_root)
76
+ nid = node_id(context)
77
+ if rel is None or nid is None or not any(b != 0 for b in bytes(numbits)):
78
+ continue
79
+ covers.setdefault(rel, set()).add(nid)
80
+ finally:
81
+ conn.close()
82
+ return {f: sorted(ids) for f, ids in sorted(covers.items())}, sorted(tests)
@@ -0,0 +1,52 @@
1
+ """Static import scan: which test files import each source module.
2
+
3
+ Ported from Sentry's find_test_imports(). Coverage misses code whose lines only
4
+ run at import time, before a per-test context starts (pydantic models, constants,
5
+ registries), so a test that imports a module is selected even when coverage did
6
+ not link them. Sentry hard-codes src/ and tests/; here both are parameters and we
7
+ scan once for every module, so the result can be uploaded with the map.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from pathlib import Path
14
+
15
+
16
+ def source_file_to_module(repo_relative_path: str, source_roots: tuple[str, ...]) -> str | None:
17
+ if not repo_relative_path.endswith(".py"):
18
+ return None
19
+ for root in source_roots:
20
+ if root and not repo_relative_path.startswith(root):
21
+ continue
22
+ module = repo_relative_path.removeprefix(root).removesuffix(".py")
23
+ module = module.removesuffix("/__init__")
24
+ return module.replace("/", ".") or None
25
+ return None
26
+
27
+
28
+ def _pattern(module: str) -> re.Pattern[str]:
29
+ escaped = re.escape(module)
30
+ return re.compile(rf"from {escaped} import|import {escaped}(?:\s|;|,|$)", re.MULTILINE)
31
+
32
+
33
+ def imported_by(
34
+ source_files: list[str],
35
+ test_files: list[str],
36
+ repo_root: Path,
37
+ source_roots: tuple[str, ...] = ("src/", ""),
38
+ ) -> dict[str, list[str]]:
39
+ modules = {f: m for f in source_files if (m := source_file_to_module(f, source_roots))}
40
+ contents: dict[str, str] = {}
41
+ for test_file in test_files:
42
+ try:
43
+ contents[test_file] = (repo_root / test_file).read_text(encoding="utf-8", errors="ignore")
44
+ except OSError:
45
+ continue
46
+ result: dict[str, list[str]] = {}
47
+ for source_file, module in modules.items():
48
+ pattern = _pattern(module)
49
+ found = sorted(t for t, text in contents.items() if pattern.search(text))
50
+ if found:
51
+ result[source_file] = found
52
+ return result
@@ -0,0 +1,102 @@
1
+ """Files `tu-select init` writes into a customer repository."""
2
+
3
+ MAP_WORKFLOW = """\
4
+ name: Turnstile Select test map
5
+
6
+ # Runs the whole suite once with per-test coverage and uploads only a
7
+ # file -> tests map. Source code and line data never leave this job.
8
+ on:
9
+ schedule:
10
+ - cron: "17 6 * * *"
11
+ push:
12
+ branches: [{branch}]
13
+ workflow_dispatch:
14
+
15
+ concurrency:
16
+ group: turnstile-select-map
17
+ cancel-in-progress: true
18
+
19
+ permissions:
20
+ contents: read
21
+ id-token: write
22
+
23
+ jobs:
24
+ map:
25
+ runs-on: ubuntu-latest
26
+ timeout-minutes: 120
27
+ env:
28
+ TURNSTILE_SELECT_URL: {api}
29
+ steps:
30
+ - uses: actions/checkout@v4
31
+ - uses: actions/setup-python@v5
32
+ with:
33
+ python-version: "{python}"
34
+ - run: pip install -e . 'turnstile-select[map]' pytest-cov
35
+ # Keep the same install steps as your normal test job above this line.
36
+ - run: python -m pytest --cov=. --cov-context=test --cov-report= -p no:cacheprovider || true
37
+ - run: tu-select map --out turnstile-map.json
38
+ - run: tu-select upload turnstile-map.json
39
+ """
40
+
41
+ CONFIG = """\
42
+ # Turnstile Select settings. Everything here is optional.
43
+ # mode: off | shadow | on. shadow runs every test and reports what it would skip.
44
+ mode: shadow
45
+
46
+ # Changes to these paths always run the whole suite (added to the defaults:
47
+ # conftest.py, pyproject.toml, lockfiles, requirements, CI workflows).
48
+ full_suite_triggers: []
49
+
50
+ # Tests that always run, for example ones that walk every module at import time.
51
+ always_run: []
52
+
53
+ # Non-Python files and the tests that read them.
54
+ extra_mappings: {{}}
55
+ """
56
+
57
+ TEST_JOB_SNIPPET = """\
58
+ Add this to each pytest job (shown for GitHub Actions):
59
+
60
+ permissions:
61
+ contents: read
62
+ id-token: write # lets the plugin prove which repo it runs in
63
+ env:
64
+ TURNSTILE_SELECT: "1"
65
+ TURNSTILE_SELECT_URL: {api}
66
+ steps:
67
+ - run: pip install turnstile-select
68
+
69
+ Optional, to skip whole test jobs when a PR affects no tests (on mode only).
70
+ Run the workflow on both pull_request and merge_group. In the merge queue the plan
71
+ always answers run_tests=true. GitHub reports a skipped job as "skipped", which a
72
+ required check accepts, but job names change with a matrix, so do not require the
73
+ test jobs themselves. Require only turnstile-tests: it always runs, and it fails when
74
+ the plan or any test job (any matrix leg) failed or was cancelled.
75
+
76
+ on: [pull_request, merge_group]
77
+ jobs:
78
+ plan:
79
+ runs-on: ubuntu-latest
80
+ permissions: {{ contents: read, id-token: write }}
81
+ outputs:
82
+ run_tests: ${{{{ steps.plan.outputs.run_tests }}}}
83
+ steps:
84
+ - run: pip install turnstile-select
85
+ - id: plan
86
+ env: {{ TURNSTILE_SELECT_URL: {api} }}
87
+ run: tu-select plan >> "$GITHUB_OUTPUT"
88
+ tests:
89
+ needs: plan
90
+ if: needs.plan.outputs.run_tests == 'true'
91
+ strategy:
92
+ matrix:
93
+ python: ["3.11", "3.12"]
94
+ turnstile-tests:
95
+ needs: [plan, tests] # list every test job here
96
+ if: always()
97
+ runs-on: ubuntu-latest
98
+ steps:
99
+ - env:
100
+ FAILED: ${{{{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}}}
101
+ run: test "$FAILED" != "true"
102
+ """
@@ -0,0 +1,49 @@
1
+ """Build the map we upload: file -> tests plus the static import graph. No line data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ from pathlib import Path
7
+
8
+ from .selector.coverage_map import file_to_tests
9
+ from .selector.imports import imported_by
10
+
11
+ MAP_VERSION = 1
12
+
13
+
14
+ def test_file_of(node_id: str) -> str:
15
+ return node_id.split("::", 1)[0]
16
+
17
+
18
+ TEST_GLOBS = ("test_*.py", "*_test.py")
19
+ SKIP_DIRS = {".git", ".venv", "venv", "node_modules", ".tox", "build", "dist", "site-packages"}
20
+
21
+
22
+ def find_test_files(repo_root: Path) -> list[str]:
23
+ found = set()
24
+ for pattern in TEST_GLOBS:
25
+ for path in repo_root.rglob(pattern):
26
+ rel = path.relative_to(repo_root)
27
+ if not SKIP_DIRS.intersection(rel.parts):
28
+ found.add(rel.as_posix())
29
+ return sorted(found)
30
+
31
+
32
+ def build_map(coverage_db: str, repo_root: Path, commit: str, now: dt.datetime | None = None, suite: str = "default") -> dict:
33
+ """Tests that ran no measured line have no coverage context, so they are not in
34
+ `tests` and the server never skips them. The import scan still sees them."""
35
+ covers, tests = file_to_tests(coverage_db, repo_root)
36
+ test_files = sorted({test_file_of(t) for t in tests} | set(find_test_files(repo_root)))
37
+ test_file_set = set(test_files)
38
+ sources = [f for f in covers if f not in test_file_set]
39
+ created = (now or dt.datetime.now(dt.timezone.utc)).isoformat().replace("+00:00", "Z")
40
+ return {
41
+ "version": MAP_VERSION,
42
+ "suite": suite,
43
+ "language": "python",
44
+ "commit": commit,
45
+ "createdAt": created,
46
+ "tests": tests,
47
+ "covers": {f: ids for f, ids in covers.items() if f not in test_file_set},
48
+ "importedBy": imported_by(sources, test_files, repo_root),
49
+ }