turnstile-select 0.1.0__py3-none-any.whl
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.
- turnstile_select/__init__.py +3 -0
- turnstile_select/cli.py +105 -0
- turnstile_select/client.py +133 -0
- turnstile_select/plugin.py +102 -0
- turnstile_select/selector/__init__.py +6 -0
- turnstile_select/selector/coverage_map.py +82 -0
- turnstile_select/selector/imports.py +52 -0
- turnstile_select/templates.py +102 -0
- turnstile_select/testmap.py +49 -0
- turnstile_select-0.1.0.dist-info/METADATA +11 -0
- turnstile_select-0.1.0.dist-info/RECORD +13 -0
- turnstile_select-0.1.0.dist-info/WHEEL +4 -0
- turnstile_select-0.1.0.dist-info/entry_points.txt +5 -0
turnstile_select/cli.py
ADDED
|
@@ -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
|
+
}
|
|
@@ -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,13 @@
|
|
|
1
|
+
turnstile_select/__init__.py,sha256=oqSf21ITK2moOwOPQevyAHnrtJd2pSI_ZA9iB23lP4c,93
|
|
2
|
+
turnstile_select/cli.py,sha256=nWSqciDoTX8K08jrEGC5qB5btF45v5DScr14H5V9MrE,4024
|
|
3
|
+
turnstile_select/client.py,sha256=J3ZVvdmtklE6MIhS36FbTvcPmxWCsL-Cmm1NjTINIjc,5711
|
|
4
|
+
turnstile_select/plugin.py,sha256=ffXBaAmVW3M17qeA5ZFfVDjTEPFIViw9ZAGvrgxPKRE,4039
|
|
5
|
+
turnstile_select/templates.py,sha256=Bc6vNIm3wiotvTbS5vXMlQoC_JU9ZI40h4DwmVqpGm8,3262
|
|
6
|
+
turnstile_select/testmap.py,sha256=IiGJfB60xwnAqItc-ZKM3sN_Mn6XCPizr6AP51LysbI,1779
|
|
7
|
+
turnstile_select/selector/__init__.py,sha256=xpDaeX8KjZxgxP1JxStiD0muA1uFUneyYtNvBLUA04E,296
|
|
8
|
+
turnstile_select/selector/coverage_map.py,sha256=Asi0LJkhX-OjtNvhLuvjlIoBzJEAo-lSG2buH-Qc93s,2866
|
|
9
|
+
turnstile_select/selector/imports.py,sha256=_vnyCVqmWLQ5wVWFtUT7-NqLyddUy0TXIpVYTHSlE3c,1951
|
|
10
|
+
turnstile_select-0.1.0.dist-info/METADATA,sha256=buM00qa6j0vFqjCA0yqLQN2qDOD1x9cuPfOWv_Dy8aE,407
|
|
11
|
+
turnstile_select-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
turnstile_select-0.1.0.dist-info/entry_points.txt,sha256=U1pplSTwK0Eaa0Vkns5X_E2pnH3hC1kpsKP2SZBuxqs,111
|
|
13
|
+
turnstile_select-0.1.0.dist-info/RECORD,,
|