pytest-sloppy-tools 0.2.1__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.
@@ -0,0 +1,5 @@
1
+ # __init__.py
2
+ # SPDX-License-Identifier: CC0-1.0
3
+ # This file was created by an AI model: openai/gpt-6.2-sol
4
+
5
+ """Helpers for pytest workflows."""
@@ -0,0 +1,83 @@
1
+ # _parallel.py
2
+ # SPDX-License-Identifier: CC0-1.0
3
+ # This file was created by an AI model: openai/gpt-6.2-sol
4
+
5
+ """Pytest entry point for the Linux parallel runner."""
6
+
7
+ import sys
8
+ from argparse import ArgumentTypeError
9
+
10
+ import pytest
11
+
12
+
13
+ def _worker_count(value: str) -> int:
14
+ try:
15
+ count = int(value)
16
+ except ValueError:
17
+ count = 0
18
+ if count < 1:
19
+ raise ArgumentTypeError("--workers expects a positive integer")
20
+ return count
21
+
22
+
23
+ def pytest_addoption(parser: pytest.Parser) -> None:
24
+ group = parser.getgroup("sloppy-tools", "pytest-sloppy-tools")
25
+ group.addoption(
26
+ "--workers",
27
+ type=_worker_count,
28
+ metavar="N",
29
+ help="run tests on N worker processes (Linux only)",
30
+ )
31
+ group.addoption(
32
+ "--output",
33
+ choices=("live", "batched"),
34
+ help="display worker output live or after each test (required with --workers)",
35
+ )
36
+ group.addoption("--pretty", action="store_true", help="show compact, grouped test progress")
37
+
38
+
39
+ @pytest.hookimpl(trylast=True)
40
+ def pytest_configure(config: pytest.Config) -> None:
41
+ count = config.getoption("workers")
42
+ output = config.getoption("output")
43
+ xdist = config.getoption("numprocesses", 0) or config.getoption("dist", "no") != "no"
44
+ if config.getoption("pretty") and not config.option.collectonly:
45
+ if xdist or config.getoption("distload", False):
46
+ raise pytest.UsageError("--pretty cannot be combined with xdist distribution")
47
+ from ._pretty import _install
48
+
49
+ _install(config, parallel=count is not None)
50
+ if count is None:
51
+ if output is not None:
52
+ raise pytest.UsageError("--output requires --workers")
53
+ return
54
+ if config.option.collectonly:
55
+ return
56
+ if sys.platform != "linux":
57
+ raise pytest.UsageError("--workers is supported only on Linux")
58
+ if xdist:
59
+ raise pytest.UsageError("--workers cannot be combined with xdist distribution")
60
+ if config.getoption("usepdb") or config.getoption("trace"):
61
+ raise pytest.UsageError("--workers does not support interactive debugging")
62
+ if output is None:
63
+ raise pytest.UsageError("--workers requires --output=live or --output=batched")
64
+
65
+
66
+ @pytest.hookimpl(tryfirst=True)
67
+ def pytest_runtestloop(session: pytest.Session) -> bool | None:
68
+ config = session.config
69
+ count = config.getoption("workers")
70
+ if count is None or config.option.collectonly or not session.items:
71
+ return None
72
+ if session.testsfailed and not config.option.continue_on_collection_errors:
73
+ # Let pytest report collection failures.
74
+ return None
75
+ if session.shouldfail:
76
+ raise session.Failed(session.shouldfail)
77
+ if session.shouldstop:
78
+ raise session.Interrupted(session.shouldstop)
79
+
80
+ from ._workers import _run
81
+
82
+ _run(session, count, live=config.getoption("output") == "live")
83
+ return True
@@ -0,0 +1,276 @@
1
+ # _pretty.py
2
+ # SPDX-License-Identifier: CC0-1.0
3
+ # This file was created by an AI model: openai/gpt-6.2-sol
4
+
5
+ """Opt-in progress display for the controller and the serial runner."""
6
+
7
+ from collections import Counter
8
+ from collections.abc import Generator
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass, field
11
+
12
+ import pytest
13
+ from _pytest._io.wcwidth import wcswidth
14
+ from _pytest.capture import CaptureManager
15
+ from _pytest.terminal import TerminalReporter
16
+
17
+
18
+ _PLUGIN = "sloppy-pretty"
19
+ _PROGRESS_GAP = 12
20
+ _PERCENT_WIDTH = 4
21
+ _MARKS = {
22
+ "passed": ("·", {"green": True}),
23
+ "failed": ("×", {"red": True}),
24
+ "skipped": ("s", {"yellow": True}),
25
+ "xfailed": ("x", {"yellow": True}),
26
+ "xpassed": ("X", {"yellow": True}),
27
+ }
28
+
29
+
30
+ @contextmanager
31
+ def _quiet_progress(terminal: TerminalReporter) -> Generator[None]:
32
+ """Keep pytest's report bookkeeping and summary, but suppress its progress."""
33
+ hook = terminal.config.hook
34
+ start = next(impl for impl in hook.pytest_runtest_logstart.get_hookimpls() if impl.plugin is terminal)
35
+ report_hook = next(impl for impl in hook.pytest_runtest_logreport.get_hookimpls() if impl.plugin is terminal)
36
+ original = start.function, report_hook.function, terminal._show_progress_info
37
+
38
+ def logstart(nodeid: str, location: tuple[str, int | None, str]) -> None:
39
+ pass
40
+
41
+ def logreport(report: pytest.TestReport) -> None:
42
+ terminal._current_logreport = report
43
+ terminal._tests_ran = True
44
+ category, letter, word = hook.pytest_report_teststatus(report=report, config=terminal.config)
45
+ terminal._add_stats(category, [report])
46
+ if letter or word:
47
+ terminal._progress_nodeids_reported.add(getattr(report, "id", report.nodeid))
48
+
49
+ # Pluggy binds these callables at registration. Change only this reporter's
50
+ # implementations for the run loop, not the status hook used by summaries.
51
+ start.function, report_hook.function, terminal._show_progress_info = logstart, logreport, False
52
+ try:
53
+ yield
54
+ finally:
55
+ start.function, report_hook.function, terminal._show_progress_info = original
56
+
57
+
58
+ @dataclass(eq=False)
59
+ class _Row:
60
+ label: str
61
+ size: int = 0
62
+ marks: dict[int, str] = field(default_factory=dict)
63
+ fresh: set[int] = field(default_factory=set)
64
+
65
+
66
+ @dataclass
67
+ class _Case:
68
+ row: _Row
69
+ slot: int
70
+ outcome: str | None = None
71
+ output_shown: bool = False
72
+
73
+
74
+ def _function(item: pytest.Item) -> tuple[str, str]:
75
+ name = item.originalname if isinstance(item, pytest.Function) else item.name
76
+ return (item.parent.nodeid if item.parent is not None else "", name)
77
+
78
+
79
+ class _Pretty:
80
+ def __init__(self, terminal: TerminalReporter, *, parallel: bool) -> None:
81
+ self.terminal = terminal
82
+ self.parallel = parallel
83
+ config = terminal.config
84
+ capture = config.getoption("capture", "no")
85
+ self.raw_streams = not parallel and capture in ("no", "tee-sys")
86
+ self.direct_streams = not parallel and capture != "fd"
87
+ self.live_logs = (
88
+ not parallel
89
+ and config.pluginmanager.hasplugin("logging")
90
+ and (config.getoption("log_cli_level") is not None or config.getini("log_cli"))
91
+ )
92
+ interactive = any(config.getoption(option) for option in ("usepdb", "trace", "setupshow", "setuponly"))
93
+ self.direct_output = not parallel and (self.direct_streams or self.live_logs or interactive)
94
+ self.in_place = bool(terminal.isatty) and not self.direct_output
95
+ self.cases: list[_Case] = []
96
+ self.rows: dict[tuple[str, str], _Row] = {}
97
+ self.indices: dict[int, int] = {}
98
+ self.percent_column = 0
99
+ self.completed = 0
100
+ self.open_row: _Row | None = None
101
+ self.serial_index: int | None = None
102
+ self.sections: list[tuple[str, str]] = []
103
+
104
+ def _prepare(self, items: list[pytest.Item]) -> None:
105
+ keys = [_function(item) for item in items]
106
+ counts = Counter(name for _, name in dict.fromkeys(keys))
107
+ for index, (item, key) in enumerate(zip(items, keys, strict=True)):
108
+ parent, name = key
109
+ if key not in self.rows:
110
+ label = f"{parent}::{name}" if counts[name] > 1 and parent else name
111
+ self.rows[key] = _Row(label if label.isprintable() else repr(label))
112
+ row = self.rows[key]
113
+ self.cases.append(_Case(row, row.size))
114
+ row.size += 1
115
+ self.indices[id(item)] = index
116
+ self.percent_column = max(wcswidth(row.label) + 2 + row.size for row in self.rows.values()) + _PROGRESS_GAP
117
+
118
+ def _can_rewrite(self) -> bool:
119
+ return self.in_place and self.percent_column + _PERCENT_WIDTH < self.terminal._tw.fullwidth
120
+
121
+ def _seal(self) -> None:
122
+ if self.open_row is not None:
123
+ self.terminal.write("\n", flush=True)
124
+ self.open_row.fresh.clear()
125
+ self.open_row = None
126
+
127
+ def _show(self, row: _Row, *, seal: bool = False) -> None:
128
+ writer = self.terminal._tw
129
+ last = max(row.marks, default=-1)
130
+ progress = f"{self.completed * 100 // len(self.cases)}%".rjust(_PERCENT_WIDTH)
131
+ label = f"{row.label} "
132
+ body_width = wcswidth(label) + last + 1
133
+ in_place = self._can_rewrite() and not seal
134
+ if self.open_row is not row or not in_place:
135
+ self._seal()
136
+ marks = []
137
+ for slot in range(last + 1):
138
+ if slot in row.marks:
139
+ symbol, colour = _MARKS[row.marks[slot]]
140
+ marks.append(writer.markup(symbol, **(colour if slot in row.fresh else {"light": True})))
141
+ else:
142
+ marks.append(" ")
143
+ line = f"{label}{''.join(marks)}{' ' * (self.percent_column - body_width)}{progress}"
144
+ prefix = "\r" if self.open_row is row else ""
145
+ self.terminal.write(prefix + line + ("" if in_place else "\n"), flush=True)
146
+ if in_place:
147
+ self.open_row = row
148
+ else:
149
+ row.fresh.clear()
150
+
151
+ def start(self, index: int) -> None:
152
+ row = self.cases[index].row
153
+ if self._can_rewrite() and (self.open_row is None or not self.parallel and self.open_row is not row):
154
+ self._show(row)
155
+
156
+ def report(self, index: int, report: pytest.TestReport) -> None:
157
+ case = self.cases[index]
158
+ if report.failed:
159
+ case.outcome = "failed"
160
+ elif case.outcome != "failed":
161
+ if report.skipped:
162
+ case.outcome = "xfailed" if hasattr(report, "wasxfail") else "skipped"
163
+ elif report.when == "call":
164
+ case.outcome = "xpassed" if hasattr(report, "wasxfail") else "passed"
165
+
166
+ def _before_output(self, index: int) -> None:
167
+ case = self.cases[index]
168
+ if not case.output_shown and self.open_row is not case.row:
169
+ self._show(case.row, seal=True)
170
+ else:
171
+ self._seal()
172
+ case.output_shown = True
173
+
174
+ def heading(self, index: int, title: str) -> None:
175
+ self._before_output(index)
176
+ self.terminal.write(f"{title}\n", flush=True)
177
+
178
+ @contextmanager
179
+ def _serial_capture(self) -> Generator[None]:
180
+ capture = self.terminal.config.pluginmanager.get_plugin("capturemanager")
181
+ if self.parallel or self.direct_output or not isinstance(capture, CaptureManager):
182
+ yield
183
+ return
184
+
185
+ original = capture.global_and_fixture_disabled
186
+
187
+ @contextmanager
188
+ def disabled() -> Generator[None]:
189
+ # Capture fixtures can send output straight to the terminal.
190
+ with original():
191
+ index = self.serial_index
192
+ if index is not None:
193
+ self._before_output(index)
194
+ try:
195
+ yield
196
+ finally:
197
+ if index is not None:
198
+ self.terminal.write("\n", flush=True)
199
+
200
+ capture.global_and_fixture_disabled = disabled
201
+ try:
202
+ yield
203
+ finally:
204
+ capture.global_and_fixture_disabled = original
205
+
206
+ def finish(self, index: int) -> None:
207
+ case = self.cases[index]
208
+ self.completed += 1
209
+ row = case.row
210
+ if case.outcome is not None:
211
+ row.marks[case.slot] = case.outcome
212
+ row.fresh.add(case.slot)
213
+ if self._can_rewrite() or self.direct_output or case.output_shown or len(row.marks) == row.size:
214
+ self._show(row)
215
+
216
+ @pytest.hookimpl(wrapper=True, tryfirst=True)
217
+ def pytest_runtestloop(self, session: pytest.Session) -> Generator[None, object, object]:
218
+ if not session.items:
219
+ return (yield)
220
+ self._prepare(session.items)
221
+ self.terminal.ensure_newline()
222
+ with _quiet_progress(self.terminal), self._serial_capture():
223
+ try:
224
+ return (yield)
225
+ finally:
226
+ self._seal()
227
+ for row in self.rows.values():
228
+ if row.fresh:
229
+ self._show(row, seal=True)
230
+
231
+ @pytest.hookimpl(wrapper=True, tryfirst=True)
232
+ def pytest_runtest_protocol(self, item: pytest.Item) -> Generator[None, object, object]:
233
+ if self.parallel:
234
+ return (yield)
235
+ index = self.indices[id(item)]
236
+ self.serial_index = index
237
+ self.sections = []
238
+ self.start(index)
239
+ try:
240
+ result = yield
241
+ if self.direct_streams:
242
+ # Native output can bypass capture and omit the trailing newline.
243
+ self.terminal.write("\n", flush=True)
244
+ for title, text in self.sections:
245
+ parts = title.split()
246
+ if len(parts) < 2 or parts[0] != "Captured" or not text:
247
+ continue
248
+ stream = parts[1]
249
+ if stream == "log" and self.live_logs or stream in ("stdout", "stderr") and self.raw_streams:
250
+ continue
251
+ self.heading(index, f"--- {item.nodeid} [{stream}] ---")
252
+ self.terminal.write(text if text.endswith("\n") else text + "\n", flush=True)
253
+ self.finish(index)
254
+ return result
255
+ finally:
256
+ self.serial_index = None
257
+
258
+ @pytest.hookimpl(trylast=True)
259
+ def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
260
+ if self.serial_index is not None:
261
+ self.report(self.serial_index, report)
262
+ # Each phase report includes the sections from earlier phases.
263
+ self.sections = report.sections
264
+
265
+
266
+ def _install(config: pytest.Config, *, parallel: bool) -> None:
267
+ terminal = config.pluginmanager.get_plugin("terminalreporter")
268
+ if isinstance(terminal, TerminalReporter):
269
+ if (progress := config.pluginmanager.get_plugin("terminalprogress")) is not None:
270
+ config.pluginmanager.unregister(progress)
271
+ config.pluginmanager.register(_Pretty(terminal, parallel=parallel), _PLUGIN)
272
+
273
+
274
+ def _get_pretty(config: pytest.Config) -> _Pretty | None:
275
+ plugin = config.pluginmanager.get_plugin(_PLUGIN)
276
+ return plugin if isinstance(plugin, _Pretty) else None
@@ -0,0 +1,379 @@
1
+ # _workers.py
2
+ # SPDX-License-Identifier: CC0-1.0
3
+ # This file was created by an AI model: openai/gpt-6.2-sol
4
+
5
+ """Worker lifecycle, output transport, and report relay."""
6
+
7
+ import codecs
8
+ import io
9
+ import logging
10
+ import os
11
+ import signal
12
+ import sys
13
+ import threading
14
+ import time
15
+ import traceback
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from multiprocessing import Pipe
19
+ from multiprocessing.connection import Connection, wait
20
+ from pathlib import Path
21
+ from tempfile import TemporaryDirectory
22
+ from typing import BinaryIO, Never
23
+ from warnings import WarningMessage
24
+
25
+ import pytest
26
+ from _pytest.capture import CaptureManager
27
+ from _pytest.warnings import warning_record_to_str
28
+
29
+ from ._pretty import _get_pretty
30
+
31
+
32
+ _STREAMS = ("stdout", "stderr")
33
+ _CHUNK_SIZE = 64 * 1024
34
+
35
+
36
+ def _item_queues(size: int, count: int) -> list[range]:
37
+ """Distribute collected item indices, keeping collection order within each worker."""
38
+ return [range(start, size, count) for start in range(count)]
39
+
40
+
41
+ def _stream_path(directory: Path, index: int, stream: str) -> Path:
42
+ return directory / f"{index}.{stream}"
43
+
44
+
45
+ def _flush() -> None:
46
+ sys.stdout.flush()
47
+ sys.stderr.flush()
48
+
49
+
50
+ def _configure_worker(config: pytest.Config, basetemp: Path) -> None:
51
+ manager = config.pluginmanager
52
+ terminal = manager.get_plugin("terminalreporter")
53
+ if terminal is not None:
54
+ manager.unregister(terminal)
55
+ if (pretty := _get_pretty(config)) is not None:
56
+ manager.unregister(pretty)
57
+
58
+ # Disable global capture in the child only. The new capture manager still
59
+ # activates capsys and capfd when tests request them.
60
+ capture = manager.get_plugin("capturemanager")
61
+ if isinstance(capture, CaptureManager):
62
+ capture.stop_global_capturing()
63
+ manager.unregister(capture)
64
+ worker_capture = CaptureManager("no")
65
+ worker_capture.start_global_capturing()
66
+ manager.register(worker_capture, "capturemanager")
67
+
68
+ if (factory := getattr(config, "_tmp_path_factory", None)) is not None:
69
+ basetemp.mkdir(mode=0o700)
70
+ factory._basetemp = basetemp
71
+
72
+ with open(os.devnull, "rb") as stdin:
73
+ os.dup2(stdin.fileno(), 0)
74
+ for stream in (sys.stdout, sys.stderr):
75
+ if isinstance(stream, io.TextIOWrapper):
76
+ stream.reconfigure(line_buffering=True, write_through=True)
77
+
78
+ # Keep pytest's caplog handler and report sections. Move its terminal
79
+ # logging to the worker's stderr so both output modes display records.
80
+ root = logging.getLogger()
81
+ log_plugin = manager.get_plugin("logging-plugin")
82
+ if log_plugin is not None:
83
+ root.removeHandler(log_plugin.log_cli_handler)
84
+ formatter = log_plugin.log_cli_handler.formatter or log_plugin.formatter
85
+ level = log_plugin.log_cli_level
86
+ if level is None:
87
+ level = log_plugin.log_level
88
+ else:
89
+ level = None
90
+ formatter = logging.Formatter("%(levelname)s %(name)s: %(message)s")
91
+ level = logging.WARNING if level is None else level
92
+ handler = logging.StreamHandler(sys.stderr)
93
+ handler.setFormatter(formatter)
94
+ handler.setLevel(level)
95
+ root.addHandler(handler)
96
+ root.setLevel(min(root.level, level))
97
+
98
+
99
+ @dataclass(eq=False)
100
+ class _WorkerReports:
101
+ channel: Connection
102
+ config: pytest.Config
103
+
104
+ def pytest_runtest_logstart(self, nodeid: str, location: tuple[str, int | None, str]) -> None:
105
+ self.channel.send(("logstart", (nodeid, location)))
106
+
107
+ def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
108
+ payload = self.config.hook.pytest_report_to_serializable(config=self.config, report=report)
109
+ self.channel.send(("report", payload))
110
+
111
+ def pytest_runtest_logfinish(self, nodeid: str, location: tuple[str, int | None, str]) -> None:
112
+ self.channel.send(("logfinish", (nodeid, location)))
113
+
114
+ def pytest_warning_recorded(self, warning_message: WarningMessage, when: str) -> None:
115
+ if when == "runtest" and not self.config.getoption("disable_warnings"):
116
+ sys.stderr.write(warning_record_to_str(warning_message))
117
+
118
+
119
+ def _work(session: pytest.Session, queue: range, channel: Connection, directory: Path, basetemp: Path) -> None:
120
+ _configure_worker(session.config, basetemp)
121
+ session.config.pluginmanager.register(_WorkerReports(channel, session.config))
122
+ for position, index in enumerate(queue):
123
+ item = session.items[index]
124
+ nextitem = session.items[queue[position + 1]] if position + 1 < len(queue) else None
125
+ for fd, stream in enumerate(_STREAMS, start=1):
126
+ with _stream_path(directory, index, stream).open("wb") as output:
127
+ os.dup2(output.fileno(), fd)
128
+ channel.send(("begin", index))
129
+ item.ihook.pytest_runtest_protocol(item=item, nextitem=nextitem)
130
+ _flush()
131
+ channel.send(("decision", (str(session.shouldstop or ""), nextitem is not None)))
132
+ proceed = channel.recv()
133
+ if not proceed:
134
+ # On an early stop, the last protocol may have kept broader-scoped
135
+ # fixtures for a queued item that will no longer run.
136
+ session._setupstate.teardown_exact(None)
137
+ _flush()
138
+ channel.send(("end", None))
139
+ if not proceed:
140
+ break
141
+
142
+
143
+ class _Output:
144
+ def __init__(self, directory: Path, index: int, nodeid: str) -> None:
145
+ self.index = index
146
+ self.nodeid = nodeid
147
+ self.paths = [_stream_path(directory, index, stream) for stream in _STREAMS]
148
+ self.files: list[BinaryIO] = []
149
+ self.decoders = [codecs.getincrementaldecoder("utf-8")(errors="replace") for _ in _STREAMS]
150
+ try:
151
+ for path in self.paths:
152
+ self.files.append(path.open("rb"))
153
+ except BaseException:
154
+ self.close()
155
+ raise
156
+
157
+ def show(self, heading: Callable[[int, str], None], write: Callable[[str], None], *, final: bool) -> None:
158
+ for stream, file, decoder in zip(_STREAMS, self.files, self.decoders, strict=True):
159
+ size = os.fstat(file.fileno()).st_size - file.tell()
160
+ if not final:
161
+ size = min(size, _CHUNK_SIZE)
162
+ title = f"--- {self.nodeid} [{stream}] ---"
163
+ last = ""
164
+ while size:
165
+ data = file.read(min(size, _CHUNK_SIZE))
166
+ if not data:
167
+ break
168
+ size -= len(data)
169
+ if text := decoder.decode(data):
170
+ if not last:
171
+ heading(self.index, title)
172
+ write(text)
173
+ last = text[-1]
174
+ if final and (tail := decoder.decode(b"", final=True)):
175
+ if not last:
176
+ heading(self.index, title)
177
+ write(tail)
178
+ last = tail[-1]
179
+ if last and last != "\n":
180
+ write("\n")
181
+
182
+ def close(self) -> None:
183
+ for file in self.files:
184
+ file.close()
185
+ for path in self.paths:
186
+ path.unlink(missing_ok=True)
187
+
188
+
189
+ @dataclass
190
+ class _Worker:
191
+ pid: int
192
+ channel: Connection
193
+ item: pytest.Item | None = None
194
+ output: _Output | None = None
195
+ stopping: bool = False
196
+
197
+
198
+ def _spawn(session: pytest.Session, queue: range, directory: Path, basetemp: Path, workers: list[_Worker]) -> None:
199
+ parent, child = Pipe()
200
+ try:
201
+ pid = os.fork()
202
+ except BaseException:
203
+ parent.close()
204
+ child.close()
205
+ raise
206
+ if pid == 0:
207
+ exit_code = 1
208
+ try:
209
+ os.setpgid(0, 0)
210
+ parent.close()
211
+ for worker in workers:
212
+ worker.channel.close()
213
+ _work(session, queue, child, directory, basetemp)
214
+ exit_code = 0
215
+ except KeyboardInterrupt:
216
+ child.send(("interrupt", None))
217
+ except pytest.exit.Exception as exc:
218
+ child.send(("exit", (str(exc), exc.returncode)))
219
+ except BaseException:
220
+ child.send(("error", traceback.format_exc()))
221
+ finally:
222
+ os._exit(exit_code)
223
+ workers.append(_Worker(pid, parent))
224
+ child.close()
225
+
226
+
227
+ def _abort(workers: list[_Worker]) -> None:
228
+ if not workers:
229
+ return
230
+ for sig in (signal.SIGTERM, signal.SIGKILL):
231
+ for worker in workers:
232
+ try:
233
+ os.killpg(worker.pid, sig)
234
+ except ProcessLookupError:
235
+ # The child may not have created its process group yet.
236
+ try:
237
+ os.kill(worker.pid, sig)
238
+ except ProcessLookupError:
239
+ pass
240
+ if sig == signal.SIGTERM:
241
+ time.sleep(0.1)
242
+ for worker in workers:
243
+ os.waitpid(worker.pid, 0)
244
+ worker.channel.close()
245
+
246
+
247
+ def _worker_status(worker: _Worker) -> os.waitid_result | None:
248
+ return os.waitid(os.P_PID, worker.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
249
+
250
+
251
+ def _crash(worker: _Worker) -> Never:
252
+ status = _worker_status(worker)
253
+ detail = ""
254
+ if status is not None:
255
+ reason = "exit status" if status.si_code == os.CLD_EXITED else "signal"
256
+ detail = f" ({reason} {status.si_status})"
257
+ pytest.exit(
258
+ f"parallel worker {worker.pid} exited before finishing its tests{detail}", pytest.ExitCode.INTERNAL_ERROR
259
+ )
260
+
261
+
262
+ def _collect(session: pytest.Session, directory: Path, workers: list[_Worker], *, live: bool) -> None:
263
+ terminal = session.config.pluginmanager.get_plugin("terminalreporter")
264
+ pretty = _get_pretty(session.config)
265
+
266
+ def heading(index: int, title: str) -> None:
267
+ if pretty is not None:
268
+ pretty.heading(index, title)
269
+ return
270
+ if terminal is not None:
271
+ terminal.ensure_newline()
272
+ write(f"\n{title}\n")
273
+
274
+ def write(text: str) -> None:
275
+ if terminal is None:
276
+ print(text, end="", flush=True)
277
+ else:
278
+ terminal.write(text, flush=True)
279
+
280
+ try:
281
+ while workers:
282
+ ready = wait([worker.channel for worker in workers], timeout=0.05 if live else 0.1)
283
+ for worker in workers[:]:
284
+ if worker.channel not in ready:
285
+ # A forked grandchild may still hold open the control socket.
286
+ if _worker_status(worker) is not None and not worker.channel.poll():
287
+ _crash(worker)
288
+ if live and worker.output is not None:
289
+ worker.output.show(heading, write, final=False)
290
+ continue
291
+ try:
292
+ event, data = worker.channel.recv()
293
+ except (EOFError, ConnectionError):
294
+ _crash(worker)
295
+ if event == "begin":
296
+ worker.item = session.items[data]
297
+ worker.output = _Output(directory, data, worker.item.nodeid)
298
+ if pretty is not None:
299
+ pretty.start(data)
300
+ elif event == "interrupt":
301
+ raise KeyboardInterrupt
302
+ elif event == "exit":
303
+ pytest.exit(data[0], data[1])
304
+ elif event == "error":
305
+ pytest.exit(f"parallel worker {worker.pid} failed:\n{data}", pytest.ExitCode.INTERNAL_ERROR)
306
+ else:
307
+ assert worker.item is not None and worker.output is not None
308
+ hook = worker.item.ihook
309
+ match event:
310
+ case "logstart":
311
+ hook.pytest_runtest_logstart(nodeid=data[0], location=data[1])
312
+ case "report":
313
+ config = session.config
314
+ report = config.hook.pytest_report_from_serializable(config=config, data=data)
315
+ assert isinstance(report, pytest.TestReport)
316
+ hook.pytest_runtest_logreport(report=report)
317
+ if pretty is not None:
318
+ pretty.report(worker.output.index, report)
319
+ case "logfinish":
320
+ hook.pytest_runtest_logfinish(nodeid=data[0], location=data[1])
321
+ case "decision":
322
+ stop, has_next = data
323
+ if stop and not session.shouldstop:
324
+ session.shouldstop = stop
325
+ worker.stopping = bool(session.shouldfail or session.shouldstop or not has_next)
326
+ try:
327
+ worker.channel.send(not worker.stopping)
328
+ except (EOFError, ConnectionError):
329
+ _crash(worker)
330
+ case "end":
331
+ worker.output.show(heading, write, final=True)
332
+ if pretty is not None:
333
+ pretty.finish(worker.output.index)
334
+ worker.output.close()
335
+ worker.output = worker.item = None
336
+ if worker.stopping:
337
+ _, status = os.waitpid(worker.pid, 0)
338
+ worker.channel.close()
339
+ workers.remove(worker)
340
+ if status:
341
+ pytest.exit(
342
+ f"parallel worker {worker.pid} failed during shutdown",
343
+ pytest.ExitCode.INTERNAL_ERROR,
344
+ )
345
+ if live and worker.output is not None:
346
+ worker.output.show(heading, write, final=False)
347
+ finally:
348
+ _abort(workers)
349
+ for worker in workers:
350
+ if worker.output is not None:
351
+ try:
352
+ worker.output.show(heading, write, final=True)
353
+ finally:
354
+ worker.output.close()
355
+ workers.clear()
356
+
357
+
358
+ def _run(session: pytest.Session, count: int, *, live: bool) -> None:
359
+ if not Path("/proc/self/task").is_dir():
360
+ raise pytest.UsageError("--workers requires /proc")
361
+ if threading.active_count() != 1 or len(os.listdir("/proc/self/task")) != 1:
362
+ raise pytest.UsageError("--workers cannot fork while collection leaves background threads running")
363
+ _flush()
364
+ with TemporaryDirectory(prefix="pytest-sloppy-") as path:
365
+ directory = Path(path)
366
+ factory = getattr(session.config, "_tmp_path_factory", None)
367
+ basetemp = factory.getbasetemp() if factory is not None else directory
368
+ workers: list[_Worker] = []
369
+ try:
370
+ for number, queue in enumerate(_item_queues(len(session.items), min(count, len(session.items)))):
371
+ _spawn(session, queue, directory, basetemp / f"sloppy-{number}", workers)
372
+ except BaseException:
373
+ _abort(workers)
374
+ raise
375
+ _collect(session, directory, workers, live=live)
376
+ if session.shouldfail:
377
+ raise session.Failed(session.shouldfail)
378
+ if session.shouldstop:
379
+ raise session.Interrupted(session.shouldstop)
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.5
2
+ Name: pytest-sloppy-tools
3
+ Version: 0.2.1
4
+ Summary: Helpers and fixtures for pytest workflows
5
+ License-Expression: CC0-1.0
6
+ License-File: LICENSE.txt
7
+ Requires-Python: >=3.13
8
+ Requires-Dist: pytest<10,>=9
9
+ Provides-Extra: cocotb
10
+ Requires-Dist: cocotb>=2.1.0; extra == 'cocotb'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # pytest-sloppy-tools
14
+
15
+ Helpers and fixtures for pytest workflows, including parallel execution for suites
16
+ that launch cocotb simulations.
17
+
18
+ Install from this checkout in a Python 3.13 environment with `uv sync --no-dev`.
19
+ The parallel runner works without cocotb. Add `--extra cocotb` to `uv sync` or
20
+ `uv run` to install cocotb if your tests need it. For development, `uv sync`
21
+ includes cocotb for the simulator integration test, which also requires Linux
22
+ and NVC.
23
+
24
+ Parallel execution is **Linux only**. To run four workers, choose an output mode:
25
+
26
+ ```sh
27
+ uv run --no-dev pytest --workers=4 --output=live --log-cli-level=INFO
28
+ uv run --no-dev pytest --workers=4 --output=batched --log-cli-level=INFO
29
+ ```
30
+
31
+ Each parametrised case is scheduled separately. Output is labelled with its test
32
+ ID and stream, including output from subprocesses that inherit stdout and stderr.
33
+ Omit both options to run pytest normally.
34
+
35
+ Add [`--pretty`](docs/pretty.md) for compact, coloured progress in serial or
36
+ parallel runs. See the [parallel execution guide](docs/parallel.md) for logging,
37
+ fixtures, and simulator build-directory isolation.
@@ -0,0 +1,9 @@
1
+ pytest_sloppy_tools/__init__.py,sha256=GtA3SUlkUFb7va0fDmwfE4gGYaKS4p-PtlYiqs2Vutw,145
2
+ pytest_sloppy_tools/_parallel.py,sha256=_Y2RPNIFRoJkFZ4TfjE3ABc0h92vkizhUoMLsMUfVBk,2645
3
+ pytest_sloppy_tools/_pretty.py,sha256=9VIUpabzIn-2ddkEAh3p3uSlsK4Nq1bvQGXr6Mn_cGE,9613
4
+ pytest_sloppy_tools/_workers.py,sha256=gu-40v2DE9y8oUGNawPGRLiwfNC6Ns5wvKsGbD1P5kY,12453
5
+ pytest_sloppy_tools-0.2.1.dist-info/METADATA,sha256=l53e41U948SkRkPIbSZtrFmFJTAtImR65Or4UBiY8UY,1449
6
+ pytest_sloppy_tools-0.2.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ pytest_sloppy_tools-0.2.1.dist-info/entry_points.txt,sha256=kl8tXQNFeIHUNqQ3wLA7F4X2qWxG3lrGEBc7lUKLApc,56
8
+ pytest_sloppy_tools-0.2.1.dist-info/licenses/LICENSE.txt,sha256=ogEPNDSH0_dhiv_lT3ifVIdgIzHAqNA_SemnxUfPBJk,7048
9
+ pytest_sloppy_tools-0.2.1.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
+ sloppy_tools = pytest_sloppy_tools._parallel
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.