"""The workspace allocator: lowest free, reuse after release, and loud bugs.""" from __future__ import annotations import pytest from hhstreamd.containers import NoSlots, WorkspaceAllocator def test_allocates_the_band_from_its_base_upwards() -> None: alloc = WorkspaceAllocator(1000, 4) assert [alloc.allocate() for _ in range(4)] == [1000, 1001, 1002, 1003] assert alloc.in_use() == [1000, 1001, 1002, 1003] def test_a_released_slot_is_reused_before_a_higher_free_one() -> None: alloc = WorkspaceAllocator(1000, 4) for _ in range(3): alloc.allocate() alloc.release(1001) assert alloc.in_use() == [1000, 1002] assert alloc.allocate() == 1001 assert alloc.allocate() == 1003 assert alloc.in_use() == [1000, 1001, 1002, 1003] def test_a_full_band_raises_no_slots_and_stays_unchanged() -> None: alloc = WorkspaceAllocator(1000, 2) alloc.allocate() alloc.allocate() with pytest.raises(NoSlots) as exc: alloc.allocate() assert "1000..1001" in str(exc.value) assert alloc.in_use() == [1000, 1001] # Exhaustion is not terminal: a release makes the slot available again. alloc.release(1000) assert alloc.allocate() == 1000 def test_releasing_a_slot_we_never_handed_out_is_a_key_error() -> None: alloc = WorkspaceAllocator(1000, 2) alloc.allocate() # Inside the band but free, and outside the band: both are caller bugs, and # a silent no-op would let two sessions share a workspace later. with pytest.raises(KeyError) as free_slot: alloc.release(1001) assert "1001" in str(free_slot.value) with pytest.raises(KeyError): alloc.release(7) assert alloc.in_use() == [1000] def test_a_double_release_raises() -> None: alloc = WorkspaceAllocator(1000, 2) slot = alloc.allocate() alloc.release(slot) with pytest.raises(KeyError): alloc.release(slot) assert alloc.in_use() == [] def test_in_use_is_ascending_whatever_the_allocation_order() -> None: alloc = WorkspaceAllocator(1000, 3) a, b, c = alloc.allocate(), alloc.allocate(), alloc.allocate() alloc.release(b) alloc.release(a) alloc.allocate() alloc.allocate() assert alloc.in_use() == [1000, 1001, 1002] assert c == 1002 def test_a_band_must_be_a_real_band() -> None: with pytest.raises(ValueError) as count: WorkspaceAllocator(1000, 0) assert "count" in str(count.value) with pytest.raises(ValueError) as base: WorkspaceAllocator(0, 4) assert "base" in str(base.value) with pytest.raises(ValueError) as kind: WorkspaceAllocator(1000, 2.5) # type: ignore[arg-type] assert "count" in str(kind.value) assert "is not an int" in str(kind.value) def test_two_allocators_do_not_share_state() -> None: # The set is per-instance; a class attribute here would hand the same # workspace to two brokers' containers. first = WorkspaceAllocator(1000, 2) second = WorkspaceAllocator(1000, 2) assert first.allocate() == 1000 assert second.allocate() == 1000 assert first.in_use() == second.in_use() == [1000]