Buckets:

download
raw
14.4 kB
import asyncio
import socket
import sys
import pytest
import pytest_asyncio
from fastapi_cachex.backends import MemcachedBackend
from fastapi_cachex.exceptions import CacheXError
from fastapi_cachex.types import CacheEntry
from fastapi_cachex.types import counter_entry
def is_memcached_running(host: str = "127.0.0.1", port: int = 11211) -> bool:
"""Check if memcached is running."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
except (OSError, ConnectionRefusedError):
return False
else:
return True
finally:
sock.close()
requires_memcached = pytest.mark.skipif(
not is_memcached_running(),
reason="Memcached server is not running",
)
def test_memcached_without_pymemcache(monkeypatch):
"""Test that MemcachedBackend raises an error when pymemcache is not installed."""
# Remove pymemcache from sys.modules
if "pymemcache" in sys.modules:
del sys.modules["pymemcache"]
# Also patch __import__ to raise ImportError for pymemcache
orig_import = __import__
def mock_import(name, *args, **kwargs):
if name == "pymemcache":
msg = "No module named 'pymemcache'"
raise ImportError(msg)
return orig_import(name, *args, **kwargs)
monkeypatch.setattr("builtins.__import__", mock_import)
with pytest.raises(CacheXError) as exc_info:
MemcachedBackend(servers=["localhost:11211"])
assert "pymemcache is not installed" in str(exc_info.value)
@pytest_asyncio.fixture
async def memcached_backend():
backend = MemcachedBackend(servers=["127.0.0.1:11211"])
await backend.clear()
return backend
@requires_memcached
def test_memcached_client_waits_for_write_acknowledgements() -> None:
# With pooling, an unacknowledged write on one socket can still be in flight
# while a read on another socket is served; every command must be replied to.
backend = MemcachedBackend(servers=["127.0.0.1:11211"])
assert backend.client.use_pooling is True
assert backend.client.default_kwargs["default_noreply"] is False
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_set_get(memcached_backend: MemcachedBackend):
key = "test_key"
value = CacheEntry(fingerprint="test_etag", content=b"test_content")
ttl = 60
await memcached_backend.set(key, value, ttl)
retrieved_value = await memcached_backend.get(key)
assert retrieved_value is not None
assert retrieved_value.fingerprint == value.fingerprint
assert retrieved_value.content == value.content
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_set_without_ttl(memcached_backend: MemcachedBackend):
key = "test_key"
value = CacheEntry(fingerprint="test_etag", content=b"test_content")
await memcached_backend.set(key, value)
retrieved_value = await memcached_backend.get(key)
assert retrieved_value is not None
assert retrieved_value.fingerprint == value.fingerprint
assert retrieved_value.content == value.content
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_delete(memcached_backend: MemcachedBackend):
key = "test_key"
value = CacheEntry(fingerprint="test_etag", content=b"test_content")
await memcached_backend.set(key, value)
await memcached_backend.delete(key)
retrieved_value = await memcached_backend.get(key)
assert retrieved_value is None
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_clear(memcached_backend: MemcachedBackend):
key1 = "test_key1"
value1 = CacheEntry(fingerprint="test_etag1", content=b"test_content1")
key2 = "test_key2"
value2 = CacheEntry(fingerprint="test_etag2", content=b"test_content2")
await memcached_backend.set(key1, value1)
await memcached_backend.set(key2, value2)
await memcached_backend.clear()
retrieved_value1 = await memcached_backend.get(key1)
retrieved_value2 = await memcached_backend.get(key2)
assert retrieved_value1 is None
assert retrieved_value2 is None
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_clear_path(memcached_backend: MemcachedBackend):
# Set up test data
path = "/test"
value = CacheEntry(fingerprint="test_etag", content=b"test_value")
# Store data directly at the path
await memcached_backend.set(path, value)
# Test clearing the exact path
cleared = await memcached_backend.clear_path(path, include_params=False)
assert cleared == 1 # Should clear the exact path match
# Verify the path is cleared
result = await memcached_backend.get(path)
assert result is None
# Test include_params=True (should return 0 as this is not supported)
cleared = await memcached_backend.clear_path(path, include_params=True)
assert cleared == 0 # Should return 0 as this operation is not supported
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_clear_path_not_match(memcached_backend: MemcachedBackend):
# Set up test data
path = "/test"
value = CacheEntry(fingerprint="test_etag", content=b"test_value")
# Store data directly at the path
await memcached_backend.set(path, value)
# Make sure there is no data at a different path
other_path = "/other_path"
other_value = await memcached_backend.get(other_path) # This should return None
assert other_value is None
# Test clearing a non-matching path
cleared = await memcached_backend.clear_path(other_path, include_params=False)
assert cleared == 0 # Should return 0 as the path does not match
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_clear_pattern(memcached_backend: MemcachedBackend):
# Set up test data
path = "/users/123"
value = CacheEntry(fingerprint="test_etag", content=b"test_value")
# Store some test data
await memcached_backend.set(path, value)
# Test pattern clearing (should always return 0 as not supported)
cleared = await memcached_backend.clear_pattern("/users/*")
assert cleared == 0 # Should return 0 as pattern matching is not supported
# Verify the original data still exists (as pattern matching is not supported)
result = await memcached_backend.get(path)
assert result is not None
assert result.fingerprint == value.fingerprint
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_clear_path_warning(memcached_backend: MemcachedBackend):
# Test that warning is raised when using include_params=True
with pytest.warns(
RuntimeWarning,
match="Memcached backend does not support pattern-based key clearing",
):
cleared = await memcached_backend.clear_path("/test", include_params=True)
assert cleared == 0
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_clear_pattern_warning(memcached_backend: MemcachedBackend):
# Test that warning is raised when using pattern matching
with pytest.warns(
RuntimeWarning,
match="Memcached backend does not support pattern matching",
):
cleared = await memcached_backend.clear_pattern("/users/*")
assert cleared == 0
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_set_content_bytes(monkeypatch) -> None:
"""Test bytes content round-trip through set/get."""
backend = MemcachedBackend(servers=["127.0.0.1:11211"])
await backend.clear()
value = CacheEntry(fingerprint="c", content=b"bytes-content")
await backend.set("bytes-key", value)
out = await backend.get("bytes-key")
assert out is not None
assert out.fingerprint == value.fingerprint
assert out.content == b"bytes-content"
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_invalid_and_missing_fields(
memcached_backend: MemcachedBackend,
) -> None:
"""Cover get() error handling for invalid JSON and missing fields."""
# Write invalid JSON directly into client
raw_key = memcached_backend._make_key("invalid-json")
memcached_backend.client.set(raw_key, b"not a json", expire=0)
res = await memcached_backend.get("invalid-json")
assert res is None
# JSON missing required fields
raw_key2 = memcached_backend._make_key("missing-fields")
memcached_backend.client.set(raw_key2, b'{"some": "data"}', expire=0)
res2 = await memcached_backend.get("missing-fields")
assert res2 is None
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_clear_path_exception(
monkeypatch,
memcached_backend: MemcachedBackend,
) -> None:
"""Simulate client.delete raising to hit exception branch in clear_path()."""
def boom(*args, **kwargs) -> None:
msg = "delete failed"
raise RuntimeError(msg)
monkeypatch.setattr(memcached_backend.client, "delete", boom)
cleared = await memcached_backend.clear_path("/nope", include_params=False)
assert cleared == 0
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_all_keys_empty(
memcached_backend: MemcachedBackend,
) -> None:
"""Test get_all_keys returns empty list for Memcached (unsupported)."""
await memcached_backend.clear()
keys = await memcached_backend.get_all_keys()
# Memcached doesn't support key enumeration
assert keys == []
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_all_keys_warning(
memcached_backend: MemcachedBackend,
) -> None:
"""Test get_all_keys issues warning for Memcached."""
with pytest.warns(
RuntimeWarning,
match="Memcached backend does not support key enumeration",
):
keys = await memcached_backend.get_all_keys()
assert keys == []
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_cache_data_empty(
memcached_backend: MemcachedBackend,
) -> None:
"""Test get_cache_data returns empty dict for Memcached (unsupported)."""
await memcached_backend.clear()
cache_data = await memcached_backend.get_cache_data()
# Memcached doesn't support key enumeration
assert cache_data == {}
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_cache_data_warning(
memcached_backend: MemcachedBackend,
) -> None:
"""Test get_cache_data issues warning for Memcached."""
with pytest.warns(
RuntimeWarning,
match="Memcached backend does not support key enumeration",
):
cache_data = await memcached_backend.get_cache_data()
assert cache_data == {}
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_concurrent_calls_do_not_share_a_socket(
memcached_backend: MemcachedBackend,
) -> None:
"""Every call runs in a worker thread; the client must be thread-safe."""
entries = {
f"k{i}": CacheEntry(fingerprint=f"e{i}", content=f"v{i}".encode())
for i in range(40)
}
await asyncio.gather(*(memcached_backend.set(k, v, 60) for k, v in entries.items()))
results = await asyncio.gather(*(memcached_backend.get(k) for k in entries))
assert results == list(entries.values())
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_increment_creates_then_adds(
memcached_backend: MemcachedBackend,
) -> None:
assert await memcached_backend.increment("hits") == 1
assert await memcached_backend.increment("hits") == 2
assert await memcached_backend.increment("hits", 5) == 7
assert await memcached_backend.increment("hits", -3) == 4
assert await memcached_backend.get("hits") == counter_entry(4)
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_increment_decrement_stops_at_zero(
memcached_backend: MemcachedBackend,
) -> None:
await memcached_backend.increment("floor", 2)
assert await memcached_backend.increment("floor", -5) == 0
assert await memcached_backend.increment("missing", -5) == 0
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_increment_honors_ttl(
memcached_backend: MemcachedBackend,
) -> None:
await memcached_backend.increment("window", ttl=1)
await memcached_backend.increment("window", ttl=3600)
await asyncio.sleep(2)
assert await memcached_backend.get("window") is None
assert await memcached_backend.increment("window", ttl=1) == 1
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_increment_rejects_a_cached_response(
memcached_backend: MemcachedBackend,
) -> None:
await memcached_backend.set("page", CacheEntry(fingerprint="e", content=b"<html>"))
with pytest.raises(CacheXError, match="not a counter"):
await memcached_backend.increment("page")
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_increment_is_atomic_under_concurrency(
memcached_backend: MemcachedBackend,
) -> None:
results = await asyncio.gather(
*(memcached_backend.increment("race", ttl=60) for _ in range(30))
)
assert sorted(results) == list(range(1, 31))
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_and_delete_returns_then_removes(
memcached_backend: MemcachedBackend,
) -> None:
value = CacheEntry(fingerprint="e", content=b"once", media_type="text/plain")
await memcached_backend.set("once", value, 60)
assert await memcached_backend.get_and_delete("once") == value
assert await memcached_backend.get_and_delete("once") is None
assert await memcached_backend.get("once") is None
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_and_delete_loses_the_race_when_delete_fails(
memcached_backend: MemcachedBackend, monkeypatch
) -> None:
await memcached_backend.set("once", CacheEntry(fingerprint="e", content=b"x"), 60)
monkeypatch.setattr(memcached_backend.client, "delete", lambda *a, **kw: False)
assert await memcached_backend.get_and_delete("once") is None
@requires_memcached
@pytest.mark.asyncio
async def test_memcached_get_and_delete_has_exactly_one_winner(
memcached_backend: MemcachedBackend,
) -> None:
value = CacheEntry(fingerprint="e", content=b"once")
await memcached_backend.set("once", value, 60)
results = await asyncio.gather(
*(memcached_backend.get_and_delete("once") for _ in range(20))
)
assert results.count(value) == 1
assert results.count(None) == 19

Xet Storage Details

Size:
14.4 kB
·
Xet hash:
e40b55caf3f34b3ee049293affd3985584503e8ae754217ab2b16ae2b71c6621

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.