pytest-probability 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.
@@ -0,0 +1,6 @@
1
+ """pytest-probability — empirical pass probabilities for flaky-prone tests."""
2
+
3
+ from pytest_probability.plugin import StepResult, TokenUsage
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["StepResult", "TokenUsage"]
@@ -0,0 +1,704 @@
1
+ """pytest-probability — empirical pass probabilities for flaky-prone tests.
2
+
3
+ Collects ``bench_*.py`` files the way pytest collects ``test_*.py``:
4
+ every module-level ``bench_*`` function is a benchmark — an ordinary
5
+ parametrized generator that yields step results. Each parameter
6
+ combination is a case; every case runs N times; and a pass-fraction
7
+ summary — ``7/10 FLAKY`` — renders after pytest's own output.
8
+
9
+ There is no declaration surface beyond stock pytest:
10
+ ``@pytest.mark.parametrize`` supplies the cases (values arrive as
11
+ function arguments, ids compose pytest-style), ``pytest.param`` names
12
+ and marks individual cases, ``-k``/``-m`` select them, and a function
13
+ with no parametrize marks simply runs as a single case.
14
+
15
+ Design notes:
16
+
17
+ - Multi-run execution is modeled as one pytest item per (case, run),
18
+ so ``-k``, ``-x``, xdist, and JUnit XML all apply per run.
19
+ - Step results ride on ``report.user_properties`` as plain dicts so the
20
+ aggregate survives pytest-xdist's worker-to-controller serialization.
21
+ - A pass fraction only exists across items, so it cannot be attached to
22
+ any single test outcome; it is rendered in ``pytest_terminal_summary``.
23
+ - Steps are consumed by duck-typing (``label``, ``passed``, ``elapsed``,
24
+ ``error``, ``message``, ``cost``, ``usage``), so bench functions may
25
+ yield the ``StepResult`` defined here or any object with the same
26
+ attributes.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import fnmatch
31
+ import hashlib
32
+ import importlib.util
33
+ import json
34
+ import sys
35
+ import time
36
+ from collections import OrderedDict
37
+ from dataclasses import dataclass, field
38
+ from pathlib import Path
39
+ from typing import Any, Callable, Iterator
40
+
41
+ import pytest
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # Author-facing types
45
+ # ---------------------------------------------------------------------------
46
+
47
+
48
+ @dataclass
49
+ class TokenUsage:
50
+ """Token accounting for one model's calls within a step.
51
+
52
+ A step may carry several of these — one per model it touched.
53
+ """
54
+
55
+ model: str = ""
56
+ input_tokens: int = 0
57
+ output_tokens: int = 0
58
+ cached_input_tokens: int = 0
59
+ cost: float = 0.0
60
+
61
+
62
+ @dataclass
63
+ class StepResult:
64
+ """One yielded step of a bench function."""
65
+
66
+ label: str
67
+ passed: bool
68
+ elapsed: float = 0.0
69
+ error: str | None = None
70
+ message: str | None = None
71
+ details: dict[str, Any] = field(default_factory=dict)
72
+ cost: float | None = None
73
+ usage: list[TokenUsage] = field(default_factory=list)
74
+
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # Options
78
+ # ---------------------------------------------------------------------------
79
+
80
+
81
+ def pytest_addoption(parser: pytest.Parser) -> None:
82
+ group = parser.getgroup("probability")
83
+ group.addoption(
84
+ "--prob-runs",
85
+ dest="prob_runs",
86
+ type=int,
87
+ default=None,
88
+ metavar="N",
89
+ help="Run every case N times (default: prob_runs ini or 1)",
90
+ )
91
+ group.addoption(
92
+ "--prob-json",
93
+ dest="prob_json",
94
+ default=None,
95
+ metavar="PATH",
96
+ help="Write a JSON report (fractions, statuses, per-run steps) to PATH",
97
+ )
98
+ group.addoption(
99
+ "--prob-delay",
100
+ dest="prob_delay",
101
+ type=float,
102
+ default=None,
103
+ metavar="SECONDS",
104
+ help="Sleep between case executions, e.g. for rate-limited backends"
105
+ " (default: prob_delay ini or 0)",
106
+ )
107
+ group.addoption(
108
+ "--prob-transpose",
109
+ dest="prob_transpose",
110
+ action="store_true",
111
+ default=None,
112
+ help="Run-major order: run 1 of every case, then run 2, ..."
113
+ " (default: prob_transpose ini or case-major)",
114
+ )
115
+ parser.addini("prob_runs", "Default number of runs per case", default="1")
116
+ parser.addini(
117
+ "prob_delay", "Default seconds between case executions", default="0"
118
+ )
119
+ parser.addini(
120
+ "prob_transpose", "Run-major execution order", type="bool", default=False
121
+ )
122
+ parser.addini(
123
+ "prob_pattern", "Glob pattern for benchmark files", default="bench_*.py"
124
+ )
125
+
126
+
127
+ def _runs(config: pytest.Config) -> int:
128
+ runs = config.getoption("prob_runs")
129
+ if runs is None:
130
+ runs = int(config.getini("prob_runs"))
131
+ return max(1, runs)
132
+
133
+
134
+ # Set once the first bench item of this process has run: the delay
135
+ # applies *between* executions, never before the first. Per-process on
136
+ # purpose — under xdist every worker throttles its own stream.
137
+ _DELAYED_ONCE = pytest.StashKey[bool]()
138
+
139
+
140
+ def _delay(config: pytest.Config) -> float:
141
+ delay = config.getoption("prob_delay")
142
+ if delay is None:
143
+ delay = float(config.getini("prob_delay"))
144
+ return max(0.0, delay)
145
+
146
+
147
+ def _transpose(config: pytest.Config) -> bool:
148
+ transpose = config.getoption("prob_transpose")
149
+ if transpose is None:
150
+ transpose = bool(config.getini("prob_transpose"))
151
+ return transpose
152
+
153
+
154
+ def pytest_configure(config: pytest.Config) -> None:
155
+ config.pluginmanager.register(
156
+ ProbabilityAggregator(config), "probability-aggregator"
157
+ )
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # @pytest.mark.parametrize expansion
162
+ # ---------------------------------------------------------------------------
163
+
164
+
165
+ def _default_param_id(value: Any, argname: str, index: int) -> str:
166
+ if value is None or isinstance(value, (str, int, float, bool)):
167
+ return str(value)
168
+ return f"{argname}{index}"
169
+
170
+
171
+ def _parametrize_variants(
172
+ marks: list,
173
+ ) -> list[tuple[str, dict[str, Any], tuple]]:
174
+ """Expand stacked ``@pytest.mark.parametrize`` decorators.
175
+
176
+ Returns ``(id, params, marks)`` triples — the cartesian product
177
+ across stacked decorators, processed in ``pytestmark`` order so
178
+ composite ids read ``bottom-top`` like pytest's own. ``params`` are
179
+ passed to the bench function as keyword arguments; ``marks`` come
180
+ from ``pytest.param(..., marks=...)`` values. With no parametrize
181
+ marks this returns the single empty variant: an unparametrized
182
+ bench function is one case.
183
+ """
184
+ variants: list[tuple[str, dict[str, Any], tuple]] = [("", {}, ())]
185
+ for mark in marks:
186
+ argnames, argvalues = mark.args[0], mark.args[1]
187
+ names = (
188
+ [n.strip() for n in argnames.split(",")]
189
+ if isinstance(argnames, str)
190
+ else [str(n) for n in argnames]
191
+ )
192
+ ids_opt = mark.kwargs.get("ids")
193
+ expanded: list[tuple[str, dict[str, Any], tuple]] = []
194
+ for prev_id, prev_params, prev_marks in variants:
195
+ for i, value in enumerate(argvalues):
196
+ vid: str | None = None
197
+ vmarks: tuple = ()
198
+ # pytest.param(...) → ParameterSet, duck-typed
199
+ if hasattr(value, "values") and hasattr(value, "marks"):
200
+ vid = value.id
201
+ vmarks = tuple(value.marks)
202
+ vals = tuple(value.values)
203
+ elif len(names) == 1:
204
+ vals = (value,)
205
+ else:
206
+ vals = tuple(value)
207
+ if vid is None:
208
+ if isinstance(ids_opt, (list, tuple)):
209
+ vid = str(ids_opt[i])
210
+ elif callable(ids_opt):
211
+ vid = "-".join(
212
+ str(ids_opt(v) or _default_param_id(v, names[j], i))
213
+ for j, v in enumerate(vals)
214
+ )
215
+ else:
216
+ vid = "-".join(
217
+ _default_param_id(v, names[j], i)
218
+ for j, v in enumerate(vals)
219
+ )
220
+ expanded.append(
221
+ (
222
+ f"{prev_id}-{vid}" if prev_id else vid,
223
+ {**prev_params, **dict(zip(names, vals))},
224
+ prev_marks + vmarks,
225
+ )
226
+ )
227
+ variants = expanded
228
+ return variants
229
+
230
+
231
+ # ---------------------------------------------------------------------------
232
+ # Collection
233
+ # ---------------------------------------------------------------------------
234
+
235
+
236
+ def pytest_collect_file(file_path: Path, parent: pytest.Collector):
237
+ pattern = parent.config.getini("prob_pattern")
238
+ if fnmatch.fnmatch(file_path.name, pattern):
239
+ return BenchFile.from_parent(parent, path=file_path)
240
+ return None
241
+
242
+
243
+ def _import_bench_module(path: Path):
244
+ """Import a benchmark file under a path-unique module name.
245
+
246
+ Import errors propagate so pytest reports them as collection errors.
247
+ """
248
+ digest = hashlib.md5(str(path).encode()).hexdigest()[:8]
249
+ module_name = f"pytest_probability_mods.{path.stem}_{digest}"
250
+ spec = importlib.util.spec_from_file_location(module_name, path)
251
+ if spec is None or spec.loader is None:
252
+ raise ImportError(f"cannot load {path}")
253
+ mod = importlib.util.module_from_spec(spec)
254
+ sys.modules[module_name] = mod
255
+ spec.loader.exec_module(mod)
256
+ return mod
257
+
258
+
259
+ class BenchFile(pytest.File):
260
+ """A collected benchmark file."""
261
+
262
+ _setup_fn: Callable[[], None] | None = None
263
+ _teardown_fn: Callable[[], None] | None = None
264
+
265
+ def collect(self) -> Iterator[pytest.Collector]:
266
+ mod = _import_bench_module(self.path)
267
+
268
+ setup = getattr(mod, "setup", None)
269
+ teardown = getattr(mod, "teardown", None)
270
+ self._setup_fn = setup if callable(setup) else None
271
+ self._teardown_fn = teardown if callable(teardown) else None
272
+
273
+ # Every module-level bench_* callable is a benchmark, in
274
+ # definition order — the same convention pytest applies to
275
+ # test_* functions.
276
+ for name, obj in vars(mod).items():
277
+ if name.startswith("bench_") and callable(obj):
278
+ yield BenchFunction.from_parent(self, name=name, bench_fn=obj)
279
+
280
+ # pytest's SetupState calls collector setup() before the first item
281
+ # under this file and teardown() after the last — once-per-module
282
+ # lifecycle semantics.
283
+ def setup(self) -> None:
284
+ if self._setup_fn is not None:
285
+ self._setup_fn()
286
+
287
+ def teardown(self) -> None:
288
+ if self._teardown_fn is not None:
289
+ self._teardown_fn()
290
+
291
+
292
+ class BenchFunction(pytest.Collector):
293
+ """One ``bench_*`` function: an ordinary parametrized generator.
294
+
295
+ Emits one item per (parameter combination, run). Summary rows are
296
+ namespaced by the function's short name (``bench_classify`` →
297
+ ``classify::<case-id>``) so identical case ids in different
298
+ benchmarks aggregate separately. A function with no parametrize
299
+ marks is a single case named after the function.
300
+ """
301
+
302
+ def __init__(self, *, bench_fn: Callable, **kwargs: Any) -> None:
303
+ super().__init__(**kwargs)
304
+ self.bench_fn = bench_fn
305
+
306
+ def collect(self) -> Iterator[pytest.Item]:
307
+ all_marks = list(getattr(self.bench_fn, "pytestmark", []))
308
+ param_marks = [m for m in all_marks if m.name == "parametrize"]
309
+ other_marks = [m for m in all_marks if m.name != "parametrize"]
310
+ variants = _parametrize_variants(param_marks)
311
+ runs = _runs(self.config)
312
+ short = self.name.removeprefix("bench_") or self.name
313
+
314
+ if _transpose(self.config):
315
+ # Run-major: run 1 of every case, then run 2, ...
316
+ pairs = [
317
+ (variant, run_id)
318
+ for run_id in range(1, runs + 1)
319
+ for variant in variants
320
+ ]
321
+ else:
322
+ pairs = [
323
+ (variant, run_id)
324
+ for variant in variants
325
+ for run_id in range(1, runs + 1)
326
+ ]
327
+ for (variant_id, params, vmarks), run_id in pairs:
328
+ if variant_id:
329
+ name = variant_id if runs == 1 else f"{variant_id}[run{run_id}]"
330
+ case = f"{short}::{variant_id}"
331
+ else:
332
+ # Unparametrized: one case, named after the function.
333
+ name = f"run{run_id}"
334
+ case = short
335
+ item = BenchItem.from_parent(
336
+ self,
337
+ name=name,
338
+ run_id=run_id,
339
+ bench_fn=self.bench_fn,
340
+ params=params,
341
+ case=case,
342
+ )
343
+ for mark in (*other_marks, *vmarks):
344
+ # add_marker() only accepts MarkDecorator; these are raw
345
+ # Mark objects, so attach the way it does internally
346
+ # (skip/xfail/-m all read these).
347
+ item.own_markers.append(mark)
348
+ item.keywords[mark.name] = mark
349
+ yield item
350
+
351
+
352
+ # ---------------------------------------------------------------------------
353
+ # Execution
354
+ # ---------------------------------------------------------------------------
355
+
356
+
357
+ class StepFailures(Exception):
358
+ """Raised by ``BenchItem.runtest`` when one or more steps failed."""
359
+
360
+ def __init__(self, steps: list[dict[str, Any]]) -> None:
361
+ super().__init__(f"{len(steps)} step(s) failed")
362
+ self.steps = steps
363
+
364
+
365
+ def _usage_to_dict(u: Any) -> dict[str, Any]:
366
+ """Normalize a usage entry (``TokenUsage``, any object with the same
367
+ attributes, or a plain dict) into a serializable dict."""
368
+ if isinstance(u, dict):
369
+ get = u.get
370
+ else:
371
+ get = lambda k, d=None: getattr(u, k, d) # noqa: E731
372
+ return {
373
+ "model": str(get("model") or ""),
374
+ "input_tokens": int(get("input_tokens") or 0),
375
+ "output_tokens": int(get("output_tokens") or 0),
376
+ "cached_input_tokens": int(get("cached_input_tokens") or 0),
377
+ "cost": float(get("cost") or 0.0),
378
+ }
379
+
380
+
381
+ def _step_to_dict(step: Any) -> dict[str, Any]:
382
+ usage = [_usage_to_dict(u) for u in (getattr(step, "usage", None) or ())]
383
+ cost = getattr(step, "cost", None)
384
+ if cost is None and usage:
385
+ # An explicit cost overrides; otherwise it derives from usage.
386
+ cost = sum(u["cost"] for u in usage)
387
+ return {
388
+ "label": getattr(step, "label", "step"),
389
+ "passed": bool(getattr(step, "passed", False)),
390
+ "elapsed": float(getattr(step, "elapsed", 0.0) or 0.0),
391
+ "error": getattr(step, "error", None),
392
+ "message": getattr(step, "message", None),
393
+ "cost": float(cost) if cost is not None else None,
394
+ "usage": usage,
395
+ }
396
+
397
+
398
+ class BenchItem(pytest.Item):
399
+ """One (case, run) execution of a bench function."""
400
+
401
+ def __init__(
402
+ self,
403
+ *,
404
+ run_id: int,
405
+ bench_fn: Callable,
406
+ params: dict[str, Any],
407
+ case: str,
408
+ **kwargs: Any,
409
+ ) -> None:
410
+ super().__init__(**kwargs)
411
+ self.run_id = run_id
412
+ self.bench_fn = bench_fn
413
+ self.params = params
414
+ # Function-qualified case id: the aggregation row.
415
+ self.case = case
416
+
417
+ def runtest(self) -> None:
418
+ delay = _delay(self.config)
419
+ if delay > 0:
420
+ if self.config.stash.get(_DELAYED_ONCE, False):
421
+ time.sleep(delay)
422
+ else:
423
+ self.config.stash[_DELAYED_ONCE] = True
424
+ steps: list[dict[str, Any]] = []
425
+ try:
426
+ for step in self.bench_fn(**self.params):
427
+ steps.append(_step_to_dict(step))
428
+ except Exception as exc:
429
+ # An exception mid-case is recorded as a failed "error"
430
+ # step so it counts in the aggregate, then surfaces as a
431
+ # normal pytest failure.
432
+ steps.append(
433
+ {
434
+ "label": "error",
435
+ "passed": False,
436
+ "elapsed": 0.0,
437
+ "error": str(exc),
438
+ "message": None,
439
+ "cost": None,
440
+ "usage": [],
441
+ }
442
+ )
443
+ self._publish(steps)
444
+ raise
445
+ self._publish(steps)
446
+ failed = [s for s in steps if not s["passed"]]
447
+ if failed:
448
+ raise StepFailures(failed)
449
+
450
+ def _publish(self, steps: list[dict[str, Any]]) -> None:
451
+ # Plain dicts only: user_properties must survive xdist's
452
+ # worker-to-controller report serialization.
453
+ self.user_properties.append(
454
+ (
455
+ "probability",
456
+ {
457
+ "case": self.case,
458
+ "run": self.run_id,
459
+ "steps": steps,
460
+ },
461
+ )
462
+ )
463
+
464
+ def repr_failure(self, excinfo, style=None):
465
+ if isinstance(excinfo.value, StepFailures):
466
+ lines = []
467
+ for s in excinfo.value.steps:
468
+ detail = s["error"] or s["message"]
469
+ lines.append(
470
+ f"step '{s['label']}' failed" + (f": {detail}" if detail else "")
471
+ )
472
+ return "\n".join(lines)
473
+ return super().repr_failure(excinfo, style=style)
474
+
475
+ def reportinfo(self):
476
+ return self.path, 0, f"case: {self.case}"
477
+
478
+
479
+ # ---------------------------------------------------------------------------
480
+ # Aggregation + the fraction summary
481
+ # ---------------------------------------------------------------------------
482
+
483
+
484
+ def _merge_usage(into: dict[str, dict[str, Any]], usage: dict[str, Any]) -> None:
485
+ """Fold one normalized usage entry into a per-model aggregate."""
486
+ model = usage["model"] or "unknown"
487
+ agg = into.setdefault(
488
+ model,
489
+ {
490
+ "input_tokens": 0,
491
+ "output_tokens": 0,
492
+ "cached_input_tokens": 0,
493
+ "cost": 0.0,
494
+ },
495
+ )
496
+ agg["input_tokens"] += usage["input_tokens"]
497
+ agg["output_tokens"] += usage["output_tokens"]
498
+ agg["cached_input_tokens"] += usage["cached_input_tokens"]
499
+ agg["cost"] += usage["cost"]
500
+
501
+
502
+ @dataclass
503
+ class CaseStats:
504
+ """Aggregated results for a (case, label) pair across all runs."""
505
+
506
+ case: str
507
+ label: str
508
+ passes: int = 0
509
+ fails: int = 0
510
+ errors: int = 0
511
+ cost: float = 0.0
512
+ # per-model token aggregates: model -> {input_tokens, output_tokens, ...}
513
+ usage: dict[str, dict[str, Any]] = field(default_factory=dict)
514
+
515
+ @property
516
+ def total(self) -> int:
517
+ return self.passes + self.fails + self.errors
518
+
519
+ @property
520
+ def status(self) -> str:
521
+ """Runs are a 3-class outcome (pass / fail / error); the row
522
+ status names the combination so the classes never blur:
523
+ ``flaky`` means real pass/fail nondeterminism, ``errored``
524
+ means the only blemishes were errors (infra, not the model)."""
525
+ if self.total == 0:
526
+ return "pending"
527
+ if self.passes == self.total:
528
+ return "pass"
529
+ if self.errors == self.total:
530
+ return "error"
531
+ if self.passes == 0:
532
+ return "fail"
533
+ if self.fails == 0:
534
+ return "errored"
535
+ return "flaky"
536
+
537
+
538
+ _MARKUP = {
539
+ "pass": {"green": True},
540
+ "flaky": {"yellow": True},
541
+ "errored": {"yellow": True},
542
+ "fail": {"red": True},
543
+ "error": {"red": True},
544
+ }
545
+
546
+
547
+ def _row_name(s: CaseStats) -> str:
548
+ return f"[{s.case}] {s.label}"
549
+
550
+
551
+ class ProbabilityAggregator:
552
+ """Rebuilds cross-run stats from test reports.
553
+
554
+ Consuming reports (rather than recording in-process during runtest)
555
+ keeps the aggregate correct under pytest-xdist: workers serialize
556
+ ``user_properties`` back to the controller, which is where the
557
+ summary renders.
558
+ """
559
+
560
+ def __init__(self, config: pytest.Config) -> None:
561
+ self._config = config
562
+ self._stats: OrderedDict[tuple[str, str], CaseStats] = OrderedDict()
563
+ self._json_path = config.getoption("prob_json")
564
+ # Raw (case, run, steps) records, kept only when a JSON report
565
+ # was requested.
566
+ self._records: list[dict[str, Any]] | None = (
567
+ [] if self._json_path else None
568
+ )
569
+
570
+ def pytest_runtest_logreport(self, report) -> None:
571
+ if getattr(report, "when", None) != "call":
572
+ return
573
+ for name, value in report.user_properties:
574
+ if name != "probability":
575
+ continue
576
+ if self._records is not None:
577
+ self._records.append(value)
578
+ for step in value["steps"]:
579
+ key = (value["case"], step["label"])
580
+ st = self._stats.setdefault(
581
+ key, CaseStats(case=value["case"], label=step["label"])
582
+ )
583
+ if step["error"] is not None:
584
+ st.errors += 1
585
+ elif step["passed"]:
586
+ st.passes += 1
587
+ else:
588
+ st.fails += 1
589
+ if step["cost"]:
590
+ st.cost += step["cost"]
591
+ for usage in step.get("usage", ()):
592
+ _merge_usage(st.usage, usage)
593
+
594
+ def pytest_sessionfinish(self, session: pytest.Session, exitstatus: int) -> None:
595
+ if not self._json_path:
596
+ return
597
+ # Under pytest-xdist this hook also fires on workers, which only
598
+ # hold a shard of the results — the controller writes the file.
599
+ if hasattr(session.config, "workerinput"):
600
+ return
601
+ all_stats = list(self._stats.values())
602
+ payload = {
603
+ "created": time.strftime("%Y-%m-%dT%H:%M:%S"),
604
+ "runs": _runs(session.config),
605
+ "exit_status": int(exitstatus),
606
+ "totals": {
607
+ "passes": sum(s.passes for s in all_stats),
608
+ "fails": sum(s.fails for s in all_stats),
609
+ "errors": sum(s.errors for s in all_stats),
610
+ "count": sum(s.total for s in all_stats),
611
+ "pass_rate": (
612
+ sum(s.passes for s in all_stats)
613
+ / sum(s.total for s in all_stats)
614
+ * 100
615
+ if all_stats and sum(s.total for s in all_stats)
616
+ else 0.0
617
+ ),
618
+ "cost": sum(s.cost for s in all_stats),
619
+ "usage": self._model_totals(all_stats),
620
+ },
621
+ "rows": [
622
+ {
623
+ "case": s.case,
624
+ "label": s.label,
625
+ "passes": s.passes,
626
+ "fails": s.fails,
627
+ "errors": s.errors,
628
+ "total": s.total,
629
+ "pass_rate": s.passes / s.total * 100 if s.total else 0.0,
630
+ "status": s.status,
631
+ "cost": s.cost,
632
+ "usage": s.usage,
633
+ }
634
+ for s in all_stats
635
+ ],
636
+ "records": self._records or [],
637
+ }
638
+ path = Path(self._json_path)
639
+ if path.parent != Path(""):
640
+ path.parent.mkdir(parents=True, exist_ok=True)
641
+ path.write_text(json.dumps(payload, indent=2))
642
+
643
+ @staticmethod
644
+ def _model_totals(all_stats: list[CaseStats]) -> dict[str, dict[str, Any]]:
645
+ totals: dict[str, dict[str, Any]] = {}
646
+ for s in all_stats:
647
+ for model, agg in s.usage.items():
648
+ _merge_usage(totals, {"model": model, **agg})
649
+ return totals
650
+
651
+ def pytest_terminal_summary(self, terminalreporter, exitstatus, config) -> None:
652
+ del exitstatus, config
653
+ if not self._stats:
654
+ return
655
+ all_stats = list(self._stats.values())
656
+ tr = terminalreporter
657
+ tr.write_sep("=", "probability")
658
+
659
+ name_col = max(len(_row_name(s)) for s in all_stats)
660
+ frac_col = max(len(f"{s.passes}/{s.total}") for s in all_stats)
661
+ for s in all_stats:
662
+ line = f" {_row_name(s):<{name_col}} {f'{s.passes}/{s.total}':>{frac_col}}"
663
+ if s.cost:
664
+ line += f" ${s.cost:.4f}"
665
+ # Three run classes, spelled out: the status word names the
666
+ # combination, and mixed rows show the error count.
667
+ if s.status == "errored":
668
+ line += f" {s.errors} ERRORED"
669
+ elif s.status != "pass":
670
+ line += f" {s.status.upper()}"
671
+ if s.errors and s.status != "error":
672
+ line += f" ({s.errors} errored)"
673
+ tr.write_line(line, **_MARKUP.get(s.status, {}))
674
+
675
+ total_passes = sum(s.passes for s in all_stats)
676
+ total = sum(s.total for s in all_stats)
677
+ total_errors = sum(s.errors for s in all_stats)
678
+ pct = total_passes / total * 100 if total else 0.0
679
+ overall = f" Overall: {total_passes}/{total} passed ({pct:.0f}%)"
680
+ if total_errors:
681
+ overall += f", {total_errors} errored"
682
+ tr.write_line("")
683
+ tr.write_line(overall, bold=True)
684
+ total_cost = sum(s.cost for s in all_stats)
685
+ if total_cost:
686
+ tr.write_line(f" Cost: ${total_cost:.4f}")
687
+ model_totals = self._model_totals(all_stats)
688
+ if model_totals:
689
+ def _tokens(agg: dict[str, Any]) -> str:
690
+ out = f"{agg['input_tokens']:,} in / {agg['output_tokens']:,} out"
691
+ if agg["cached_input_tokens"]:
692
+ out += f" / {agg['cached_input_tokens']:,} cached"
693
+ return out
694
+
695
+ model_col = max(len(m) for m in model_totals)
696
+ tokens_col = max(len(_tokens(a)) for a in model_totals.values())
697
+ for i, (model, agg) in enumerate(model_totals.items()):
698
+ prefix = " Tokens: " if i == 0 else " "
699
+ line = f"{prefix}{model:<{model_col}} {_tokens(agg):<{tokens_col}}"
700
+ if agg["cost"]:
701
+ line += f" ${agg['cost']:.4f}"
702
+ tr.write_line(line.rstrip())
703
+ if self._json_path:
704
+ tr.write_line(f" Report: {self._json_path}")
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-probability
3
+ Version: 0.1.0
4
+ Summary: pytest plugin for nondeterministic tests: run cases N times, report empirical pass fractions, flaky detection, and cost.
5
+ Project-URL: Homepage, https://github.com/xu-hao/pytest-probability
6
+ Project-URL: Repository, https://github.com/xu-hao/pytest-probability
7
+ Project-URL: Documentation, https://pytest-probability.readthedocs.io
8
+ Project-URL: Changelog, https://github.com/xu-hao/pytest-probability/blob/main/docs/changelog.md
9
+ Author: Hao Xu
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: benchmark,eval,evaluation,flaky,llm,probability,pytest
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: Pytest
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Testing
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: pytest>=7.4
23
+ Description-Content-Type: text/markdown
24
+
25
+ # pytest-probability
26
+
27
+ [![Documentation](https://readthedocs.org/projects/pytest-probability/badge/?version=latest)](https://pytest-probability.readthedocs.io/en/latest/)
28
+ [![PyPI](https://img.shields.io/pypi/v/pytest-probability)](https://pypi.org/project/pytest-probability/)
29
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
30
+
31
+ **A test that passes 7 times out of 10 is not a passing test — it's a probability.**
32
+
33
+ A pytest plugin for nondeterministic code — LLM-driven functions, model
34
+ inference, integration points, anything flaky-prone. A single-shot test lies
35
+ to you: it samples a distribution once and calls the result truth.
36
+ pytest-probability runs every case N times and reports the empirical pass
37
+ fraction per case, so `7/10 FLAKY` stops hiding inside a green checkmark.
38
+
39
+ ```
40
+ $ pytest benchmarks/ --prob-runs=10
41
+ ...
42
+ ================================= probability ==================================
43
+ [classify::is_question] classify 10/10 $0.0020
44
+ [classify::identify_pii] classify 7/10 $0.0020 FLAKY
45
+ [classify::extract_amount] classify 0/10 $0.0020 FAIL
46
+ [triage::refund-terse] triage 8/10 $0.0010 FLAKY
47
+ [triage::refund-chain_of_thought] triage 10/10 $0.0040
48
+
49
+ Overall: 35/50 passed (70%)
50
+ Cost: $0.0110
51
+ Tokens: m-small 1,200 in / 80 out / 640 cached $0.0010
52
+ m-large 4,800 in / 900 out $0.0040
53
+ ```
54
+
55
+ ## Documentation
56
+
57
+ Full documentation at
58
+ **[pytest-probability.readthedocs.io](https://pytest-probability.readthedocs.io)** —
59
+ installation, a quickstart, guides for benchmark files, parametrization,
60
+ running, cost accounting and the JSON report, a complete options
61
+ reference, and a developer guide covering the plugin's internals.
62
+
63
+ To build locally: `pip install -r docs/requirements.txt && sphinx-build -W -b html docs docs/_build/html`.
64
+
65
+ ## Install
66
+
67
+ ```bash
68
+ pip install pytest-probability
69
+ ```
70
+
71
+ No configuration needed — the plugin registers itself via the `pytest11`
72
+ entry point. The only dependency is pytest itself. Requires Python 3.11+
73
+ and pytest 7.4+.
74
+
75
+ ## Usage
76
+
77
+ Benchmark files are named `bench_*.py`, and every `bench_*` function in
78
+ them is a benchmark — the same convention pytest applies to `test_*`.
79
+ There is no plugin syntax to learn: cases are stock
80
+ `@pytest.mark.parametrize`, values arrive as function arguments, and
81
+ the function yields one result per step instead of asserting:
82
+
83
+ ```python
84
+ import time
85
+ import pytest
86
+ from pytest_probability import StepResult
87
+
88
+ @pytest.mark.parametrize("text,expected", [
89
+ pytest.param("is this a question?", "question", id="is_question"),
90
+ pytest.param("my ssn is 078-05-1120", "pii", id="identify_pii",
91
+ marks=pytest.mark.fast),
92
+ ])
93
+ def bench_classify(text, expected):
94
+ t0 = time.time()
95
+ answer = my_classifier(text)
96
+ yield StepResult(
97
+ label="classify",
98
+ passed=(answer == expected),
99
+ elapsed=time.time() - t0,
100
+ cost=0.0002, # optional — summed into the report
101
+ )
102
+ ```
103
+
104
+ Every parameter combination is a case with its own fraction row,
105
+ namespaced by function (`classify::identify_pii`); items collect as
106
+ `bench_x.py::bench_classify::identify_pii[run3]`. `pytest.param`
107
+ names and marks individual cases; a function with no parametrize runs
108
+ as a single case. Dataset-driven suites are a comprehension away:
109
+ `[pytest.param(row, id=row["id"]) for row in load_dataset()]`.
110
+
111
+ ```bash
112
+ pytest benchmarks/ --prob-runs=10 # every case ×10
113
+ pytest benchmarks/ -k identify_pii # one case, by id
114
+ pytest benchmarks/ -m "fast and not eu" # marks, boolean expressions
115
+ pytest benchmarks/ -n 4 # parallel via pytest-xdist
116
+ ```
117
+
118
+ Module-level `setup()` / `teardown()` run once per benchmark file.
119
+
120
+ ### Comparison axes
121
+
122
+ Stacked decorators cross-product with pytest's exact id layout and
123
+ ordering — put the configurations you're comparing (models, prompts,
124
+ thresholds) on their own axes and each combination gets its own row:
125
+
126
+ ```python
127
+ import pytest
128
+ from pytest_probability import StepResult, TokenUsage
129
+
130
+ @pytest.mark.parametrize("style", ["terse", "chain_of_thought"])
131
+ @pytest.mark.parametrize("text", [
132
+ pytest.param("my card was charged twice", id="refund"),
133
+ ])
134
+ def bench_triage(text, style):
135
+ response = my_classifier(text, prompt_style=style)
136
+ yield StepResult(
137
+ label="triage",
138
+ passed=response.answer == "billing",
139
+ usage=[TokenUsage(model=response.model,
140
+ input_tokens=response.input_tokens,
141
+ output_tokens=response.output_tokens,
142
+ cost=response.cost)],
143
+ )
144
+ ```
145
+
146
+ ```
147
+ [triage::refund-terse] triage 8/10 $0.0010 FLAKY
148
+ [triage::refund-chain_of_thought] triage 10/10 $0.0040
149
+ ```
150
+
151
+ ## Options
152
+
153
+ | Option | Where | Default | Meaning |
154
+ |---|---|---|---|
155
+ | `--prob-runs=N` | CLI | ini or 1 | run every case N times |
156
+ | `--prob-json=PATH` | CLI | — | write a JSON report to PATH |
157
+ | `--prob-delay=SECONDS` | CLI | ini or 0 | sleep between case executions |
158
+ | `--prob-transpose` | CLI | ini or off | run-major order: run 1 of everything, then run 2, … |
159
+ | `prob_delay` | ini | 0 | default for `--prob-delay` |
160
+ | `prob_transpose` | ini | false | default for `--prob-transpose` |
161
+ | `prob_runs` | ini | 1 | default for `--prob-runs` |
162
+ | `prob_pattern` | ini | `bench_*.py` | glob for benchmark files |
163
+
164
+ ## JSON report
165
+
166
+ `--prob-json=report.json` writes a single machine-readable file (think
167
+ `--junitxml`, but for fractions) — aggregate rows plus the raw per-run
168
+ step records for downstream analysis:
169
+
170
+ ```json
171
+ {
172
+ "created": "2026-07-07T21:43:18",
173
+ "runs": 10,
174
+ "exit_status": 1,
175
+ "totals": {"passes": 35, "fails": 15, "errors": 0, "count": 50,
176
+ "pass_rate": 70.0, "cost": 0.011,
177
+ "usage": {"m-small": {"input_tokens": 1200, "output_tokens": 80,
178
+ "cached_input_tokens": 640, "cost": 0.001}}},
179
+ "rows": [
180
+ {"case": "classify::identify_pii", "label": "classify", "passes": 7,
181
+ "fails": 3, "errors": 0, "total": 10, "pass_rate": 70.0,
182
+ "status": "flaky", "cost": 0.002, "usage": {}}
183
+ ],
184
+ "records": [
185
+ {"case": "classify::identify_pii", "run": 3, "steps": [
186
+ {"label": "classify", "passed": false, "elapsed": 0.01, "error": null,
187
+ "message": "got 'other'", "cost": 0.0002, "usage": []}]}
188
+ ]
189
+ }
190
+ ```
191
+
192
+ Under pytest-xdist the controller writes the file with the full result
193
+ set; workers never write partial reports.
194
+
195
+ ## Semantics
196
+
197
+ - One pytest item per **(function, case, run)** —
198
+ `bench_x.py::bench_classify::identify_pii[run3]`. `-k`, `-x`, `--lf`,
199
+ JUnit XML, and xdist all operate per run.
200
+ - A failing step fails that run's item with a compact message (no traceback
201
+ noise); an exception in a bench function is a normal pytest failure *and*
202
+ counts as an `error` step in the aggregate.
203
+ - Runs are a three-class outcome — pass, fail, error — and the row status
204
+ names the combination: `FLAKY` is reserved for genuine pass/fail
205
+ nondeterminism, while passes mixed with errors show `7/10 3 ERRORED`
206
+ (the model never answered wrong; the harness dropped runs). Fractions
207
+ are always over all runs.
208
+ - Selection is pure pytest: `-k` over composed case ids, `-m` over marks
209
+ (with and/or/not), node ids for single runs. Note pytest's `-k` grammar
210
+ rejects `=` — select on id substrings and mark names.
211
+ - Steps are consumed by duck-typing: anything with `label`, `passed`, and
212
+ optionally `elapsed` / `error` / `message` / `cost` / `usage` works,
213
+ including types from other frameworks. `usage` entries (objects or plain
214
+ dicts with `model` and token fields) aggregate per model into the
215
+ `Tokens:` block and the JSON report.
216
+ - The fraction summary is computed from `report.user_properties`, so it
217
+ stays correct under pytest-xdist (workers serialize results back to the
218
+ controller, which renders the table).
219
+ - Exit code follows pytest: any failed or errored run fails the session,
220
+ so a flaky case exits nonzero. For softer CI gates (e.g. alert only
221
+ below 80%), policy-check the JSON report in a follow-up step.
222
+ - `--prob-delay` throttles between executions and never sleeps before the
223
+ first; under pytest-xdist each worker throttles its own stream.
224
+ - Default order is case-major (`alpha[run1]`, `alpha[run2]`, `beta[run1]`,
225
+ …); `--prob-transpose` makes it run-major (`alpha[run1]`, `beta[run1]`,
226
+ `alpha[run2]`, …), which spreads each case's runs over time — useful
227
+ when back-to-back runs would hit the same transient state. Ordering is
228
+ advisory under xdist, which schedules items across workers itself.
@@ -0,0 +1,7 @@
1
+ pytest_probability/__init__.py,sha256=Eoup6IfJQI-n2XIM0kKEsJ_edJY1L5CkordIQGa3vL8,205
2
+ pytest_probability/plugin.py,sha256=Q3ACsU9gbVUmtkmUB-bBOzlBrFtnQ0ccqx7nZG72IJw,25598
3
+ pytest_probability-0.1.0.dist-info/METADATA,sha256=B0LLxROWPjO93biZeotF2QC668zYXJwN4dfQO0Y8bDQ,9700
4
+ pytest_probability-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
5
+ pytest_probability-0.1.0.dist-info/entry_points.txt,sha256=CNKpSDziPgf2fKn2wZytEmHsRmJ2FJ36B5vsI1q2_ys,51
6
+ pytest_probability-0.1.0.dist-info/licenses/LICENSE,sha256=A05MrCU2la2wd-qcvIwgwo_hfTZVZqGLY45ZxfLZ_Bg,1063
7
+ pytest_probability-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ probability = pytest_probability.plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hao Xu
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.