rustest 0.2.0__cp312-cp312-macosx_11_0_arm64.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.

Potentially problematic release.


This version of rustest might be problematic. Click here for more details.

rustest/_decorators.py ADDED
@@ -0,0 +1,350 @@
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, TypeVar
7
+
8
+ F = TypeVar("F", bound=Callable[..., object])
9
+
10
+ # Valid fixture scopes
11
+ VALID_SCOPES = frozenset(["function", "class", "module", "session"])
12
+
13
+
14
+ def fixture(
15
+ func: F | None = None,
16
+ *,
17
+ scope: str = "function",
18
+ ) -> F | Callable[[F], F]:
19
+ """Mark a function as a fixture with a specific scope.
20
+
21
+ Args:
22
+ func: The function to decorate (when used without parentheses)
23
+ scope: The scope of the fixture. One of:
24
+ - "function": New instance for each test function (default)
25
+ - "class": Shared across all test methods in a class
26
+ - "module": Shared across all tests in a module
27
+ - "session": Shared across all tests in the session
28
+
29
+ Usage:
30
+ @fixture
31
+ def my_fixture():
32
+ return 42
33
+
34
+ @fixture(scope="module")
35
+ def shared_fixture():
36
+ return expensive_setup()
37
+ """
38
+ if scope not in VALID_SCOPES:
39
+ valid = ", ".join(sorted(VALID_SCOPES))
40
+ msg = f"Invalid fixture scope '{scope}'. Must be one of: {valid}"
41
+ raise ValueError(msg)
42
+
43
+ def decorator(f: F) -> F:
44
+ setattr(f, "__rustest_fixture__", True)
45
+ setattr(f, "__rustest_fixture_scope__", scope)
46
+ return f
47
+
48
+ # Support both @fixture and @fixture(scope="...")
49
+ if func is not None:
50
+ return decorator(func)
51
+ return decorator
52
+
53
+
54
+ def skip(reason: str | None = None) -> Callable[[F], F]:
55
+ """Skip a test or fixture."""
56
+
57
+ def decorator(func: F) -> F:
58
+ setattr(func, "__rustest_skip__", reason or "skipped via rustest.skip")
59
+ return func
60
+
61
+ return decorator
62
+
63
+
64
+ def parametrize(
65
+ arg_names: str | Sequence[str],
66
+ values: Sequence[Sequence[object] | Mapping[str, object]],
67
+ *,
68
+ ids: Sequence[str] | None = None,
69
+ ) -> Callable[[F], F]:
70
+ """Parametrise a test function."""
71
+
72
+ normalized_names = _normalize_arg_names(arg_names)
73
+
74
+ def decorator(func: F) -> F:
75
+ cases = _build_cases(normalized_names, values, ids)
76
+ setattr(func, "__rustest_parametrization__", cases)
77
+ return func
78
+
79
+ return decorator
80
+
81
+
82
+ def _normalize_arg_names(arg_names: str | Sequence[str]) -> tuple[str, ...]:
83
+ if isinstance(arg_names, str):
84
+ parts = [part.strip() for part in arg_names.split(",") if part.strip()]
85
+ if not parts:
86
+ msg = "parametrize() expected at least one argument name"
87
+ raise ValueError(msg)
88
+ return tuple(parts)
89
+ return tuple(arg_names)
90
+
91
+
92
+ def _build_cases(
93
+ names: tuple[str, ...],
94
+ values: Sequence[Sequence[object] | Mapping[str, object]],
95
+ ids: Sequence[str] | None,
96
+ ) -> tuple[dict[str, object], ...]:
97
+ case_payloads: list[dict[str, object]] = []
98
+ if ids is not None and len(ids) != len(values):
99
+ msg = "ids must match the number of value sets"
100
+ raise ValueError(msg)
101
+
102
+ for index, case in enumerate(values):
103
+ # Mappings are only treated as parameter mappings when there are multiple parameters
104
+ # For single parameters, dicts/mappings are treated as values
105
+ if isinstance(case, Mapping) and len(names) > 1:
106
+ data = {name: case[name] for name in names}
107
+ elif isinstance(case, tuple) and len(case) == len(names):
108
+ # Tuples are unpacked to match parameter names (pytest convention)
109
+ # This handles both single and multiple parameters
110
+ data = {name: case[pos] for pos, name in enumerate(names)}
111
+ else:
112
+ # Everything else is treated as a single value
113
+ # This includes: primitives, lists (even if len==names), dicts (single param), objects
114
+ if len(names) == 1:
115
+ data = {names[0]: case}
116
+ else:
117
+ raise ValueError("Parametrized value does not match argument names")
118
+ case_id = ids[index] if ids is not None else f"case_{index}"
119
+ case_payloads.append({"id": case_id, "values": data})
120
+ return tuple(case_payloads)
121
+
122
+
123
+ class MarkDecorator:
124
+ """A decorator for applying a mark to a test function."""
125
+
126
+ def __init__(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
127
+ super().__init__()
128
+ self.name = name
129
+ self.args = args
130
+ self.kwargs = kwargs
131
+
132
+ def __call__(self, func: F) -> F:
133
+ """Apply this mark to the given function."""
134
+ # Get existing marks or create a new list
135
+ existing_marks: list[dict[str, Any]] = getattr(func, "__rustest_marks__", [])
136
+
137
+ # Add this mark to the list
138
+ mark_data = {
139
+ "name": self.name,
140
+ "args": self.args,
141
+ "kwargs": self.kwargs,
142
+ }
143
+ existing_marks.append(mark_data)
144
+
145
+ # Store the marks list on the function
146
+ setattr(func, "__rustest_marks__", existing_marks)
147
+ return func
148
+
149
+ def __repr__(self) -> str:
150
+ return f"Mark({self.name!r}, {self.args!r}, {self.kwargs!r})"
151
+
152
+
153
+ class MarkGenerator:
154
+ """Namespace for dynamically creating marks like pytest.mark.
155
+
156
+ Usage:
157
+ @mark.slow
158
+ @mark.integration
159
+ @mark.timeout(seconds=30)
160
+ """
161
+
162
+ def __getattr__(self, name: str) -> Any:
163
+ """Create a mark decorator for the given name."""
164
+ # Return a callable that can be used as @mark.name or @mark.name(args)
165
+ return self._create_mark(name)
166
+
167
+ def _create_mark(self, name: str) -> Any:
168
+ """Create a MarkDecorator that can be called with or without arguments."""
169
+
170
+ class _MarkDecoratorFactory:
171
+ """Factory that allows @mark.name or @mark.name(args)."""
172
+
173
+ def __init__(self, mark_name: str) -> None:
174
+ super().__init__()
175
+ self.mark_name = mark_name
176
+
177
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
178
+ # If called with a single argument that's a function, it's @mark.name
179
+ if (
180
+ len(args) == 1
181
+ and not kwargs
182
+ and callable(args[0])
183
+ and hasattr(args[0], "__name__")
184
+ ):
185
+ decorator = MarkDecorator(self.mark_name, (), {})
186
+ return decorator(args[0])
187
+ # Otherwise it's @mark.name(args) - return a decorator
188
+ return MarkDecorator(self.mark_name, args, kwargs)
189
+
190
+ return _MarkDecoratorFactory(name)
191
+
192
+
193
+ # Create a singleton instance
194
+ mark = MarkGenerator()
195
+
196
+
197
+ class ExceptionInfo:
198
+ """Information about an exception caught by raises().
199
+
200
+ Attributes:
201
+ type: The exception type
202
+ value: The exception instance
203
+ traceback: The exception traceback
204
+ """
205
+
206
+ def __init__(
207
+ self, exc_type: type[BaseException], exc_value: BaseException, exc_tb: Any
208
+ ) -> None:
209
+ super().__init__()
210
+ self.type = exc_type
211
+ self.value = exc_value
212
+ self.traceback = exc_tb
213
+
214
+ def __repr__(self) -> str:
215
+ return f"<ExceptionInfo {self.type.__name__}({self.value!r})>"
216
+
217
+
218
+ class RaisesContext:
219
+ """Context manager for asserting that code raises a specific exception.
220
+
221
+ This mimics pytest.raises() behavior, supporting:
222
+ - Single or tuple of exception types
223
+ - Optional regex matching of exception messages
224
+ - Access to caught exception information
225
+
226
+ Usage:
227
+ with raises(ValueError):
228
+ int("not a number")
229
+
230
+ with raises(ValueError, match="invalid literal"):
231
+ int("not a number")
232
+
233
+ with raises((ValueError, TypeError)):
234
+ some_function()
235
+
236
+ # Access the caught exception
237
+ with raises(ValueError) as exc_info:
238
+ raise ValueError("oops")
239
+ assert "oops" in str(exc_info.value)
240
+ """
241
+
242
+ def __init__(
243
+ self,
244
+ exc_type: type[BaseException] | tuple[type[BaseException], ...],
245
+ *,
246
+ match: str | None = None,
247
+ ) -> None:
248
+ super().__init__()
249
+ self.exc_type = exc_type
250
+ self.match_pattern = match
251
+ self.excinfo: ExceptionInfo | None = None
252
+
253
+ def __enter__(self) -> RaisesContext:
254
+ return self
255
+
256
+ def __exit__(
257
+ self,
258
+ exc_type: type[BaseException] | None,
259
+ exc_val: BaseException | None,
260
+ exc_tb: Any,
261
+ ) -> bool:
262
+ # No exception was raised
263
+ if exc_type is None:
264
+ exc_name = self._format_exc_name()
265
+ msg = f"DID NOT RAISE {exc_name}"
266
+ raise AssertionError(msg)
267
+
268
+ # At this point, we know an exception was raised, so exc_val cannot be None
269
+ assert exc_val is not None, "exc_val must not be None when exc_type is not None"
270
+
271
+ # Check if the exception type matches
272
+ if not issubclass(exc_type, self.exc_type):
273
+ # Unexpected exception type - let it propagate
274
+ return False
275
+
276
+ # Store the exception information
277
+ self.excinfo = ExceptionInfo(exc_type, exc_val, exc_tb)
278
+
279
+ # Check if the message matches the pattern (if provided)
280
+ if self.match_pattern is not None:
281
+ import re
282
+
283
+ exc_message = str(exc_val)
284
+ if not re.search(self.match_pattern, exc_message):
285
+ msg = (
286
+ f"Pattern {self.match_pattern!r} does not match "
287
+ f"{exc_message!r}. Exception: {exc_type.__name__}: {exc_message}"
288
+ )
289
+ raise AssertionError(msg)
290
+
291
+ # Suppress the exception (it was expected)
292
+ return True
293
+
294
+ def _format_exc_name(self) -> str:
295
+ """Format the expected exception name(s) for error messages."""
296
+ if isinstance(self.exc_type, tuple):
297
+ names = " or ".join(exc.__name__ for exc in self.exc_type)
298
+ return names
299
+ return self.exc_type.__name__
300
+
301
+ @property
302
+ def value(self) -> BaseException:
303
+ """Access the caught exception value."""
304
+ if self.excinfo is None:
305
+ msg = "No exception was caught"
306
+ raise AttributeError(msg)
307
+ return self.excinfo.value
308
+
309
+ @property
310
+ def type(self) -> type[BaseException]:
311
+ """Access the caught exception type."""
312
+ if self.excinfo is None:
313
+ msg = "No exception was caught"
314
+ raise AttributeError(msg)
315
+ return self.excinfo.type
316
+
317
+
318
+ def raises(
319
+ exc_type: type[BaseException] | tuple[type[BaseException], ...],
320
+ *,
321
+ match: str | None = None,
322
+ ) -> RaisesContext:
323
+ """Assert that code raises a specific exception.
324
+
325
+ Args:
326
+ exc_type: The expected exception type(s). Can be a single type or tuple of types.
327
+ match: Optional regex pattern to match against the exception message.
328
+
329
+ Returns:
330
+ A context manager that catches and validates the exception.
331
+
332
+ Raises:
333
+ AssertionError: If no exception is raised, or if the message doesn't match.
334
+
335
+ Usage:
336
+ with raises(ValueError):
337
+ int("not a number")
338
+
339
+ with raises(ValueError, match="invalid literal"):
340
+ int("not a number")
341
+
342
+ with raises((ValueError, TypeError)):
343
+ some_function()
344
+
345
+ # Access the caught exception
346
+ with raises(ValueError) as exc_info:
347
+ raise ValueError("oops")
348
+ assert "oops" in str(exc_info.value)
349
+ """
350
+ return RaisesContext(exc_type, match=match)
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,35 @@
1
+ """Type stubs for the Rust extension module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ class PyTestResult:
8
+ """Test result from Rust layer."""
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
+ """Run report from Rust layer."""
20
+
21
+ total: int
22
+ passed: int
23
+ failed: int
24
+ skipped: int
25
+ duration: float
26
+ results: Sequence[PyTestResult]
27
+
28
+ def run(
29
+ paths: list[str],
30
+ pattern: str | None,
31
+ workers: int | None,
32
+ capture_output: bool,
33
+ ) -> PyRunReport:
34
+ """Run tests and return a report."""
35
+ ...
rustest/core.py ADDED
@@ -0,0 +1,21 @@
1
+ """High level Python API wrapping the Rust extension."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ from . import _rust
8
+ from ._reporting import RunReport
9
+
10
+
11
+ def run(
12
+ *,
13
+ paths: Sequence[str],
14
+ pattern: str | None,
15
+ workers: int | None,
16
+ capture_output: bool,
17
+ ) -> RunReport:
18
+ """Execute tests and return a rich report."""
19
+
20
+ raw_report = _rust.run(list(paths), pattern, workers, capture_output)
21
+ return RunReport.from_py(raw_report)