pytest-uv 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.
pytest_uv/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """pytest-uv: Multi-version Python testing with uv and pytest-xdist."""
2
+
3
+ from pytest_uv._version import __version__, __version_tuple__
4
+
5
+ __all__ = ["__version__", "__version_tuple__"]
pytest_uv/_lock.py ADDED
@@ -0,0 +1,49 @@
1
+ """Inter-process exclusive file lock (stdlib only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ import time
8
+ from collections.abc import Iterator
9
+ from contextlib import contextmanager
10
+ from pathlib import Path
11
+
12
+ if sys.platform == "win32":
13
+ import msvcrt
14
+
15
+ def _acquire(fd: int) -> None:
16
+ while True:
17
+ try:
18
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
19
+ return
20
+ except OSError:
21
+ time.sleep(0.1)
22
+
23
+ def _release(fd: int) -> None:
24
+ os.lseek(fd, 0, os.SEEK_SET)
25
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
26
+
27
+ else:
28
+ import fcntl
29
+
30
+ def _acquire(fd: int) -> None:
31
+ fcntl.flock(fd, fcntl.LOCK_EX)
32
+
33
+ def _release(fd: int) -> None:
34
+ fcntl.flock(fd, fcntl.LOCK_UN)
35
+
36
+
37
+ @contextmanager
38
+ def file_lock(path: Path) -> Iterator[None]:
39
+ """Hold an exclusive lock on ``path`` (created if missing) for the block."""
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o644)
42
+ try:
43
+ _acquire(fd)
44
+ try:
45
+ yield
46
+ finally:
47
+ _release(fd)
48
+ finally:
49
+ os.close(fd)
pytest_uv/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
pytest_uv/envs.py ADDED
@@ -0,0 +1,370 @@
1
+ """Environment preparation: one uv-managed venv per Python version."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib.metadata
7
+ import json
8
+ import os
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ from collections import deque
13
+ from collections.abc import Callable
14
+ from concurrent.futures import ThreadPoolExecutor
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+ from urllib.parse import urlparse
19
+ from urllib.request import url2pathname
20
+
21
+ import pytest
22
+ from packaging.specifiers import SpecifierSet
23
+ from packaging.version import Version
24
+
25
+ from ._lock import file_lock
26
+
27
+ DEFAULT_VENV_DIR = ".pytest-uv"
28
+ STAMP_NAME = ".pytest-uv-stamp"
29
+ _STAMP_FORMAT = 1
30
+
31
+ Log = Callable[[str], None]
32
+
33
+ _PROBE = """\
34
+ import importlib.util, json, platform, sys
35
+ print(json.dumps({
36
+ "python": platform.python_version(),
37
+ "sys_path": sys.path,
38
+ "missing": [m for m in ("pytest", "xdist", "pytest_uv")
39
+ if importlib.util.find_spec(m) is None],
40
+ }))
41
+ """
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Settings:
46
+ """``[tool.pytest-uv]`` configuration (paths resolved against the rootdir).
47
+
48
+ Keys:
49
+ versions: list used by ``--python-versions=declared``.
50
+ venv-dir: where venvs live, default ``.pytest-uv``.
51
+ sync-args: extra ``uv sync`` arguments when ``uv.lock`` exists,
52
+ default ``[]`` (uv's default groups, i.e. ``dev``, apply).
53
+ install-args: ``uv pip install`` arguments when there is no
54
+ ``uv.lock``. Default: ``-e .`` (``-e .[test]`` if a ``test``
55
+ extra exists) plus ``--group test`` and ``--group dev`` for each
56
+ of those dependency groups that exists.
57
+ """
58
+
59
+ root: Path
60
+ venv_dir: Path
61
+ sync_args: tuple[str, ...]
62
+ install_args: tuple[str, ...]
63
+
64
+ @property
65
+ def lockfile(self) -> Path:
66
+ return self.root / "uv.lock"
67
+
68
+ @classmethod
69
+ def from_pyproject(cls, pyproject: dict[str, Any], root: Path) -> Settings:
70
+ table = pyproject.get("tool", {}).get("pytest-uv", {})
71
+ if not isinstance(table, dict):
72
+ raise pytest.UsageError("[tool.pytest-uv] must be a table")
73
+ venv_dir = table.get("venv-dir", DEFAULT_VENV_DIR)
74
+ if not isinstance(venv_dir, str) or not venv_dir:
75
+ raise pytest.UsageError("[tool.pytest-uv].venv-dir must be a string")
76
+ install_args = table.get("install-args")
77
+ return cls(
78
+ root=root,
79
+ venv_dir=root / venv_dir,
80
+ sync_args=_str_list(table, "sync-args", []),
81
+ install_args=(
82
+ _str_list(table, "install-args", [])
83
+ if install_args is not None
84
+ else tuple(default_install_args(pyproject, root))
85
+ ),
86
+ )
87
+
88
+
89
+ def _str_list(table: dict[str, Any], key: str, default: list[str]) -> tuple[str, ...]:
90
+ value = table.get(key, default)
91
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
92
+ raise pytest.UsageError(f"[tool.pytest-uv].{key} must be a list of strings")
93
+ return tuple(value)
94
+
95
+
96
+ def default_install_args(pyproject: dict[str, Any], root: Path) -> list[str]:
97
+ """Default ``uv pip install`` arguments for projects without ``uv.lock``."""
98
+ if not any((root / f).exists() for f in ("pyproject.toml", "setup.py")):
99
+ return []
100
+ extras = pyproject.get("project", {}).get("optional-dependencies", {})
101
+ args = ["-e", ".[test]" if "test" in extras else "."]
102
+ groups = pyproject.get("dependency-groups", {})
103
+ for group in ("test", "dev"):
104
+ if group in groups:
105
+ args += ["--group", group]
106
+ return args
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class Env:
111
+ """A prepared per-version environment."""
112
+
113
+ version: str
114
+ python: Path
115
+ full_version: str
116
+ sys_path: tuple[str, ...]
117
+
118
+
119
+ def prepare_envs(
120
+ versions: list[str],
121
+ settings: Settings,
122
+ *,
123
+ uv: str = "uv",
124
+ log: Log | None = None,
125
+ ) -> list[Env]:
126
+ """Create or reuse one venv per version, in parallel.
127
+
128
+ Each venv is guarded by a file lock so concurrent pytest runs do not race.
129
+ uv output is captured unless ``log`` is given, in which case every line is
130
+ passed to it. Failures raise ``pytest.UsageError`` with uv's output.
131
+ """
132
+ settings.venv_dir.mkdir(parents=True, exist_ok=True)
133
+ gitignore = settings.venv_dir / ".gitignore"
134
+ if not gitignore.exists():
135
+ gitignore.write_text("*\n")
136
+ with ThreadPoolExecutor(max_workers=max(len(versions), 1)) as pool:
137
+ futures = [
138
+ pool.submit(_prepare_env, version, settings, uv, log)
139
+ for version in versions
140
+ ]
141
+ return [f.result() for f in futures]
142
+
143
+
144
+ def python_bin_path(env_path: Path) -> Path:
145
+ """Return the path to the Python binary inside a venv."""
146
+ if sys.platform == "win32":
147
+ return env_path / "Scripts" / "python.exe"
148
+ return env_path / "bin" / "python"
149
+
150
+
151
+ def env_command(version: str, settings: Settings) -> list[str]:
152
+ """The uv command that installs the project into the venv (sans paths)."""
153
+ if settings.lockfile.exists():
154
+ return ["sync", "--frozen", "--python", version, *settings.sync_args]
155
+ return ["pip", "install", *settings.install_args]
156
+
157
+
158
+ def compute_fingerprint(root: Path, version: str, command: list[str]) -> str:
159
+ """Hash of everything that, when changed, requires rebuilding the venv."""
160
+ h = hashlib.sha256(
161
+ json.dumps([_STAMP_FORMAT, version, command, _self_identity()]).encode()
162
+ )
163
+ for name in ("pyproject.toml", "uv.lock", *_referenced_files(command)):
164
+ path = root / name
165
+ h.update(name.encode())
166
+ h.update(path.read_bytes() if path.is_file() else b"\0")
167
+ return h.hexdigest()[:16]
168
+
169
+
170
+ def _self_identity() -> list[str]:
171
+ try:
172
+ dist = importlib.metadata.distribution("pytest-uv")
173
+ except importlib.metadata.PackageNotFoundError:
174
+ return []
175
+ return [dist.version, dist.read_text("direct_url.json") or ""]
176
+
177
+
178
+ def _referenced_files(command: list[str]) -> list[str]:
179
+ """Requirement and constraint files named by ``-r``/``-c`` style options."""
180
+ options = {"-r", "--requirement", "-c", "--constraint", "--constraints"}
181
+ files = []
182
+ for option, value in zip(command, command[1:]):
183
+ if option in options:
184
+ files.append(value)
185
+ for arg in command:
186
+ name, sep, value = arg.partition("=")
187
+ if sep and name in options:
188
+ files.append(value)
189
+ return files
190
+
191
+
192
+ def read_stamp(env_path: Path, fingerprint: str) -> Env | None:
193
+ """Return the recorded env if its stamp matches and its paths still exist.
194
+
195
+ The path check catches a uv-managed Python that was upgraded or removed
196
+ since the venv was built.
197
+ """
198
+ python = python_bin_path(env_path)
199
+ try:
200
+ data = json.loads((env_path / STAMP_NAME).read_text())
201
+ except (OSError, ValueError):
202
+ return None
203
+ if (
204
+ not python.exists()
205
+ or not isinstance(data, dict)
206
+ or data.get("fingerprint") != fingerprint
207
+ or not isinstance(data.get("sys_path"), list)
208
+ or not all(Path(p).exists() for p in data["sys_path"] if not p.endswith(".zip"))
209
+ ):
210
+ return None
211
+ return Env(
212
+ version=data.get("version", ""),
213
+ python=python,
214
+ full_version=str(data.get("python", "")),
215
+ sys_path=tuple(data["sys_path"]),
216
+ )
217
+
218
+
219
+ def _prepare_env(version: str, settings: Settings, uv: str, log: Log | None) -> Env:
220
+ env_path = settings.venv_dir / f"py{version}"
221
+ command = env_command(version, settings)
222
+ fingerprint = compute_fingerprint(settings.root, version, command)
223
+ with file_lock(settings.venv_dir / f".py{version}.lock"):
224
+ cached = read_stamp(env_path, fingerprint)
225
+ if cached is not None:
226
+ return cached
227
+ env = _build_env(version, env_path, command, settings, uv, log)
228
+ (env_path / STAMP_NAME).write_text(
229
+ json.dumps(
230
+ {
231
+ "fingerprint": fingerprint,
232
+ "version": version,
233
+ "python": env.full_version,
234
+ "sys_path": list(env.sys_path),
235
+ },
236
+ indent=2,
237
+ )
238
+ )
239
+ return env
240
+
241
+
242
+ def _build_env(
243
+ version: str,
244
+ env_path: Path,
245
+ command: list[str],
246
+ settings: Settings,
247
+ uv: str,
248
+ log: Log | None,
249
+ ) -> Env:
250
+ python = python_bin_path(env_path)
251
+ run_env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"}
252
+ prefix = f"[py{version}] "
253
+
254
+ def run(*args: str, extra_env: dict[str, str] | None = None) -> None:
255
+ _run([uv, *args], settings.root, {**run_env, **(extra_env or {})}, log, prefix)
256
+
257
+ if env_path.exists() and not (env_path / "pyvenv.cfg").exists():
258
+ # uv refuses to --clear a directory that is not a venv.
259
+ shutil.rmtree(env_path)
260
+ run("venv", "--clear", "--python", version, str(env_path))
261
+ if command[0] == "sync":
262
+ run(*command, extra_env={"UV_PROJECT_ENVIRONMENT": str(env_path)})
263
+ elif len(command) > 2:
264
+ run("pip", "install", "--python", str(python), *command[2:])
265
+
266
+ probe = _probe(python, settings.root, log, prefix)
267
+ missing = _missing_requirements(probe["missing"], probe["python"])
268
+ if missing:
269
+ run("pip", "install", "--python", str(python), *missing)
270
+ probe = _probe(python, settings.root, log, prefix)
271
+
272
+ return Env(
273
+ version=version,
274
+ python=python,
275
+ full_version=probe["python"],
276
+ sys_path=tuple(probe["sys_path"]),
277
+ )
278
+
279
+
280
+ def _probe(python: Path, cwd: Path, log: Log | None, prefix: str) -> dict[str, Any]:
281
+ # -I: no cwd, PYTHONPATH or user site, i.e. only the venv's own sys.path.
282
+ output = _run([str(python), "-I", "-c", _PROBE], cwd, None, None, prefix)
283
+ return json.loads(output.strip().splitlines()[-1])
284
+
285
+
286
+ def _missing_requirements(missing: list[str], python_version: str) -> list[str]:
287
+ requirements: list[str] = []
288
+ if "pytest" in missing:
289
+ requirements.append("pytest")
290
+ if "xdist" in missing:
291
+ requirements.append("pytest-xdist")
292
+ if "pytest_uv" in missing:
293
+ requirements += self_requirement(python_version)
294
+ return requirements
295
+
296
+
297
+ def self_requirement(python_version: str) -> list[str]:
298
+ """How to install the running pytest-uv into a worker venv.
299
+
300
+ Returns ``[]`` if the worker's Python is outside pytest-uv's
301
+ ``Requires-Python`` (workers then run without the plugin, so the
302
+ ``python_version`` fixture is unavailable there).
303
+ """
304
+ try:
305
+ dist = importlib.metadata.distribution("pytest-uv")
306
+ except importlib.metadata.PackageNotFoundError:
307
+ return []
308
+ requires_python = dist.metadata.get("Requires-Python")
309
+ if requires_python and not SpecifierSet(requires_python).contains(
310
+ Version(python_version), prereleases=True
311
+ ):
312
+ return []
313
+ direct_url = dist.read_text("direct_url.json")
314
+ if direct_url:
315
+ info = json.loads(direct_url)
316
+ url = info.get("url", "")
317
+ if info.get("dir_info", {}).get("editable") and url.startswith("file:"):
318
+ return ["-e", url2pathname(urlparse(url).path)]
319
+ if url:
320
+ return [f"pytest-uv @ {url}"]
321
+ return [f"pytest-uv=={dist.version}"]
322
+
323
+
324
+ def _run(
325
+ cmd: list[str],
326
+ cwd: Path,
327
+ env: dict[str, str] | None,
328
+ log: Log | None,
329
+ prefix: str,
330
+ ) -> str:
331
+ if log is None:
332
+ result = subprocess.run(
333
+ cmd,
334
+ cwd=cwd,
335
+ env=env,
336
+ capture_output=True,
337
+ encoding="utf-8",
338
+ errors="replace",
339
+ )
340
+ if result.returncode != 0:
341
+ _fail(cmd, result.returncode, result.stderr or result.stdout)
342
+ return result.stdout
343
+
344
+ tail: deque[str] = deque(maxlen=50)
345
+ lines: list[str] = []
346
+ with subprocess.Popen(
347
+ cmd,
348
+ cwd=cwd,
349
+ env=env,
350
+ stdout=subprocess.PIPE,
351
+ stderr=subprocess.STDOUT,
352
+ encoding="utf-8",
353
+ errors="replace",
354
+ ) as proc:
355
+ assert proc.stdout is not None
356
+ for line in proc.stdout:
357
+ lines.append(line)
358
+ tail.append(line)
359
+ log(prefix + line.rstrip("\n"))
360
+ if proc.returncode != 0:
361
+ _fail(cmd, proc.returncode, "".join(tail))
362
+ return "".join(lines)
363
+
364
+
365
+ def _fail(cmd: list[str], returncode: int, output: str) -> None:
366
+ shown = " ".join(c if len(c) < 200 else c[:40] + "..." for c in cmd)
367
+ raise pytest.UsageError(
368
+ f"pytest-uv: command failed with exit code {returncode}: {shown}\n"
369
+ f"{output.rstrip()}"
370
+ )
pytest_uv/plugin.py ADDED
@@ -0,0 +1,241 @@
1
+ """pytest plugin: run the test suite once per Python version via uv and xdist."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import sys
8
+ import threading
9
+ import tomllib
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import pytest
15
+
16
+ from .envs import Env, Log, Settings, prepare_envs, python_bin_path
17
+ from .resolver import resolve_versions
18
+
19
+
20
+ @dataclass
21
+ class _State:
22
+ versions: list[str]
23
+ envs: dict[str, Env] = field(default_factory=dict)
24
+ sys_path_head: list[str] = field(default_factory=list)
25
+ xdist_sys_path: list[str] | None = None
26
+ original_sys_path: list[str] = field(default_factory=list)
27
+
28
+
29
+ _STATE = pytest.StashKey[_State]()
30
+
31
+
32
+ def pytest_addoption(parser: pytest.Parser) -> None:
33
+ group = parser.getgroup("uv", "Multi-version testing with uv")
34
+ group.addoption(
35
+ "--python-versions",
36
+ dest="python_versions",
37
+ default=None,
38
+ metavar="VERSIONS",
39
+ help=(
40
+ "Run the whole test suite once per Python version, each in its own "
41
+ "uv-managed venv and xdist worker. VERSIONS is 'auto' (installed "
42
+ "versions matching requires-python), 'declared' ([tool.pytest-uv] "
43
+ "versions) or a list like '3.12,3.13'. Not combinable with -n or "
44
+ "--dist other than 'each'."
45
+ ),
46
+ )
47
+
48
+
49
+ @pytest.hookimpl(tryfirst=True)
50
+ def pytest_configure(config: pytest.Config) -> None:
51
+ """Resolve versions, prepare venvs and point xdist at them.
52
+
53
+ Runs tryfirst so ``tx``/``dist`` are set before xdist's trylast
54
+ ``pytest_configure`` decides whether to start a distributed session.
55
+ xdist's ``pytest_cmdline_main`` has already run, so ``-n`` is resolved.
56
+ """
57
+ if hasattr(config, "workerinput"):
58
+ return
59
+ mode = config.getoption("python_versions", default=None)
60
+ if mode is None:
61
+ return
62
+
63
+ root = config.rootpath
64
+ pyproject = _load_pyproject(root)
65
+ settings = Settings.from_pyproject(pyproject, root)
66
+ _check_options(config, settings)
67
+ uv = _find_uv()
68
+ try:
69
+ versions = resolve_versions(mode, pyproject, uv)
70
+ except ValueError as exc:
71
+ raise pytest.UsageError(f"pytest-uv: {exc}") from exc
72
+ if not versions:
73
+ raise pytest.UsageError(
74
+ f"pytest-uv: no Python versions matched --python-versions={mode}"
75
+ )
76
+
77
+ state = _State(versions=versions)
78
+ config.stash[_STATE] = state
79
+ if config.option.collectonly:
80
+ return
81
+
82
+ xdist_sys_path = _xdist_sys_path()
83
+ envs = prepare_envs(versions, settings, uv=uv, log=_make_log(config))
84
+ state.envs = {str(env.python): env for env in envs}
85
+ state.xdist_sys_path = xdist_sys_path
86
+ state.original_sys_path = list(xdist_sys_path)
87
+ state.sys_path_head = _sys_path_head(state.original_sys_path)
88
+
89
+ config.option.tx = [f"popen//python={env.python}" for env in envs]
90
+ config.option.dist = "each"
91
+
92
+
93
+ def _check_options(config: pytest.Config, settings: Settings) -> None:
94
+ if not config.pluginmanager.hasplugin("xdist"):
95
+ raise pytest.UsageError(
96
+ "pytest-uv: --python-versions requires pytest-xdist "
97
+ "(is it disabled with -p no:xdist?)"
98
+ )
99
+ if config.getoption("numprocesses", None):
100
+ raise pytest.UsageError(
101
+ "pytest-uv: -n/--numprocesses cannot be combined with "
102
+ "--python-versions, which starts one worker per version and runs "
103
+ "every test on each (--dist each). Remove -n, or pass -n 0 to "
104
+ "override it from addopts."
105
+ )
106
+ dist = config.getoption("dist", "no")
107
+ if dist not in ("no", "each"):
108
+ raise pytest.UsageError(
109
+ f"pytest-uv: --dist {dist} cannot be combined with "
110
+ "--python-versions, which always uses --dist each."
111
+ )
112
+ if config.getoption("tx", None):
113
+ raise pytest.UsageError(
114
+ "pytest-uv: --tx cannot be combined with --python-versions, "
115
+ "which creates one worker per version itself."
116
+ )
117
+ if config.getoption("usepdb", False):
118
+ python = python_bin_path(settings.venv_dir / "py3.X")
119
+ try:
120
+ python = python.relative_to(settings.root)
121
+ except ValueError:
122
+ pass
123
+ raise pytest.UsageError(
124
+ "pytest-uv: --pdb does not work in xdist workers. Run the test "
125
+ f"in that version's environment instead: {python} -m pytest <test> --pdb"
126
+ )
127
+
128
+
129
+ def _xdist_sys_path() -> list[str]:
130
+ """The list xdist sends to popen workers as their ``sys.path``.
131
+
132
+ xdist (3.0 to at least 3.8) freezes the controller's ``sys.path`` in
133
+ ``xdist.plugin._sys_path`` and ``WorkerController.setup`` sends it to
134
+ every popen worker right after ``pytest_configure_node``. We rewrite it
135
+ in place per node so each worker keeps its own venv's ``sys.path``.
136
+ """
137
+ import xdist.workermanage
138
+
139
+ value = getattr(xdist.workermanage, "_sys_path", None)
140
+ if not isinstance(value, list):
141
+ raise pytest.UsageError(
142
+ "pytest-uv: unsupported pytest-xdist version (no "
143
+ "xdist.workermanage._sys_path); workers cannot be isolated."
144
+ )
145
+ return value
146
+
147
+
148
+ def _sys_path_head(controller_sys_path: list[str]) -> list[str]:
149
+ """Entries the controller has on top of its environment.
150
+
151
+ That is the script directory (or cwd for ``python -m pytest``) and
152
+ ``PYTHONPATH``, which workers should keep; the rest is replaced by the
153
+ worker venv's own paths.
154
+ """
155
+ head = controller_sys_path[:0] if sys.flags.safe_path else controller_sys_path[:1]
156
+ if sys.flags.ignore_environment:
157
+ return head
158
+ pythonpath = {
159
+ os.path.normcase(os.path.abspath(p))
160
+ for p in os.environ.get("PYTHONPATH", "").split(os.pathsep)
161
+ if p
162
+ }
163
+ for entry in controller_sys_path[len(head) :]:
164
+ if os.path.normcase(os.path.abspath(entry)) not in pythonpath:
165
+ break
166
+ head.append(entry)
167
+ return head
168
+
169
+
170
+ @pytest.hookimpl(optionalhook=True)
171
+ def pytest_configure_node(node: Any) -> None:
172
+ """Give the worker its version and its venv's ``sys.path``."""
173
+ state = node.config.stash.get(_STATE, None)
174
+ if state is None or state.xdist_sys_path is None:
175
+ return
176
+ env = state.envs.get(str(node.gateway.spec.python))
177
+ if env is None:
178
+ return
179
+ node.workerinput["python_version"] = env.version
180
+ state.xdist_sys_path[:] = [*state.sys_path_head, *env.sys_path]
181
+
182
+
183
+ def pytest_unconfigure(config: pytest.Config) -> None:
184
+ state = config.stash.get(_STATE, None)
185
+ if state is not None and state.xdist_sys_path is not None:
186
+ state.xdist_sys_path[:] = state.original_sys_path
187
+
188
+
189
+ def pytest_report_header(config: pytest.Config) -> str | None:
190
+ state = config.stash.get(_STATE, None)
191
+ if state is None:
192
+ return None
193
+ if state.envs:
194
+ listed = [f"{e.version} ({e.full_version})" for e in state.envs.values()]
195
+ else:
196
+ listed = state.versions
197
+ return "pytest-uv: " + ", ".join(listed)
198
+
199
+
200
+ @pytest.fixture(scope="session")
201
+ def python_version(request: pytest.FixtureRequest) -> str | None:
202
+ """The version this worker was started for (e.g. ``"3.13"``).
203
+
204
+ ``None`` when not running under ``--python-versions``.
205
+ """
206
+ return _worker_python_version(request.config)
207
+
208
+
209
+ def _worker_python_version(config: Any) -> str | None:
210
+ workerinput = getattr(config, "workerinput", None)
211
+ if workerinput is None:
212
+ return None
213
+ return workerinput.get("python_version")
214
+
215
+
216
+ def _make_log(config: pytest.Config) -> Log | None:
217
+ if config.option.verbose <= 0:
218
+ return None
219
+ lock = threading.Lock()
220
+
221
+ def log(line: str) -> None:
222
+ with lock:
223
+ sys.stderr.write(line + "\n")
224
+ sys.stderr.flush()
225
+
226
+ return log
227
+
228
+
229
+ def _find_uv() -> str:
230
+ uv = os.environ.get("UV") or shutil.which("uv")
231
+ if not uv:
232
+ raise pytest.UsageError("pytest-uv: uv executable not found on PATH")
233
+ return uv
234
+
235
+
236
+ def _load_pyproject(root: Path) -> dict[str, Any]:
237
+ path = root / "pyproject.toml"
238
+ if not path.exists():
239
+ return {}
240
+ with path.open("rb") as f:
241
+ return tomllib.load(f)
pytest_uv/resolver.py ADDED
@@ -0,0 +1,123 @@
1
+ """Version resolution: determine which Python versions to test against."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import subprocess
8
+ from collections.abc import Iterable
9
+ from typing import Any
10
+
11
+ from packaging.specifiers import SpecifierSet
12
+ from packaging.version import InvalidVersion, Version
13
+
14
+ _VERSION_RE = re.compile(r"[A-Za-z]*\d+(\.\d+){0,2}[A-Za-z0-9]*")
15
+
16
+
17
+ def resolve_versions(mode: str, pyproject: dict[str, Any], uv: str = "uv") -> list[str]:
18
+ """Resolve Python versions based on the given mode.
19
+
20
+ Args:
21
+ mode: 'auto', 'declared', or a comma-separated list like '3.11,3.12'.
22
+ Explicit and declared entries are passed to uv as-is, so requests
23
+ such as '3.14t' or '3.15' (pre-release) work there.
24
+ pyproject: Parsed pyproject.toml contents.
25
+ uv: Path to the uv executable.
26
+
27
+ Returns:
28
+ Sorted, de-duplicated list of version requests, e.g. ['3.11', '3.12'].
29
+
30
+ Raises:
31
+ ValueError: If the mode is unknown, configuration is missing, or a
32
+ version request is malformed.
33
+ """
34
+ mode = mode.strip()
35
+
36
+ if mode == "declared":
37
+ try:
38
+ declared = pyproject["tool"]["pytest-uv"]["versions"]
39
+ except (KeyError, TypeError) as exc:
40
+ raise ValueError(
41
+ "Mode 'declared' requires [tool.pytest-uv].versions in pyproject.toml"
42
+ ) from exc
43
+ if not isinstance(declared, list) or not all(
44
+ isinstance(v, str) for v in declared
45
+ ):
46
+ raise ValueError(
47
+ "[tool.pytest-uv].versions must be a list of strings, "
48
+ 'e.g. ["3.12", "3.13"]'
49
+ )
50
+ return _normalize(declared)
51
+
52
+ if mode == "auto":
53
+ try:
54
+ requires_python = pyproject["project"]["requires-python"]
55
+ except (KeyError, TypeError) as exc:
56
+ raise ValueError(
57
+ "Mode 'auto' requires [project].requires-python in pyproject.toml"
58
+ ) from exc
59
+ spec = SpecifierSet(requires_python)
60
+ return _normalize(
61
+ f"{v.major}.{v.minor}" for v in get_installed_versions(uv) if v in spec
62
+ )
63
+
64
+ return _normalize(mode.split(","))
65
+
66
+
67
+ def _normalize(requests: Iterable[str]) -> list[str]:
68
+ unique: list[str] = []
69
+ for raw in requests:
70
+ request = raw.strip()
71
+ if not request:
72
+ continue
73
+ if not _VERSION_RE.fullmatch(request):
74
+ raise ValueError(
75
+ f"invalid Python version {request!r}; expected 'auto', "
76
+ "'declared' or a list like '3.12,3.13'"
77
+ )
78
+ if request not in unique:
79
+ unique.append(request)
80
+ return sorted(unique, key=_sort_key)
81
+
82
+
83
+ def _sort_key(request: str) -> tuple[Any, ...]:
84
+ match = re.search(r"\d+(\.\d+)*", request)
85
+ numeric = tuple(int(p) for p in match.group().split(".")) if match else ()
86
+ return (numeric, request)
87
+
88
+
89
+ def get_installed_versions(uv: str = "uv") -> list[Version]:
90
+ """Return final CPython releases (default builds) that uv finds installed."""
91
+ cmd = [uv, "python", "list", "--only-installed", "--output-format", "json"]
92
+ result = subprocess.run(
93
+ cmd, capture_output=True, encoding="utf-8", errors="replace"
94
+ )
95
+ if result.returncode != 0:
96
+ raise ValueError(
97
+ f"{' '.join(cmd)} failed with exit code {result.returncode}\n"
98
+ f"{result.stderr.rstrip()}"
99
+ )
100
+ return parse_uv_python_list(result.stdout)
101
+
102
+
103
+ def parse_uv_python_list(output: str) -> list[Version]:
104
+ """Parse ``uv python list --output-format json`` output.
105
+
106
+ Keeps only CPython, the default (GIL) variant and final releases, so
107
+ free-threaded, debug and pre-release interpreters are never picked by
108
+ 'auto'.
109
+ """
110
+ versions: list[Version] = []
111
+ for entry in json.loads(output or "[]"):
112
+ if entry.get("implementation") != "cpython":
113
+ continue
114
+ if entry.get("variant", "default") != "default":
115
+ continue
116
+ try:
117
+ version = Version(entry["version"])
118
+ except (KeyError, InvalidVersion):
119
+ continue
120
+ if version.is_prerelease or version.is_devrelease:
121
+ continue
122
+ versions.append(version)
123
+ return versions
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.5
2
+ Name: pytest-uv
3
+ Version: 0.1.0
4
+ Summary: Multi-version Python testing with uv and pytest-xdist
5
+ Project-URL: Homepage, https://github.com/jirikuncar/pytest-uv
6
+ Project-URL: Documentation, https://jirikuncar.github.io/pytest-uv/
7
+ Project-URL: Repository, https://github.com/jirikuncar/pytest-uv
8
+ Project-URL: Issues, https://github.com/jirikuncar/pytest-uv/issues
9
+ Project-URL: Changelog, https://github.com/jirikuncar/pytest-uv/blob/main/CHANGELOG.md
10
+ Author-email: Jiri Kuncar <jiri.kuncar@gmail.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: multi-version,nox,pytest,python-versions,testing,tox,uv,xdist
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Framework :: Pytest
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: MacOS
19
+ Classifier: Operating System :: POSIX :: Linux
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Programming Language :: Python :: 3.15
27
+ Classifier: Programming Language :: Python :: Implementation :: CPython
28
+ Classifier: Topic :: Software Development :: Testing
29
+ Requires-Python: >=3.11
30
+ Requires-Dist: packaging
31
+ Requires-Dist: pytest-xdist>=3.0
32
+ Requires-Dist: pytest>=7.0
33
+ Description-Content-Type: text/markdown
34
+
35
+ # pytest-uv
36
+
37
+ [![PyPI](https://img.shields.io/pypi/v/pytest-uv.svg)](https://pypi.org/project/pytest-uv/)
38
+ [![Python versions](https://img.shields.io/pypi/pyversions/pytest-uv.svg)](https://pypi.org/project/pytest-uv/)
39
+ [![CI](https://github.com/jirikuncar/pytest-uv/actions/workflows/ci.yml/badge.svg)](https://github.com/jirikuncar/pytest-uv/actions/workflows/ci.yml)
40
+ [![Docs](https://github.com/jirikuncar/pytest-uv/actions/workflows/docs.yml/badge.svg)](https://jirikuncar.github.io/pytest-uv/)
41
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
42
+
43
+ > [!WARNING]
44
+ > pytest-uv is in early development (alpha). Options, configuration and behaviour may
45
+ > change between releases without a deprecation period. Worker isolation relies on a
46
+ > private pytest-xdist attribute, tested with xdist 3.0 to 3.8. Please
47
+ > [report issues](https://github.com/jirikuncar/pytest-uv/issues).
48
+
49
+ Run your test suite on every Python version you support, in one `pytest` command.
50
+
51
+ pytest-uv builds a virtual environment per version with [uv](https://docs.astral.sh/uv/),
52
+ starts one [pytest-xdist](https://github.com/pytest-dev/pytest-xdist) worker in each, and
53
+ runs every test once per version. Failures from all versions come back in one report,
54
+ so a test that breaks only on 3.11 shows up before you push.
55
+
56
+ **Documentation: [jirikuncar.github.io/pytest-uv](https://jirikuncar.github.io/pytest-uv/)**
57
+
58
+ ```bash
59
+ uv add --dev pytest-uv
60
+ uv run pytest --python-versions 3.11,3.12,3.13
61
+ ```
62
+
63
+ ```text
64
+ created: 3/3 workers
65
+ 3 workers [4 items]
66
+ ............ [100%]
67
+ ============================== 12 passed in 2.01s ==============================
68
+ ```
69
+
70
+ **Fits if** your project has a `pyproject.toml`, uv is on `PATH`, and the matrix you
71
+ care about is Python versions. Needs Python 3.11+.
72
+
73
+ | | |
74
+ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
75
+ | Versions | An explicit list, `declared` (`[tool.pytest-uv] versions`), or `auto` (installed interpreters allowed by `requires-python`) |
76
+ | Environments | `.pytest-uv/py<version>`, synced from `uv.lock` with `uv sync --frozen`, or installed with `uv pip install` without a lock file; built in parallel, reused until inputs change |
77
+ | Isolation | Each worker imports only from its own environment; your `.venv` is untouched |
78
+ | In tests | `sys.version_info` markers as usual, plus a `python_version` fixture (`"3.13"`) |
79
+ | Not for | Running linters or docs per version, dependency-version matrices (use tox or nox), or one version over many CPUs (use `pytest -n auto`) |
80
+
81
+ ## Usage
82
+
83
+ ```bash
84
+ pytest --python-versions 3.12,3.13 # these versions; uv downloads missing ones
85
+ pytest --python-versions declared # [tool.pytest-uv] versions
86
+ pytest --python-versions auto # installed CPython matching requires-python
87
+ pytest --python-versions 3.13 --lf # re-run last failures on one version
88
+ ```
89
+
90
+ ```toml
91
+ [tool.pytest-uv]
92
+ versions = ["3.11", "3.12", "3.13", "3.14"]
93
+ venv-dir = ".pytest-uv" # ignored by git automatically
94
+ sync-args = ["--no-default-groups", "--group", "test"] # with uv.lock
95
+ install-args = ["-e", ".", "--group", "test"] # without uv.lock
96
+ ```
97
+
98
+ `-n` and `--pdb` cannot be combined with `--python-versions`: each version gets exactly
99
+ one worker, and workers have no terminal. To debug interactively, run the version's
100
+ interpreter directly:
101
+ `.pytest-uv/py3.13/bin/python -m pytest tests/test_foo.py::test_bar --pdb`.
102
+
103
+ In GitHub Actions, one step runs the suite on every supported version:
104
+
105
+ ```yaml
106
+ - uses: jirikuncar/pytest-uv@v0.1.0
107
+ with:
108
+ python-versions: auto
109
+ ```
110
+
111
+ More in the docs: [Quickstart](https://jirikuncar.github.io/pytest-uv/quickstart/),
112
+ [GitHub Actions](https://jirikuncar.github.io/pytest-uv/recipes/ci/),
113
+ [Debugging failures](https://jirikuncar.github.io/pytest-uv/guide/debugging/),
114
+ [Configuration](https://jirikuncar.github.io/pytest-uv/reference/configuration/),
115
+ [Comparisons with tox, nox and xdist](https://jirikuncar.github.io/pytest-uv/alternatives/).
116
+ Runnable projects are in [`examples/`](https://github.com/jirikuncar/pytest-uv/tree/main/examples).
117
+
118
+ ## Coding agents
119
+
120
+ In Claude Code:
121
+
122
+ ```text
123
+ /plugin marketplace add jirikuncar/pytest-uv
124
+ /plugin install pytest-uv@pytest-uv
125
+ ```
126
+
127
+ Other agents: [Coding agents](https://jirikuncar.github.io/pytest-uv/recipes/agents/).
128
+ The docs are also available as [`llms.txt`](https://jirikuncar.github.io/pytest-uv/llms.txt)
129
+ and [`llms-full.txt`](https://jirikuncar.github.io/pytest-uv/llms-full.txt).
130
+
131
+ ## Development
132
+
133
+ ```bash
134
+ git clone https://github.com/jirikuncar/pytest-uv
135
+ cd pytest-uv
136
+ uv sync
137
+ uv run pytest tests/test_plugin.py tests/test_envs.py tests/test_resolver.py
138
+ ```
139
+
140
+ See [AGENTS.md](https://github.com/jirikuncar/pytest-uv/blob/main/AGENTS.md) for the architecture and the integration tests.
141
+
142
+ ## License
143
+
144
+ MIT
@@ -0,0 +1,11 @@
1
+ pytest_uv/__init__.py,sha256=QTQseloG5EL01I5rI3wEOxOoN3g83xvF0R783lxq060,183
2
+ pytest_uv/_lock.py,sha256=P7bW_Y2nAte4I7nzo223jaBjE23ljLoSjfPrXnpaQ10,1163
3
+ pytest_uv/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
4
+ pytest_uv/envs.py,sha256=Ojk97ge5HTuqlB4MChkJiO8q13sB6ZsLEpTDEP8I6D8,12506
5
+ pytest_uv/plugin.py,sha256=FKx9yf1oHGJn5wyUFLFt84PKag2IsyfHZelNrhfFsT0,8140
6
+ pytest_uv/resolver.py,sha256=QPCeXdl9Nbt4ZrshlJr-N0IKE5Fzk0AVBS-_2dK4joc,4247
7
+ pytest_uv-0.1.0.dist-info/METADATA,sha256=t1-gvSGjBPnmF_w2p7KNaMODjFdIDmyQnF_KWNWHpMM,7028
8
+ pytest_uv-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ pytest_uv-0.1.0.dist-info/entry_points.txt,sha256=U1SV13i3YGXUlvSn7owSoQHJKMdeT6SrQCB1TNXKo1U,33
10
+ pytest_uv-0.1.0.dist-info/licenses/LICENSE,sha256=amTLUEm2eiSFRlKez3sNqUF-8C2FfeE3d_s5bpWUIxc,1068
11
+ pytest_uv-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ uv = pytest_uv.plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jiri Kuncar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.