Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /test_cache_v4.py
| """ | |
| Corrected targeted tests for core/cache.py | |
| Exact signatures: | |
| SQLiteCache(db_path: Path = None, pool_size: int = 5, cleanup_interval: int = 3600) | |
| MultiTierCache(memory_size: int = 100, memory_max_mb: float = 50.0, | |
| sqlite_path: Optional[Path] = None, redis_config: Optional[dict] = None) | |
| """ | |
| import asyncio | |
| import json | |
| import os | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| from unittest.mock import AsyncMock, MagicMock, patch | |
| import pytest | |
| try: | |
| from core.cache import ( | |
| CacheStats, | |
| MemoryCache, | |
| MultiTierCache, | |
| RedisCache, | |
| SQLiteCache, | |
| ) | |
| HAS_CACHE = True | |
| except ImportError as e: | |
| HAS_CACHE = False | |
| pytestmark = pytest.mark.skip(f"core.cache: {e}") | |
| try: | |
| from core.cache import CacheManager | |
| HAS_MANAGER = True | |
| except ImportError: | |
| HAS_MANAGER = False | |
| try: | |
| from core.cache import async_cached, cached | |
| HAS_DECORATORS = True | |
| except ImportError: | |
| HAS_DECORATORS = False | |
| # =========================================================================== | |
| # SQLiteCache — exact constructor | |
| # =========================================================================== | |
| class TestSQLiteCacheCorrect: | |
| def setup_method(self): | |
| _tmpf = tempfile.NamedTemporaryFile(suffix=".db", delete=False) | |
| _tmpf.close() | |
| self.tmp = Path(_tmpf.name) | |
| try: | |
| self.cache = SQLiteCache(db_path=self.tmp) | |
| except Exception as e: | |
| pytest.skip(f"SQLiteCache init failed: {e}") | |
| def teardown_method(self): | |
| try: | |
| self.tmp.unlink(missing_ok=True) | |
| except Exception: # noqa: S110 - cleanup error can be ignored | |
| pass | |
| async def test_set_and_get_string(self): | |
| await self.cache.set("k", "hello") | |
| assert await self.cache.get("k") == "hello" | |
| async def test_set_and_get_int(self): | |
| await self.cache.set("n", 42) | |
| assert await self.cache.get("n") == 42 | |
| async def test_set_and_get_dict(self): | |
| val = {"host": "192.168.1.1", "ports": [22, 80, 443]} | |
| await self.cache.set("scan", val) | |
| assert await self.cache.get("scan") == val | |
| async def test_set_and_get_list(self): | |
| await self.cache.set("lst", [1, 2, 3]) | |
| assert await self.cache.get("lst") == [1, 2, 3] | |
| async def test_get_missing_returns_none(self): | |
| assert await self.cache.get("ghost_xyz") is None | |
| async def test_overwrite_key(self): | |
| await self.cache.set("k", "old") | |
| await self.cache.set("k", "new") | |
| assert await self.cache.get("k") == "new" | |
| async def test_delete_existing(self): | |
| await self.cache.set("del_me", "v") | |
| await self.cache.delete("del_me") | |
| assert await self.cache.get("del_me") is None | |
| async def test_delete_nonexistent_no_error(self): | |
| await self.cache.delete("never_existed_xyz") | |
| async def test_clear(self): | |
| await self.cache.set("a", 1) | |
| await self.cache.set("b", 2) | |
| await self.cache.clear() | |
| assert await self.cache.get("a") is None | |
| async def test_ttl_expiry(self): | |
| await self.cache.set("exp", "data", ttl=0) | |
| await asyncio.sleep(0.05) | |
| assert await self.cache.get("exp") is None | |
| async def test_long_ttl_not_expired(self): | |
| await self.cache.set("perm", "keep", ttl=99999) | |
| assert await self.cache.get("perm") == "keep" | |
| async def test_exists(self): | |
| if hasattr(self.cache, "exists"): | |
| await self.cache.set("here", 1) | |
| assert await self.cache.exists("here") is True | |
| assert await self.cache.exists("not_here") is False | |
| async def test_size(self): | |
| if hasattr(self.cache, "size"): | |
| await self.cache.set("x", 1) | |
| await self.cache.set("y", 2) | |
| sz = self.cache.size() | |
| assert sz >= 2 | |
| async def test_mget(self): | |
| if hasattr(self.cache, "mget"): | |
| await self.cache.set("p", 10) | |
| await self.cache.set("q", 20) | |
| results = await self.cache.mget(["p", "q", "missing"]) | |
| assert results.get("p") == 10 | |
| assert results.get("q") == 20 | |
| assert results.get("missing") is None | |
| async def test_mset(self): | |
| if hasattr(self.cache, "mset"): | |
| await self.cache.mset({"r": 1, "s": 2, "t": 3}) | |
| assert await self.cache.get("r") == 1 | |
| assert await self.cache.get("s") == 2 | |
| async def test_cleanup_expired(self): | |
| if hasattr(self.cache, "cleanup_expired"): | |
| await self.cache.set("old1", "v", ttl=0) | |
| await self.cache.set("old2", "v", ttl=0) | |
| await self.cache.set("fresh", "v", ttl=9999) | |
| await asyncio.sleep(0.05) | |
| removed = await self.cache.cleanup_expired() | |
| assert removed >= 0 | |
| assert await self.cache.get("fresh") == "v" | |
| async def test_persist_across_instances(self): | |
| await self.cache.set("persist", "survive") | |
| cache2 = SQLiteCache(db_path=self.tmp) | |
| assert await cache2.get("persist") == "survive" | |
| async def test_stats_tracking(self): | |
| if hasattr(self.cache, "stats"): | |
| await self.cache.set("s", "v") | |
| await self.cache.get("s") | |
| await self.cache.get("no_such") | |
| assert self.cache.stats.hits >= 1 | |
| assert self.cache.stats.misses >= 1 | |
| async def test_concurrent_writes(self): | |
| async def write(i): | |
| await self.cache.set(f"cc_{i}", i) | |
| await asyncio.gather(*[write(i) for i in range(10)]) | |
| for i in range(10): | |
| assert await self.cache.get(f"cc_{i}") == i | |
| def test_init_with_pool_size(self): | |
| _tmpf = tempfile.NamedTemporaryFile(suffix=".db", delete=False) | |
| _tmpf.close() | |
| tmp2 = Path(_tmpf.name) | |
| try: | |
| c = SQLiteCache(db_path=tmp2, pool_size=3) | |
| assert c is not None | |
| except Exception as e: | |
| pytest.skip(f"pool_size failed: {e}") | |
| finally: | |
| tmp2.unlink(missing_ok=True) | |
| def test_init_with_cleanup_interval(self): | |
| _tmpf = tempfile.NamedTemporaryFile(suffix=".db", delete=False) | |
| _tmpf.close() | |
| tmp3 = Path(_tmpf.name) | |
| try: | |
| c = SQLiteCache(db_path=tmp3, cleanup_interval=7200) | |
| assert c is not None | |
| except Exception as e: | |
| pytest.skip(f"cleanup_interval failed: {e}") | |
| finally: | |
| tmp3.unlink(missing_ok=True) | |
| def test_init_default_path(self): | |
| try: | |
| c = SQLiteCache() | |
| assert c is not None | |
| except Exception: # noqa: S110 - cleanup error can be ignored | |
| pass # May require explicit path | |
| # =========================================================================== | |
| # MultiTierCache — exact constructor | |
| # =========================================================================== | |
| class TestMultiTierCacheCorrect: | |
| def setup_method(self): | |
| try: | |
| self.mtc = MultiTierCache(memory_size=50, memory_max_mb=10.0) | |
| except Exception as e: | |
| pytest.skip(f"MultiTierCache init failed: {e}") | |
| async def test_set_and_get(self): | |
| await self.mtc.set("k", "v") | |
| result = await self.mtc.get("k") | |
| assert result == "v" | |
| async def test_get_miss(self): | |
| assert await self.mtc.get("nowhere_xyz_abc") is None | |
| async def test_delete(self): | |
| await self.mtc.set("del", "v") | |
| await self.mtc.delete("del") | |
| assert await self.mtc.get("del") is None | |
| async def test_clear(self): | |
| await self.mtc.set("a", 1) | |
| await self.mtc.set("b", 2) | |
| await self.mtc.clear() | |
| assert await self.mtc.get("a") is None | |
| async def test_set_get_dict(self): | |
| val = {"ports": [22, 80], "host": "10.0.0.1"} | |
| await self.mtc.set("scan", val) | |
| assert await self.mtc.get("scan") == val | |
| async def test_overwrite(self): | |
| await self.mtc.set("k", "old") | |
| await self.mtc.set("k", "new") | |
| assert await self.mtc.get("k") == "new" | |
| async def test_ttl_expiry(self): | |
| await self.mtc.set("tmp", "data", ttl=0) | |
| await asyncio.sleep(0.05) | |
| assert await self.mtc.get("tmp") is None | |
| async def test_stats(self): | |
| if hasattr(self.mtc, "stats"): | |
| await self.mtc.set("s", "v") | |
| await self.mtc.get("s") | |
| assert self.mtc.stats is not None | |
| async def test_size(self): | |
| if hasattr(self.mtc, "size"): | |
| await self.mtc.set("x", 1) | |
| sz = self.mtc.size() | |
| assert sz >= 1 | |
| def test_init_default_args(self): | |
| try: | |
| c = MultiTierCache() | |
| assert c is not None | |
| except Exception as e: | |
| pytest.skip(f"default init failed: {e}") | |
| def test_init_large_memory(self): | |
| try: | |
| c = MultiTierCache(memory_size=1000, memory_max_mb=500.0) | |
| assert c is not None | |
| except Exception as e: | |
| pytest.skip(f"large memory init failed: {e}") | |
| def test_init_with_sqlite(self): | |
| _tmpf = tempfile.NamedTemporaryFile(suffix=".db", delete=False) | |
| _tmpf.close() | |
| tmp = Path(_tmpf.name) | |
| try: | |
| c = MultiTierCache(memory_size=50, sqlite_path=tmp) | |
| assert c is not None | |
| except Exception as e: | |
| pytest.skip(f"sqlite_path init failed: {e}") | |
| finally: | |
| tmp.unlink(missing_ok=True) | |
| def test_init_with_redis_config(self): | |
| try: | |
| c = MultiTierCache( | |
| memory_size=50, | |
| redis_config={"host": "localhost", "port": 6379}, | |
| ) | |
| assert c is not None | |
| except Exception: # noqa: S110 - cleanup error can be ignored | |
| pass # Redis may not be running | |
| async def test_concurrent_access(self): | |
| async def worker(i): | |
| await self.mtc.set(f"ct_{i}", i) | |
| return await self.mtc.get(f"ct_{i}") | |
| results = await asyncio.gather(*[worker(i) for i in range(10)]) | |
| assert all(r is not None for r in results) | |
| async def test_hit_distribution(self): | |
| if hasattr(self.mtc, "get_hit_distribution"): | |
| await self.mtc.set("k", "v") | |
| await self.mtc.get("k") | |
| dist = self.mtc.get_hit_distribution() | |
| assert isinstance(dist, dict) | |
| async def test_mget(self): | |
| if hasattr(self.mtc, "mget"): | |
| await self.mtc.set("a", 1) | |
| await self.mtc.set("b", 2) | |
| results = await self.mtc.mget(["a", "b", "miss"]) | |
| assert results.get("a") == 1 | |
| async def test_mset(self): | |
| if hasattr(self.mtc, "mset"): | |
| await self.mtc.mset({"x": 10, "y": 20}) | |
| assert await self.mtc.get("x") == 10 | |
| async def test_exists(self): | |
| if hasattr(self.mtc, "exists"): | |
| await self.mtc.set("present", True) | |
| assert await self.mtc.exists("present") is True | |
| assert await self.mtc.exists("absent") is False | |
| # =========================================================================== | |
| # RedisCache — mock the connection | |
| # =========================================================================== | |
| class TestRedisCacheCorrect: | |
| def _make(self): | |
| mock_r = AsyncMock() | |
| mock_r.ping = AsyncMock(return_value=True) | |
| mock_r.get = AsyncMock(return_value=None) | |
| mock_r.set = AsyncMock(return_value=True) | |
| mock_r.setex = AsyncMock(return_value=True) | |
| mock_r.delete = AsyncMock(return_value=1) | |
| mock_r.exists = AsyncMock(return_value=0) | |
| mock_r.keys = AsyncMock(return_value=[]) | |
| mock_r.flushdb = AsyncMock(return_value=True) | |
| mock_r.mget = AsyncMock(return_value=[]) | |
| mock_r.expire = AsyncMock(return_value=True) | |
| mock_r.ttl = AsyncMock(return_value=60) | |
| mock_r.incr = AsyncMock(return_value=1) | |
| mock_r.hset = AsyncMock(return_value=1) | |
| mock_r.hget = AsyncMock(return_value=None) | |
| mock_r.hgetall = AsyncMock(return_value={}) | |
| mock_r.publish = AsyncMock(return_value=1) | |
| try: | |
| with ( | |
| patch("redis.asyncio.Redis", return_value=mock_r), | |
| patch("redis.Redis", return_value=mock_r), | |
| ): | |
| cache = RedisCache(host="localhost", port=6379, db=0) | |
| for attr in ("_redis", "_client", "client"): | |
| if hasattr(cache, attr): | |
| setattr(cache, attr, mock_r) | |
| cache._redis = mock_r | |
| return cache, mock_r | |
| except Exception as e: | |
| pytest.skip(f"RedisCache init failed: {e}") | |
| async def test_set_calls_redis(self): | |
| cache, mock_r = self._make() | |
| await cache.set("k", "v") | |
| assert mock_r.set.called or mock_r.setex.called | |
| async def test_set_with_ttl(self): | |
| cache, mock_r = self._make() | |
| await cache.set("k", "v", ttl=300) | |
| assert mock_r.setex.called or mock_r.set.called or mock_r.expire.called | |
| async def test_get_miss(self): | |
| cache, mock_r = self._make() | |
| mock_r.get.return_value = None | |
| assert await cache.get("missing") is None | |
| async def test_get_hit(self): | |
| cache, mock_r = self._make() | |
| mock_r.get.return_value = json.dumps("cached").encode() | |
| result = await cache.get("k") | |
| assert result == "cached" or result is not None | |
| async def test_delete(self): | |
| cache, mock_r = self._make() | |
| await cache.delete("k") | |
| assert mock_r.delete.called | |
| async def test_clear(self): | |
| cache, mock_r = self._make() | |
| await cache.clear() | |
| assert mock_r.flushdb.called or mock_r.keys.called | |
| async def test_mget(self): | |
| cache, mock_r = self._make() | |
| if hasattr(cache, "mget"): | |
| mock_r.mget.return_value = [json.dumps("v1").encode(), None] | |
| result = await cache.mget(["k1", "k2"]) | |
| assert isinstance(result, dict) | |
| async def test_hset_hget(self): | |
| cache, mock_r = self._make() | |
| if hasattr(cache, "hset") and hasattr(cache, "hget"): | |
| await cache.hset("h", "f", "val") | |
| mock_r.hget.return_value = json.dumps("val").encode() | |
| result = await cache.hget("h", "f") | |
| assert result is not None | |
| async def test_publish(self): | |
| cache, mock_r = self._make() | |
| if hasattr(cache, "publish"): | |
| await cache.publish("chan", {"event": "invalidate"}) | |
| assert mock_r.publish.called | |
| # =========================================================================== | |
| # CacheManager | |
| # =========================================================================== | |
| class TestCacheManagerCorrect: | |
| def setup_method(self): | |
| try: | |
| CacheManager.clear_all() | |
| except Exception: # noqa: S110 - cleanup error can be ignored | |
| pass | |
| def test_get_returns_cache(self): | |
| c = CacheManager.get_cache("test") | |
| assert c is not None | |
| def test_same_name_same_instance(self): | |
| c1 = CacheManager.get_cache("shared") | |
| c2 = CacheManager.get_cache("shared") | |
| assert c1 is c2 | |
| def test_different_names_isolated(self): | |
| c1 = CacheManager.get_cache("ns1") | |
| c2 = CacheManager.get_cache("ns2") | |
| assert c1 is not c2 | |
| def test_clear_all(self): | |
| CacheManager.get_cache("will_clear") | |
| CacheManager.clear_all() | |
| assert CacheManager.get_cache("will_clear") is not None | |
| def test_list_caches(self): | |
| if hasattr(CacheManager, "list_caches"): | |
| CacheManager.get_cache("listed_cache") | |
| assert "listed_cache" in CacheManager.list_caches() | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v"]) | |
Xet Storage Details
- Size:
- 17.2 kB
- Xet hash:
- 3053c2a8fbb26b6013abad7a895db90b2768e31195dcf7222ba9a9e61e2ba217
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.