|
| 1 | +"""Hypothesis property tests for the pure _accumulate_capped core. |
| 2 | +
|
| 3 | +The one subtle invariant of the response-body cap is chunk-boundary |
| 4 | +independence: the accumulator must behave identically no matter how the decoded |
| 5 | +body is split into chunks. It must raise _CapExceeded iff the total decoded |
| 6 | +length exceeds the cap, and otherwise return the body byte-for-byte. |
| 7 | +""" |
| 8 | + |
| 9 | +import pytest |
| 10 | +from hypothesis import given |
| 11 | +from hypothesis import strategies as st |
| 12 | + |
| 13 | +from httpware.client import _accumulate_capped, _CapExceeded |
| 14 | + |
| 15 | + |
| 16 | +def _partition(body: bytes, sizes: list[int]) -> list[bytes]: |
| 17 | + """Split `body` into chunks following `sizes` (remainder becomes a final chunk).""" |
| 18 | + chunks: list[bytes] = [] |
| 19 | + pos = 0 |
| 20 | + for size in sizes: |
| 21 | + if pos >= len(body): |
| 22 | + break |
| 23 | + chunks.append(body[pos : pos + size]) |
| 24 | + pos += size |
| 25 | + if pos < len(body): |
| 26 | + chunks.append(body[pos:]) |
| 27 | + return chunks |
| 28 | + |
| 29 | + |
| 30 | +@given( |
| 31 | + body=st.binary(max_size=2048), |
| 32 | + sizes=st.lists(st.integers(min_value=1, max_value=64), max_size=64), |
| 33 | + cap=st.integers(min_value=1, max_value=4096), |
| 34 | +) |
| 35 | +def test_accumulate_capped_chunk_boundary_independence(body: bytes, sizes: list[int], cap: int) -> None: |
| 36 | + chunks = _partition(body, sizes) |
| 37 | + if len(body) > cap: |
| 38 | + with pytest.raises(_CapExceeded) as caught: |
| 39 | + _accumulate_capped(chunks, cap) |
| 40 | + assert caught.value.read > cap |
| 41 | + else: |
| 42 | + assert _accumulate_capped(chunks, cap) == body |
| 43 | + |
| 44 | + |
| 45 | +@given(body=st.binary(min_size=2, max_size=512)) |
| 46 | +def test_accumulate_capped_trips_at_one_below_length(body: bytes) -> None: |
| 47 | + cap = len(body) - 1 |
| 48 | + with pytest.raises(_CapExceeded): |
| 49 | + _accumulate_capped([body], cap) |
| 50 | + |
| 51 | + |
| 52 | +@given(body=st.binary(max_size=512)) |
| 53 | +def test_accumulate_capped_passes_at_exact_length(body: bytes) -> None: |
| 54 | + cap = max(1, len(body)) |
| 55 | + assert _accumulate_capped([body], cap) == body |
0 commit comments