| 1 |
"""Generative C-vs-Python parity fuzzing. |
| 2 |
|
| 3 |
Complements the enumerated grid in ``test_parity_matrix.py``: instead of a |
| 4 |
fixed table of hand-picked cases, this seeds a PRNG and feeds thousands of |
| 5 |
random valid and malformed inputs to both implementations, asserting identical |
| 6 |
observable behavior — same return value, or same exception type. It locks in |
| 7 |
the parity achieved across the #206-#212 / #219 fixes and guards against future |
| 8 |
regressions in the base32 codec or the type-checking front doors. |
| 9 |
|
| 10 |
Scope is deliberately the *deterministic* surface: ``ulid_to_bytes``, |
| 11 |
``bytes_to_ulid``, ``ulid_to_timestamp``, and their ``*_or_none`` counterparts. |
| 12 |
The ``ulid_at_time*`` family stays out of scope: its random 80-bit tail makes |
| 13 |
full-output comparison non-deterministic, and its numeric-domain corners |
| 14 |
(NaN/inf/overflow/str-reject — #218/#219) are pinned in the matrix instead. |
| 15 |
|
| 16 |
Buffer-protocol inputs (``bytearray``/``memoryview``/``list``) to the |
| 17 |
encode/decode front doors were once excluded under #210, when Python's buffer |
| 18 |
tolerance diverged from the C extension's strict type check. That divergence is |
| 19 |
resolved (#210 closed) — both impls now reject them identically at the strict |
| 20 |
``str``/``bytes`` gate — so they are fuzzed here in ``test_wrong_type_parity``. |
| 21 |
|
| 22 |
Seeds are fixed so CI is fully reproducible: a failure always replays from the |
| 23 |
``seed`` printed in the assertion message. |
| 24 |
""" |
| 25 |
|
| 26 |
from __future__ import annotations |
| 27 |
|
| 28 |
import random |
| 29 |
from typing import TYPE_CHECKING |
| 30 |
|
| 31 |
import pytest |
| 32 |
|
| 33 |
import ulid_transform._py_ulid_impl as py_impl |
| 34 |
|
| 35 |
if TYPE_CHECKING: |
| 36 |
from collections.abc import Callable |
| 37 |
|
| 38 |
try: |
| 39 |
import ulid_transform._ulid_impl as c_impl |
| 40 |
except ImportError: |
| 41 |
c_impl = None |
| 42 |
|
| 43 |
|
| 44 |
pytestmark = pytest.mark.skipif( |
| 45 |
c_impl is None, reason="C extension unavailable; parity fuzz is C-vs-Py only" |
| 46 |
) |
| 47 |
|
| 48 |
|
| 49 |
_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" |
| 50 |
|
| 51 |
_DECODE_ALIASES = "ILOilo" |
| 52 |
|
| 53 |
_PRINTABLE = ( |
| 54 |
"0123456789" |
| 55 |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 56 |
"abcdefghijklmnopqrstuvwxyz" |
| 57 |
"!@#$%^&*()_+-=[]{}|;:,.<>?/~` " |
| 58 |
) |
| 59 |
|
| 60 |
|
| 61 |
_SEEDS = [1, 7, 42, 1234, 98765] |
| 62 |
_ITERATIONS = 4000 |
| 63 |
|
| 64 |
|
| 65 |
def _run(fn: Callable[..., object], *args: object) -> tuple[str, object]: |
| 66 |
"""Reduce a call to a comparable ``(kind, payload)`` pair. |
| 67 |
|
| 68 |
``("ok", value)`` on success, ``("exc", ExceptionTypeName)`` on failure. |
| 69 |
Exception *messages* are intentionally ignored — only the type matters for |
| 70 |
parity here (the matrix already pins message text where it counts). |
| 71 |
""" |
| 72 |
try: |
| 73 |
return ("ok", fn(*args)) |
| 74 |
except Exception as exc: |
| 75 |
return ("exc", type(exc).__name__) |
| 76 |
|
| 77 |
|
| 78 |
def _assert_parity(fn_name: str, value: object, seed: int) -> None: |
| 79 |
py_outcome = _run(getattr(py_impl, fn_name), value) |
| 80 |
c_outcome = _run(getattr(c_impl, fn_name), value) |
| 81 |
assert py_outcome == c_outcome, ( |
| 82 |
f"parity mismatch (seed={seed}) for {fn_name}({value!r}): " |
| 83 |
f"py={py_outcome!r} c={c_outcome!r}" |
| 84 |
) |
| 85 |
|
| 86 |
|
| 87 |
def _random_valid_ulid_str(rng: random.Random) -> str: |
| 88 |
"""A 26-char string over the canonical alphabet, optionally case-folded.""" |
| 89 |
s = "".join(rng.choice(_ALPHABET) for _ in range(26)) |
| 90 |
roll = rng.random() |
| 91 |
if roll < 0.3: |
| 92 |
return s.lower() |
| 93 |
if roll < 0.4: |
| 94 |
|
| 95 |
chars = list(s) |
| 96 |
for _ in range(rng.randint(1, 4)): |
| 97 |
chars[rng.randint(0, 25)] = rng.choice(_DECODE_ALIASES) |
| 98 |
return "".join(chars) |
| 99 |
return s |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
@pytest.mark.parametrize("seed", _SEEDS) |
| 108 |
def test_decode_valid_alphabet_parity(seed): |
| 109 |
"""Random alphabet ULIDs decode to byte-identical output in both impls.""" |
| 110 |
rng = random.Random(seed) |
| 111 |
for _ in range(_ITERATIONS): |
| 112 |
s = _random_valid_ulid_str(rng) |
| 113 |
_assert_parity("ulid_to_bytes", s, seed) |
| 114 |
_assert_parity("ulid_to_timestamp", s, seed) |
| 115 |
_assert_parity("ulid_to_bytes_or_none", s, seed) |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
@pytest.mark.parametrize("seed", _SEEDS) |
| 124 |
def test_decode_arbitrary_ascii_parity(seed): |
| 125 |
"""26-char strings of arbitrary ASCII: same value, or same exception type.""" |
| 126 |
rng = random.Random(seed + 1) |
| 127 |
for _ in range(_ITERATIONS): |
| 128 |
s = "".join(rng.choice(_PRINTABLE) for _ in range(26)) |
| 129 |
_assert_parity("ulid_to_bytes", s, seed) |
| 130 |
_assert_parity("ulid_to_bytes_or_none", s, seed) |
| 131 |
_assert_parity("ulid_to_timestamp", s, seed) |
| 132 |
|
| 133 |
|
| 134 |
@pytest.mark.parametrize("seed", _SEEDS) |
| 135 |
def test_decode_arbitrary_length_parity(seed): |
| 136 |
"""Wrong-length strings (incl. empty and >26) must diverge identically.""" |
| 137 |
rng = random.Random(seed + 2) |
| 138 |
for _ in range(_ITERATIONS): |
| 139 |
length = rng.choice([0, 1, 13, 25, 26, 27, 32]) |
| 140 |
s = "".join(rng.choice(_PRINTABLE) for _ in range(length)) |
| 141 |
_assert_parity("ulid_to_bytes", s, seed) |
| 142 |
_assert_parity("ulid_to_bytes_or_none", s, seed) |
| 143 |
_assert_parity("ulid_to_timestamp", s, seed) |
| 144 |
|
| 145 |
|
| 146 |
@pytest.mark.parametrize("seed", _SEEDS) |
| 147 |
def test_decode_non_ascii_parity(seed): |
| 148 |
"""26-char strings with non-ASCII codepoints: same outcome in both impls.""" |
| 149 |
rng = random.Random(seed + 3) |
| 150 |
pool = "éàÿĀ中µ\U0001f600" |
| 151 |
for _ in range(_ITERATIONS): |
| 152 |
s = "".join(rng.choice(_ALPHABET + pool) for _ in range(26)) |
| 153 |
_assert_parity("ulid_to_bytes", s, seed) |
| 154 |
_assert_parity("ulid_to_bytes_or_none", s, seed) |
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
@pytest.mark.parametrize("seed", _SEEDS) |
| 163 |
def test_encode_random_bytes_parity(seed): |
| 164 |
"""Random byte strings of assorted lengths: same value or same exception.""" |
| 165 |
rng = random.Random(seed + 4) |
| 166 |
for _ in range(_ITERATIONS): |
| 167 |
length = rng.choice([0, 1, 8, 15, 16, 16, 16, 17, 32]) |
| 168 |
b = bytes(rng.getrandbits(8) for _ in range(length)) |
| 169 |
_assert_parity("bytes_to_ulid", b, seed) |
| 170 |
_assert_parity("bytes_to_ulid_or_none", b, seed) |
| 171 |
_assert_parity("ulid_to_timestamp", b, seed) |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
@pytest.mark.parametrize("seed", _SEEDS) |
| 180 |
def test_round_trip_random_bytes(seed): |
| 181 |
"""16 random bytes survive encode->decode, identically in C and Python.""" |
| 182 |
rng = random.Random(seed + 5) |
| 183 |
for _ in range(_ITERATIONS): |
| 184 |
raw = bytes(rng.getrandbits(8) for _ in range(16)) |
| 185 |
c_str = c_impl.bytes_to_ulid(raw) |
| 186 |
py_str = py_impl.bytes_to_ulid(raw) |
| 187 |
assert c_str == py_str, ( |
| 188 |
f"encode mismatch (seed={seed}) for {raw!r}: c={c_str!r} py={py_str!r}" |
| 189 |
) |
| 190 |
|
| 191 |
assert c_impl.ulid_to_bytes(c_str) == raw |
| 192 |
assert py_impl.ulid_to_bytes(py_str) == raw |
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
def _random_buffer_value(rng: random.Random) -> object: |
| 203 |
"""A buffer-protocol value of assorted length and random content. |
| 204 |
|
| 205 |
``bytearray``/``memoryview``/``list`` all expose a buffer but are neither |
| 206 |
``str`` nor ``bytes``; both impls must reject them at the type gate |
| 207 |
regardless of length or content. |
| 208 |
""" |
| 209 |
length = rng.choice([0, 1, 15, 16, 17, 26, 32]) |
| 210 |
raw = bytes(rng.getrandbits(8) for _ in range(length)) |
| 211 |
kind = rng.choice(("bytearray", "memoryview", "list")) |
| 212 |
if kind == "bytearray": |
| 213 |
return bytearray(raw) |
| 214 |
if kind == "memoryview": |
| 215 |
return memoryview(raw) |
| 216 |
return list(raw) |
| 217 |
|
| 218 |
|
| 219 |
@pytest.mark.parametrize("seed", _SEEDS) |
| 220 |
def test_wrong_type_parity(seed): |
| 221 |
"""Non-str/bytes inputs must hit the same type-check verdict in both impls. |
| 222 |
|
| 223 |
Covers plain scalars and buffer-protocol types (``bytearray``/ |
| 224 |
``memoryview``/``list``) of assorted lengths and contents — see #210. |
| 225 |
""" |
| 226 |
rng = random.Random(seed + 6) |
| 227 |
scalars = [None, 123, 12.5, {"x": 1}, object(), True, frozenset()] |
| 228 |
for _ in range(_ITERATIONS): |
| 229 |
value = _random_buffer_value(rng) if rng.random() < 0.5 else rng.choice(scalars) |
| 230 |
for fn in ( |
| 231 |
"ulid_to_bytes", |
| 232 |
"bytes_to_ulid", |
| 233 |
"ulid_to_timestamp", |
| 234 |
"ulid_to_bytes_or_none", |
| 235 |
"bytes_to_ulid_or_none", |
| 236 |
): |
| 237 |
_assert_parity(fn, value, seed) |