| 1 |
"""Shared fixtures for the memory-sync suite.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing import Any |
| 6 |
from contextlib import contextmanager |
| 7 |
from collections.abc import Callable, Iterator, AsyncIterator |
| 8 |
|
| 9 |
import pytest |
| 10 |
|
| 11 |
import anthropic.lib.tools._memories as memories_mod |
| 12 |
from anthropic.lib.tools._memories import SessionMemoryStores |
| 13 |
from anthropic.types.beta.memory_stores import BetaManagedAgentsMemory |
| 14 |
|
| 15 |
|
| 16 |
class Clock: |
| 17 |
"""A settable stand-in for the module's `monotonic`.""" |
| 18 |
|
| 19 |
def __init__(self) -> None: |
| 20 |
self.now = 0.0 |
| 21 |
|
| 22 |
def __call__(self) -> float: |
| 23 |
return self.now |
| 24 |
|
| 25 |
|
| 26 |
@pytest.fixture() |
| 27 |
def clock(monkeypatch: pytest.MonkeyPatch) -> Clock: |
| 28 |
c = Clock() |
| 29 |
monkeypatch.setattr(memories_mod, "monotonic", c) |
| 30 |
return c |
| 31 |
|
| 32 |
|
| 33 |
async def run_sync(stores: SessionMemoryStores) -> None: |
| 34 |
"""Drive one reconcile pass without clock bookkeeping. |
| 35 |
|
| 36 |
The public cadence path (`sync_if_due` plus the clock) is exercised |
| 37 |
by the worker tests; unit tests call the pass directly. |
| 38 |
""" |
| 39 |
await stores._sync_all(final=False) # pyright: ignore[reportPrivateUsage] -- the suite's one deterministic driver |
| 40 |
|
| 41 |
|
| 42 |
@contextmanager |
| 43 |
def listing_interrupted_by( |
| 44 |
stores: SessionMemoryStores, interrupt: Callable[[], object], *, after_items: int | None = None |
| 45 |
) -> Iterator[None]: |
| 46 |
"""Run `interrupt` once while a sync's server listing is being consumed: |
| 47 |
right after the sync has processed `after_items` listed memories, or |
| 48 |
once the listing is exhausted when `None`. This lands a change on disk |
| 49 |
after the sync's directory scan and before whatever it does next.""" |
| 50 |
real_list = stores._list_memories |
| 51 |
|
| 52 |
async def interrupted(memory_store_id: str, **kwargs: Any) -> AsyncIterator[BetaManagedAgentsMemory]: |
| 53 |
consumed = 0 |
| 54 |
async for item in real_list(memory_store_id, **kwargs): |
| 55 |
yield item |
| 56 |
consumed += 1 |
| 57 |
if consumed == after_items: |
| 58 |
interrupt() |
| 59 |
if after_items is None: |
| 60 |
interrupt() |
| 61 |
|
| 62 |
stores._list_memories = interrupted # type: ignore[method-assign] |
| 63 |
try: |
| 64 |
yield |
| 65 |
finally: |
| 66 |
stores._list_memories = real_list # type: ignore[method-assign] |