Debian Codegraph @

tests/test_parity_matrix.py

raw symbols SCIP
1 """Table-driven C-vs-Python behavioral parity matrix.
2
3 Diff-feeds a fixed grid of valid and invalid inputs to both implementations and
4 asserts identical observable behavior — same return value, or same exception
5 type. Known divergences are marked ``xfail(strict=False)`` with the issue or PR
6 that tracks them; when those land, the corresponding case flips XPASS and the
7 marker can be removed.
8
9 Companion to ``test_impl_sync.py`` (signature/docstring parity). Together they
10 form the cross-impl contract net referenced in issue #210.
11 """
12
13 from __future__ import annotations
14
15 from typing import TYPE_CHECKING
16
17 import pytest
18
19 import ulid_transform._py_ulid_impl as py_impl
20
21 if TYPE_CHECKING:
22 from collections.abc import Callable
23
24 try:
25 import ulid_transform._ulid_impl as c_impl
26 except ImportError:
27 c_impl = None
28
29
30 pytestmark = pytest.mark.skipif(
31 c_impl is None, reason="C extension unavailable; parity matrix is C-vs-Py only"
32 )
33
34
35 _VALID_ULID_STR = "01GTCKZT7K26YEVVW6AMQ3J0VT"
36 _VALID_ULID_BYTES = b"\x01\x86\x99\x3f\xe8\xf3\x11\xbd\xfb\xd6\x70\x55\x6c\x18\xc0\x6b"
37 _VALID_ULID_STR_LOWER = "01gtckzt7k26yevvw6amq3j0vt"
38
39
40 def _run(fn: Callable[..., object], *args: object) -> tuple[str, object]:
41 try:
42 return ("ok", fn(*args))
43 except Exception as exc: # noqa: BLE001
44 return ("exc", type(exc).__name__)
45
46
47 def _assert_parity(fn_name: str, *args: object) -> None:
48 py_fn = getattr(py_impl, fn_name)
49 c_fn = getattr(c_impl, fn_name)
50 py_outcome = _run(py_fn, *args)
51 c_outcome = _run(c_fn, *args)
52 assert py_outcome == c_outcome, (
53 f"parity mismatch for {fn_name}({', '.join(repr(a) for a in args)}): "
54 f"py={py_outcome!r} c={c_outcome!r}"
55 )
56
57
58 # --------------------------------------------------------------------------- #
59 # bytes_to_ulid
60 # --------------------------------------------------------------------------- #
61
62 _BYTES_TO_ULID_CASES = [
63 pytest.param(b"\x00" * 16, id="zero-16-bytes"),
64 pytest.param(_VALID_ULID_BYTES, id="valid-bytes"),
65 pytest.param(b"", id="empty-bytes"),
66 pytest.param(b"short", id="short-bytes"),
67 pytest.param(b"\x00" * 17, id="too-long-bytes"),
68 pytest.param(123, id="int"),
69 pytest.param(None, id="none"),
70 pytest.param("a" * 16, id="str-16"),
71 pytest.param([0] * 16, id="list"),
72 pytest.param(bytearray(16), id="bytearray-16"),
73 pytest.param(memoryview(b"\x00" * 16), id="memoryview-16"),
74 ]
75
76
77 @pytest.mark.parametrize("value", _BYTES_TO_ULID_CASES)
78 def test_bytes_to_ulid_parity(value):
79 _assert_parity("bytes_to_ulid", value)
80
81
82 # --------------------------------------------------------------------------- #
83 # ulid_to_bytes
84 # --------------------------------------------------------------------------- #
85
86 _ULID_TO_BYTES_CASES = [
87 pytest.param(_VALID_ULID_STR, id="valid-upper"),
88 pytest.param(_VALID_ULID_STR_LOWER, id="valid-lower"),
89 pytest.param("", id="empty-str"),
90 pytest.param("short", id="short-str"),
91 pytest.param("X" * 27, id="too-long-str"),
92 # 26 codepoints but non-ASCII: C measures UTF-8 byte length (> 26) and
93 # raises ValueError; Python must too (not UnicodeEncodeError from .encode).
94 pytest.param("é" * 26, id="non-ascii-26"),
95 # 13 two-byte codepoints = exactly 26 UTF-8 bytes: the byte-length check
96 # alone passes, so C must also verify ASCII or it decodes garbage instead
97 # of raising ValueError like Python.
98 pytest.param("é" * 13, id="non-ascii-13cp-26bytes"),
99 pytest.param(123, id="int"),
100 pytest.param(None, id="none"),
101 pytest.param([0] * 26, id="list"),
102 pytest.param(_VALID_ULID_BYTES, id="ulid-as-bytes"),
103 pytest.param(bytearray(_VALID_ULID_STR.encode()), id="ulid-as-bytearray"),
104 ]
105
106
107 @pytest.mark.parametrize("value", _ULID_TO_BYTES_CASES)
108 def test_ulid_to_bytes_parity(value):
109 _assert_parity("ulid_to_bytes", value)
110
111
112 # --------------------------------------------------------------------------- #
113 # ulid_to_timestamp
114 # --------------------------------------------------------------------------- #
115
116 _ULID_TO_TIMESTAMP_CASES = [
117 pytest.param(_VALID_ULID_STR, id="valid-str"),
118 pytest.param(_VALID_ULID_BYTES, id="valid-bytes"),
119 pytest.param(b"\x00" * 16, id="zero-bytes"),
120 pytest.param("short", id="short-str"),
121 # 13 two-byte codepoints = 26 UTF-8 bytes: the C string path decodes inline,
122 # so it must reject non-ASCII or return a garbage timestamp instead of the
123 # ValueError Python raises.
124 pytest.param("é" * 13, id="non-ascii-13cp-26bytes"),
125 pytest.param(123, id="int"),
126 pytest.param(None, id="none"),
127 pytest.param(b"short", id="short-bytes"),
128 pytest.param(b"\x00" * 17, id="too-long-bytes"),
129 pytest.param(bytearray(16), id="bytearray-16"),
130 pytest.param(memoryview(b"\x00" * 16), id="memoryview-16"),
131 ]
132
133
134 @pytest.mark.parametrize("value", _ULID_TO_TIMESTAMP_CASES)
135 def test_ulid_to_timestamp_parity(value):
136 _assert_parity("ulid_to_timestamp", value)
137
138
139 # --------------------------------------------------------------------------- #
140 # ulid_to_bytes_or_none
141 # --------------------------------------------------------------------------- #
142
143 _ULID_TO_BYTES_OR_NONE_CASES = [
144 pytest.param(None, id="none"),
145 pytest.param(_VALID_ULID_STR, id="valid-str"),
146 pytest.param(_VALID_ULID_STR_LOWER, id="valid-lower"),
147 pytest.param("", id="empty"),
148 pytest.param("short", id="short"),
149 pytest.param("é" * 26, id="non-ascii-26"),
150 # 13 two-byte codepoints = 26 UTF-8 bytes: C must reject non-ASCII (return
151 # None) rather than decode garbage bytes.
152 pytest.param("é" * 13, id="non-ascii-13cp-26bytes"),
153 pytest.param(123, id="int"),
154 pytest.param(b"x" * 26, id="bytes-26"),
155 pytest.param([0] * 26, id="list-26"),
156 pytest.param(object(), id="object"),
157 ]
158
159
160 @pytest.mark.parametrize("value", _ULID_TO_BYTES_OR_NONE_CASES)
161 def test_ulid_to_bytes_or_none_parity(value):
162 _assert_parity("ulid_to_bytes_or_none", value)
163
164
165 # --------------------------------------------------------------------------- #
166 # bytes_to_ulid_or_none
167 # --------------------------------------------------------------------------- #
168
169 _BYTES_TO_ULID_OR_NONE_CASES = [
170 pytest.param(None, id="none"),
171 pytest.param(_VALID_ULID_BYTES, id="valid-bytes"),
172 pytest.param(b"\x00" * 16, id="zero-bytes"),
173 pytest.param(b"short", id="short"),
174 pytest.param(b"", id="empty"),
175 pytest.param(b"\x00" * 17, id="too-long"),
176 pytest.param(123, id="int"),
177 pytest.param("x" * 16, id="str-16"),
178 pytest.param(bytearray(16), id="bytearray-16"),
179 pytest.param([0] * 16, id="list-16"),
180 pytest.param(object(), id="object"),
181 ]
182
183
184 @pytest.mark.parametrize("value", _BYTES_TO_ULID_OR_NONE_CASES)
185 def test_bytes_to_ulid_or_none_parity(value):
186 _assert_parity("bytes_to_ulid_or_none", value)
187
188
189 # --------------------------------------------------------------------------- #
190 # ulid_at_time / ulid_at_time_bytes — non-deterministic; only shape + error
191 # parity is asserted.
192 # --------------------------------------------------------------------------- #
193
194 _AT_TIME_VALID = [0.0, 1.0, 1_700_000_000.0]
195 _AT_TIME_INVALID = [
196 pytest.param(None, id="none"),
197 pytest.param([0], id="list"),
198 pytest.param({}, id="dict"),
199 pytest.param("not-a-float", id="str"),
200 pytest.param(-1.0, id="negative"),
201 # ts * 1000 in (-1, 0): int() truncates toward zero, so the Python impl
202 # must reject the negative sign before the cast to match the C extension.
203 pytest.param(-0.0005, id="negative-truncates-to-zero"),
204 pytest.param(1e18, id="huge"),
205 pytest.param(float("nan"), id="nan"),
206 pytest.param(float("inf"), id="inf"),
207 pytest.param(float("-inf"), id="neg-inf"),
208 ]
209
210
211 @pytest.mark.parametrize("timestamp", _AT_TIME_VALID)
212 def test_ulid_at_time_valid_shape(timestamp):
213 """Valid timestamps: both impls return a 26-char str (content is random)."""
214 py_val = py_impl.ulid_at_time(timestamp)
215 c_val = c_impl.ulid_at_time(timestamp)
216 assert isinstance(py_val, str)
217 assert len(py_val) == 26
218 assert isinstance(c_val, str)
219 assert len(c_val) == 26
220
221
222 @pytest.mark.parametrize("timestamp", _AT_TIME_VALID)
223 def test_ulid_at_time_bytes_valid_shape(timestamp):
224 py_val = py_impl.ulid_at_time_bytes(timestamp)
225 c_val = c_impl.ulid_at_time_bytes(timestamp)
226 assert isinstance(py_val, bytes)
227 assert len(py_val) == 16
228 assert isinstance(c_val, bytes)
229 assert len(c_val) == 16
230
231
232 @pytest.mark.parametrize("timestamp", _AT_TIME_INVALID)
233 def test_ulid_at_time_invalid_parity(timestamp):
234 """Both impls raise the same exception type on invalid input."""
235 py_outcome = _run(py_impl.ulid_at_time, timestamp)
236 c_outcome = _run(c_impl.ulid_at_time, timestamp)
237 # Both must have errored — if either returned successfully, the case
238 # doesn't belong in the invalid grid. Filtered separately so the failure
239 # message is clearer than `_assert_parity` would give.
240 assert py_outcome[0] == "exc", (
241 f"expected py impl to raise; got py={py_outcome!r} c={c_outcome!r}"
242 )
243 assert c_outcome[0] == "exc", (
244 f"expected c impl to raise; got py={py_outcome!r} c={c_outcome!r}"
245 )
246 assert py_outcome == c_outcome, (
247 f"exception type mismatch: py={py_outcome!r} c={c_outcome!r}"
248 )
249
250
251 @pytest.mark.parametrize("timestamp", _AT_TIME_INVALID)
252 def test_ulid_at_time_bytes_invalid_parity(timestamp):
253 py_outcome = _run(py_impl.ulid_at_time_bytes, timestamp)
254 c_outcome = _run(c_impl.ulid_at_time_bytes, timestamp)
255 assert py_outcome[0] == "exc", (
256 f"expected py impl to raise; got py={py_outcome!r} c={c_outcome!r}"
257 )
258 assert c_outcome[0] == "exc", (
259 f"expected c impl to raise; got py={py_outcome!r} c={c_outcome!r}"
260 )
261 assert py_outcome == c_outcome, (
262 f"exception type mismatch: py={py_outcome!r} c={c_outcome!r}"
263 )
264
265
266 # --------------------------------------------------------------------------- #
267 # Generators — shape-only (output is random/time-dependent).
268 # --------------------------------------------------------------------------- #
269
270
271 def test_ulid_now_shape():
272 py_val = py_impl.ulid_now()
273 c_val = c_impl.ulid_now()
274 assert isinstance(py_val, str)
275 assert len(py_val) == 26
276 assert isinstance(c_val, str)
277 assert len(c_val) == 26
278
279
280 def test_ulid_now_bytes_shape():
281 py_val = py_impl.ulid_now_bytes()
282 c_val = c_impl.ulid_now_bytes()
283 assert isinstance(py_val, bytes)
284 assert len(py_val) == 16
285 assert isinstance(c_val, bytes)
286 assert len(c_val) == 16
287
288
289 def test_ulid_hex_shape():
290 py_val = py_impl.ulid_hex()
291 c_val = c_impl.ulid_hex()
292 assert isinstance(py_val, str)
293 assert len(py_val) == 32
294 assert isinstance(c_val, str)
295 assert len(c_val) == 32
296 # Must parse as hex
297 int(py_val, 16)
298 int(c_val, 16)
299
300
301 # --------------------------------------------------------------------------- #
302 # Cross-impl round-trip parity for ulid_to_bytes ↔ bytes_to_ulid.
303 # --------------------------------------------------------------------------- #
304
305 # Sample of ULID strings spanning the alphabet — mixed-case where allowed.
306 _ROUND_TRIP_DECODE_SAMPLES = [
307 pytest.param("00000000000000000000000000", id="all-zero"),
308 pytest.param("7ZZZZZZZZZZZZZZZZZZZZZZZZZ", id="all-z-upper"),
309 pytest.param(_VALID_ULID_STR, id="valid-upper"),
310 pytest.param(_VALID_ULID_STR_LOWER, id="valid-lower"),
311 pytest.param("01GTCKZT7K26yevvw6amq3j0vt", id="valid-mixed"),
312 ]
313
314
315 @pytest.mark.parametrize("ulid_str", _ROUND_TRIP_DECODE_SAMPLES)
316 def test_ulid_to_bytes_byte_equal(ulid_str):
317 """C and Py decode to identical bytes — no silent divergence."""
318 assert py_impl.ulid_to_bytes(ulid_str) == c_impl.ulid_to_bytes(ulid_str)
319
320
321 # Encode path takes canonical uppercase bytes only — no PR #209 dependency.
322 _ROUND_TRIP_ENCODE_SAMPLES = [
323 "00000000000000000000000000",
324 "7ZZZZZZZZZZZZZZZZZZZZZZZZZ",
325 _VALID_ULID_STR,
326 ]
327
328
329 @pytest.mark.parametrize("ulid_str", _ROUND_TRIP_ENCODE_SAMPLES)
330 def test_bytes_to_ulid_byte_equal(ulid_str):
331 """Encode the canonical-uppercase bytes; both impls produce the same string."""
332 raw = py_impl.ulid_to_bytes(ulid_str)
333 assert py_impl.bytes_to_ulid(raw) == c_impl.bytes_to_ulid(raw)