rustest 0.8.0__cp312-cp312-win_amd64.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.
rustest/decorators.py ADDED
@@ -0,0 +1,549 @@
1
+ """User facing decorators mirroring the most common pytest helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from typing import Any, ParamSpec, TypeVar, overload
7
+
8
+ P = ParamSpec("P")
9
+ R = TypeVar("R")
10
+ Q = ParamSpec("Q")
11
+ S = TypeVar("S")
12
+ TFunc = TypeVar("TFunc", bound=Callable[..., Any])
13
+
14
+ # Valid fixture scopes
15
+ VALID_SCOPES = frozenset(["function", "class", "module", "session"])
16
+
17
+
18
+ @overload
19
+ def fixture(func: Callable[P, R], *, scope: str = "function") -> Callable[P, R]: ...
20
+
21
+
22
+ @overload
23
+ def fixture(*, scope: str = "function") -> Callable[[Callable[P, R]], Callable[P, R]]: ...
24
+
25
+
26
+ def fixture(
27
+ func: Callable[P, R] | None = None,
28
+ *,
29
+ scope: str = "function",
30
+ ) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]:
31
+ """Mark a function as a fixture with a specific scope.
32
+
33
+ Args:
34
+ func: The function to decorate (when used without parentheses)
35
+ scope: The scope of the fixture. One of:
36
+ - "function": New instance for each test function (default)
37
+ - "class": Shared across all test methods in a class
38
+ - "module": Shared across all tests in a module
39
+ - "session": Shared across all tests in the session
40
+
41
+ Usage:
42
+ @fixture
43
+ def my_fixture():
44
+ return 42
45
+
46
+ @fixture(scope="module")
47
+ def shared_fixture():
48
+ return expensive_setup()
49
+ """
50
+ if scope not in VALID_SCOPES:
51
+ valid = ", ".join(sorted(VALID_SCOPES))
52
+ msg = f"Invalid fixture scope '{scope}'. Must be one of: {valid}"
53
+ raise ValueError(msg)
54
+
55
+ def decorator(f: Callable[P, R]) -> Callable[P, R]:
56
+ setattr(f, "__rustest_fixture__", True)
57
+ setattr(f, "__rustest_fixture_scope__", scope)
58
+ return f
59
+
60
+ # Support both @fixture and @fixture(scope="...")
61
+ if func is not None:
62
+ return decorator(func)
63
+ return decorator
64
+
65
+
66
+ def skip(reason: str | None = None) -> Callable[[Callable[P, R]], Callable[P, R]]:
67
+ """Skip a test or fixture."""
68
+
69
+ def decorator(func: Callable[P, R]) -> Callable[P, R]:
70
+ setattr(func, "__rustest_skip__", reason or "skipped via rustest.skip")
71
+ return func
72
+
73
+ return decorator
74
+
75
+
76
+ def parametrize(
77
+ arg_names: str | Sequence[str],
78
+ values: Sequence[Sequence[object] | Mapping[str, object]],
79
+ *,
80
+ ids: Sequence[str] | None = None,
81
+ ) -> Callable[[Callable[Q, S]], Callable[Q, S]]:
82
+ """Parametrise a test function."""
83
+
84
+ normalized_names = _normalize_arg_names(arg_names)
85
+
86
+ def decorator(func: Callable[Q, S]) -> Callable[Q, S]:
87
+ cases = _build_cases(normalized_names, values, ids)
88
+ setattr(func, "__rustest_parametrization__", cases)
89
+ return func
90
+
91
+ return decorator
92
+
93
+
94
+ def _normalize_arg_names(arg_names: str | Sequence[str]) -> tuple[str, ...]:
95
+ if isinstance(arg_names, str):
96
+ parts = [part.strip() for part in arg_names.split(",") if part.strip()]
97
+ if not parts:
98
+ msg = "parametrize() expected at least one argument name"
99
+ raise ValueError(msg)
100
+ return tuple(parts)
101
+ return tuple(arg_names)
102
+
103
+
104
+ def _build_cases(
105
+ names: tuple[str, ...],
106
+ values: Sequence[Sequence[object] | Mapping[str, object]],
107
+ ids: Sequence[str] | None,
108
+ ) -> tuple[dict[str, object], ...]:
109
+ case_payloads: list[dict[str, object]] = []
110
+ if ids is not None and len(ids) != len(values):
111
+ msg = "ids must match the number of value sets"
112
+ raise ValueError(msg)
113
+
114
+ for index, case in enumerate(values):
115
+ # Mappings are only treated as parameter mappings when there are multiple parameters
116
+ # For single parameters, dicts/mappings are treated as values
117
+ if isinstance(case, Mapping) and len(names) > 1:
118
+ data = {name: case[name] for name in names}
119
+ elif isinstance(case, tuple) and len(case) == len(names):
120
+ # Tuples are unpacked to match parameter names (pytest convention)
121
+ # This handles both single and multiple parameters
122
+ data = {name: case[pos] for pos, name in enumerate(names)}
123
+ else:
124
+ # Everything else is treated as a single value
125
+ # This includes: primitives, lists (even if len==names), dicts (single param), objects
126
+ if len(names) == 1:
127
+ data = {names[0]: case}
128
+ else:
129
+ raise ValueError("Parametrized value does not match argument names")
130
+ case_id = ids[index] if ids is not None else f"case_{index}"
131
+ case_payloads.append({"id": case_id, "values": data})
132
+ return tuple(case_payloads)
133
+
134
+
135
+ class MarkDecorator:
136
+ """A decorator for applying a mark to a test function."""
137
+
138
+ def __init__(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
139
+ super().__init__()
140
+ self.name = name
141
+ self.args = args
142
+ self.kwargs = kwargs
143
+
144
+ def __call__(self, func: TFunc) -> TFunc:
145
+ """Apply this mark to the given function."""
146
+ # Get existing marks or create a new list
147
+ existing_marks: list[dict[str, Any]] = getattr(func, "__rustest_marks__", [])
148
+
149
+ # Add this mark to the list
150
+ mark_data = {
151
+ "name": self.name,
152
+ "args": self.args,
153
+ "kwargs": self.kwargs,
154
+ }
155
+ existing_marks.append(mark_data)
156
+
157
+ # Store the marks list on the function
158
+ setattr(func, "__rustest_marks__", existing_marks)
159
+ return func
160
+
161
+ def __repr__(self) -> str:
162
+ return f"Mark({self.name!r}, {self.args!r}, {self.kwargs!r})"
163
+
164
+
165
+ class MarkGenerator:
166
+ """Namespace for dynamically creating marks like pytest.mark.
167
+
168
+ Usage:
169
+ @mark.slow
170
+ @mark.integration
171
+ @mark.timeout(seconds=30)
172
+
173
+ Standard marks:
174
+ @mark.skipif(condition, *, reason="...")
175
+ @mark.xfail(condition=None, *, reason=None, raises=None, run=True, strict=False)
176
+ @mark.usefixtures("fixture1", "fixture2")
177
+ @mark.asyncio(loop_scope="function")
178
+ """
179
+
180
+ def asyncio(
181
+ self,
182
+ func: Callable[..., Any] | None = None,
183
+ *,
184
+ loop_scope: str = "function",
185
+ ) -> Callable[..., Any]:
186
+ """Mark an async test function to be executed with asyncio.
187
+
188
+ This decorator allows you to write async test functions that will be
189
+ automatically executed in an asyncio event loop. The loop_scope parameter
190
+ controls the scope of the event loop used for execution.
191
+
192
+ Args:
193
+ func: The function to decorate (when used without parentheses)
194
+ loop_scope: The scope of the event loop. One of:
195
+ - "function": New loop for each test function (default)
196
+ - "class": Shared loop across all test methods in a class
197
+ - "module": Shared loop across all tests in a module
198
+ - "session": Shared loop across all tests in the session
199
+
200
+ Usage:
201
+ @mark.asyncio
202
+ async def test_async_function():
203
+ result = await some_async_operation()
204
+ assert result == expected
205
+
206
+ @mark.asyncio(loop_scope="module")
207
+ async def test_with_module_loop():
208
+ await another_async_operation()
209
+
210
+ Note:
211
+ This decorator should only be applied to async functions (coroutines).
212
+ Applying it to regular functions will raise a TypeError.
213
+ """
214
+ import asyncio
215
+ import inspect
216
+ from functools import wraps
217
+
218
+ valid_scopes = {"function", "class", "module", "session"}
219
+ if loop_scope not in valid_scopes:
220
+ valid = ", ".join(sorted(valid_scopes))
221
+ msg = f"Invalid loop_scope '{loop_scope}'. Must be one of: {valid}"
222
+ raise ValueError(msg)
223
+
224
+ def decorator(f: Callable[..., Any]) -> Callable[..., Any]:
225
+ # Handle class decoration - apply mark to all async methods
226
+ if inspect.isclass(f):
227
+ # Apply the mark to the class itself
228
+ mark_decorator = MarkDecorator("asyncio", (), {"loop_scope": loop_scope})
229
+ marked_class = mark_decorator(f)
230
+
231
+ # Wrap all async methods in the class
232
+ for name, method in inspect.getmembers(
233
+ marked_class, predicate=inspect.iscoroutinefunction
234
+ ):
235
+ wrapped_method = _wrap_async_function(method, loop_scope)
236
+ setattr(marked_class, name, wrapped_method)
237
+ return marked_class
238
+
239
+ # Validate that the function is a coroutine
240
+ if not inspect.iscoroutinefunction(f):
241
+ msg = f"@mark.asyncio can only be applied to async functions or test classes, but '{f.__name__}' is not async"
242
+ raise TypeError(msg)
243
+
244
+ # Store the asyncio mark
245
+ mark_decorator = MarkDecorator("asyncio", (), {"loop_scope": loop_scope})
246
+ marked_f = mark_decorator(f)
247
+
248
+ # Wrap the async function to run it synchronously
249
+ return _wrap_async_function(marked_f, loop_scope)
250
+
251
+ def _wrap_async_function(f: Callable[..., Any], loop_scope: str) -> Callable[..., Any]:
252
+ """Wrap an async function to run it synchronously in an event loop."""
253
+
254
+ @wraps(f)
255
+ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
256
+ # Get or create event loop based on scope
257
+ # For now, we'll always create a new loop - scope handling will be
258
+ # implemented in a future enhancement via fixtures
259
+ loop = asyncio.new_event_loop()
260
+ asyncio.set_event_loop(loop)
261
+ try:
262
+ # Run the coroutine in the event loop
263
+ # Get the original async function
264
+ original_func = getattr(f, "__wrapped__", f)
265
+ coro = original_func(*args, **kwargs)
266
+ return loop.run_until_complete(coro)
267
+ finally:
268
+ # Clean up the loop
269
+ try:
270
+ # Cancel any pending tasks
271
+ pending = asyncio.all_tasks(loop)
272
+ for task in pending:
273
+ task.cancel()
274
+ # Run the loop one more time to let tasks finish cancellation
275
+ if pending:
276
+ loop.run_until_complete(
277
+ asyncio.gather(*pending, return_exceptions=True)
278
+ )
279
+ except Exception:
280
+ pass
281
+ finally:
282
+ loop.close()
283
+
284
+ # Store reference to original async function
285
+ sync_wrapper.__wrapped__ = f
286
+ return sync_wrapper
287
+
288
+ # Support both @mark.asyncio and @mark.asyncio(loop_scope="...")
289
+ if func is not None:
290
+ return decorator(func)
291
+ return decorator
292
+
293
+ def skipif(
294
+ self,
295
+ condition: bool | str,
296
+ *,
297
+ reason: str | None = None,
298
+ ) -> MarkDecorator:
299
+ """Skip test if condition is true.
300
+
301
+ Args:
302
+ condition: Boolean or string condition to evaluate
303
+ reason: Explanation for why the test is skipped
304
+
305
+ Usage:
306
+ @mark.skipif(sys.platform == "win32", reason="Not supported on Windows")
307
+ def test_unix_only():
308
+ pass
309
+ """
310
+ return MarkDecorator("skipif", (condition,), {"reason": reason})
311
+
312
+ def xfail(
313
+ self,
314
+ condition: bool | str | None = None,
315
+ *,
316
+ reason: str | None = None,
317
+ raises: type[BaseException] | tuple[type[BaseException], ...] | None = None,
318
+ run: bool = True,
319
+ strict: bool = False,
320
+ ) -> MarkDecorator:
321
+ """Mark test as expected to fail.
322
+
323
+ Args:
324
+ condition: Optional condition - if False, mark is ignored
325
+ reason: Explanation for why the test is expected to fail
326
+ raises: Expected exception type(s)
327
+ run: Whether to run the test (False means skip it)
328
+ strict: If True, passing test will fail the suite
329
+
330
+ Usage:
331
+ @mark.xfail(reason="Known bug in backend")
332
+ def test_known_bug():
333
+ assert False
334
+
335
+ @mark.xfail(sys.platform == "win32", reason="Not implemented on Windows")
336
+ def test_feature():
337
+ pass
338
+ """
339
+ kwargs = {
340
+ "reason": reason,
341
+ "raises": raises,
342
+ "run": run,
343
+ "strict": strict,
344
+ }
345
+ args = () if condition is None else (condition,)
346
+ return MarkDecorator("xfail", args, kwargs)
347
+
348
+ def usefixtures(self, *names: str) -> MarkDecorator:
349
+ """Use fixtures without explicitly requesting them as parameters.
350
+
351
+ Args:
352
+ *names: Names of fixtures to use
353
+
354
+ Usage:
355
+ @mark.usefixtures("setup_db", "cleanup")
356
+ def test_with_fixtures():
357
+ pass
358
+ """
359
+ return MarkDecorator("usefixtures", names, {})
360
+
361
+ def __getattr__(self, name: str) -> Any:
362
+ """Create a mark decorator for the given name."""
363
+ # Return a callable that can be used as @mark.name or @mark.name(args)
364
+ return self._create_mark(name)
365
+
366
+ def _create_mark(self, name: str) -> Any:
367
+ """Create a MarkDecorator that can be called with or without arguments."""
368
+
369
+ class _MarkDecoratorFactory:
370
+ """Factory that allows @mark.name or @mark.name(args)."""
371
+
372
+ def __init__(self, mark_name: str) -> None:
373
+ super().__init__()
374
+ self.mark_name = mark_name
375
+
376
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
377
+ # If called with a single argument that's a function, it's @mark.name
378
+ if (
379
+ len(args) == 1
380
+ and not kwargs
381
+ and callable(args[0])
382
+ and hasattr(args[0], "__name__")
383
+ ):
384
+ decorator = MarkDecorator(self.mark_name, (), {})
385
+ return decorator(args[0])
386
+ # Otherwise it's @mark.name(args) - return a decorator
387
+ return MarkDecorator(self.mark_name, args, kwargs)
388
+
389
+ return _MarkDecoratorFactory(name)
390
+
391
+
392
+ # Create a singleton instance
393
+ mark = MarkGenerator()
394
+
395
+
396
+ class ExceptionInfo:
397
+ """Information about an exception caught by raises().
398
+
399
+ Attributes:
400
+ type: The exception type
401
+ value: The exception instance
402
+ traceback: The exception traceback
403
+ """
404
+
405
+ def __init__(
406
+ self, exc_type: type[BaseException], exc_value: BaseException, exc_tb: Any
407
+ ) -> None:
408
+ super().__init__()
409
+ self.type = exc_type
410
+ self.value = exc_value
411
+ self.traceback = exc_tb
412
+
413
+ def __repr__(self) -> str:
414
+ return f"<ExceptionInfo {self.type.__name__}({self.value!r})>"
415
+
416
+
417
+ class RaisesContext:
418
+ """Context manager for asserting that code raises a specific exception.
419
+
420
+ This mimics pytest.raises() behavior, supporting:
421
+ - Single or tuple of exception types
422
+ - Optional regex matching of exception messages
423
+ - Access to caught exception information
424
+
425
+ Usage:
426
+ with raises(ValueError):
427
+ int("not a number")
428
+
429
+ with raises(ValueError, match="invalid literal"):
430
+ int("not a number")
431
+
432
+ with raises((ValueError, TypeError)):
433
+ some_function()
434
+
435
+ # Access the caught exception
436
+ with raises(ValueError) as exc_info:
437
+ raise ValueError("oops")
438
+ assert "oops" in str(exc_info.value)
439
+ """
440
+
441
+ def __init__(
442
+ self,
443
+ exc_type: type[BaseException] | tuple[type[BaseException], ...],
444
+ *,
445
+ match: str | None = None,
446
+ ) -> None:
447
+ super().__init__()
448
+ self.exc_type = exc_type
449
+ self.match_pattern = match
450
+ self.excinfo: ExceptionInfo | None = None
451
+
452
+ def __enter__(self) -> RaisesContext:
453
+ return self
454
+
455
+ def __exit__(
456
+ self,
457
+ exc_type: type[BaseException] | None,
458
+ exc_val: BaseException | None,
459
+ exc_tb: Any,
460
+ ) -> bool:
461
+ # No exception was raised
462
+ if exc_type is None:
463
+ exc_name = self._format_exc_name()
464
+ msg = f"DID NOT RAISE {exc_name}"
465
+ raise AssertionError(msg)
466
+
467
+ # At this point, we know an exception was raised, so exc_val cannot be None
468
+ assert exc_val is not None, "exc_val must not be None when exc_type is not None"
469
+
470
+ # Check if the exception type matches
471
+ if not issubclass(exc_type, self.exc_type):
472
+ # Unexpected exception type - let it propagate
473
+ return False
474
+
475
+ # Store the exception information
476
+ self.excinfo = ExceptionInfo(exc_type, exc_val, exc_tb)
477
+
478
+ # Check if the message matches the pattern (if provided)
479
+ if self.match_pattern is not None:
480
+ import re
481
+
482
+ exc_message = str(exc_val)
483
+ if not re.search(self.match_pattern, exc_message):
484
+ msg = (
485
+ f"Pattern {self.match_pattern!r} does not match "
486
+ f"{exc_message!r}. Exception: {exc_type.__name__}: {exc_message}"
487
+ )
488
+ raise AssertionError(msg)
489
+
490
+ # Suppress the exception (it was expected)
491
+ return True
492
+
493
+ def _format_exc_name(self) -> str:
494
+ """Format the expected exception name(s) for error messages."""
495
+ if isinstance(self.exc_type, tuple):
496
+ names = " or ".join(exc.__name__ for exc in self.exc_type)
497
+ return names
498
+ return self.exc_type.__name__
499
+
500
+ @property
501
+ def value(self) -> BaseException:
502
+ """Access the caught exception value."""
503
+ if self.excinfo is None:
504
+ msg = "No exception was caught"
505
+ raise AttributeError(msg)
506
+ return self.excinfo.value
507
+
508
+ @property
509
+ def type(self) -> type[BaseException]:
510
+ """Access the caught exception type."""
511
+ if self.excinfo is None:
512
+ msg = "No exception was caught"
513
+ raise AttributeError(msg)
514
+ return self.excinfo.type
515
+
516
+
517
+ def raises(
518
+ exc_type: type[BaseException] | tuple[type[BaseException], ...],
519
+ *,
520
+ match: str | None = None,
521
+ ) -> RaisesContext:
522
+ """Assert that code raises a specific exception.
523
+
524
+ Args:
525
+ exc_type: The expected exception type(s). Can be a single type or tuple of types.
526
+ match: Optional regex pattern to match against the exception message.
527
+
528
+ Returns:
529
+ A context manager that catches and validates the exception.
530
+
531
+ Raises:
532
+ AssertionError: If no exception is raised, or if the message doesn't match.
533
+
534
+ Usage:
535
+ with raises(ValueError):
536
+ int("not a number")
537
+
538
+ with raises(ValueError, match="invalid literal"):
539
+ int("not a number")
540
+
541
+ with raises((ValueError, TypeError)):
542
+ some_function()
543
+
544
+ # Access the caught exception
545
+ with raises(ValueError) as exc_info:
546
+ raise ValueError("oops")
547
+ assert "oops" in str(exc_info.value)
548
+ """
549
+ return RaisesContext(exc_type, match=match)
rustest/py.typed ADDED
File without changes
rustest/reporting.py ADDED
@@ -0,0 +1,63 @@
1
+ """Utilities for converting raw results from the Rust layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+
8
+ from . import rust
9
+
10
+
11
+ @dataclass(slots=True)
12
+ class TestResult:
13
+ """Structured view of a single test outcome."""
14
+
15
+ __test__ = False # Tell pytest this is not a test class
16
+
17
+ name: str
18
+ path: str
19
+ status: str
20
+ duration: float
21
+ message: str | None
22
+ stdout: str | None
23
+ stderr: str | None
24
+
25
+ @classmethod
26
+ def from_py(cls, result: rust.PyTestResult) -> "TestResult":
27
+ return cls(
28
+ name=result.name,
29
+ path=result.path,
30
+ status=result.status,
31
+ duration=result.duration,
32
+ message=result.message,
33
+ stdout=result.stdout,
34
+ stderr=result.stderr,
35
+ )
36
+
37
+
38
+ @dataclass(slots=True)
39
+ class RunReport:
40
+ """Aggregate statistics for an entire test session."""
41
+
42
+ total: int
43
+ passed: int
44
+ failed: int
45
+ skipped: int
46
+ duration: float
47
+ results: tuple[TestResult, ...]
48
+
49
+ @classmethod
50
+ def from_py(cls, report: rust.PyRunReport) -> "RunReport":
51
+ return cls(
52
+ total=report.total,
53
+ passed=report.passed,
54
+ failed=report.failed,
55
+ skipped=report.skipped,
56
+ duration=report.duration,
57
+ results=tuple(TestResult.from_py(result) for result in report.results),
58
+ )
59
+
60
+ def iter_status(self, status: str) -> Iterable[TestResult]:
61
+ """Yield results with the requested status."""
62
+
63
+ return (result for result in self.results if result.status == status)
Binary file
rustest/rust.py ADDED
@@ -0,0 +1,23 @@
1
+ """Fallback stub for the compiled rustest extension.
2
+
3
+ This module is packaged with the Python distribution so unit tests can import the
4
+ package without building the Rust extension. Individual tests are expected to
5
+ monkeypatch the functions they exercise.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Sequence
11
+
12
+
13
+ def run(
14
+ _paths: Sequence[str],
15
+ _pattern: str | None,
16
+ _workers: int | None,
17
+ _capture_output: bool,
18
+ ) -> Any:
19
+ """Placeholder implementation that mirrors the extension signature."""
20
+
21
+ raise NotImplementedError(
22
+ "The rustest native extension is unavailable. Tests must patch rustest.rust.run."
23
+ )
rustest/rust.pyi ADDED
@@ -0,0 +1,39 @@
1
+ """Type stubs for the rustest Rust extension module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Sequence
6
+
7
+ class PyTestResult:
8
+ """Individual test result from the Rust extension."""
9
+
10
+ name: str
11
+ path: str
12
+ status: str
13
+ duration: float
14
+ message: str | None
15
+ stdout: str | None
16
+ stderr: str | None
17
+
18
+ class PyRunReport:
19
+ """Test run report from the Rust extension."""
20
+
21
+ total: int
22
+ passed: int
23
+ failed: int
24
+ skipped: int
25
+ duration: float
26
+ results: list[PyTestResult]
27
+
28
+ def run(
29
+ paths: Sequence[str],
30
+ pattern: str | None,
31
+ mark_expr: str | None,
32
+ workers: int | None,
33
+ capture_output: bool,
34
+ enable_codeblocks: bool,
35
+ last_failed_mode: str,
36
+ fail_fast: bool,
37
+ ) -> PyRunReport:
38
+ """Execute tests and return a report."""
39
+ ...