72 lines
3.1 KiB
Python
72 lines
3.1 KiB
Python
"""Real PostgreSQL and Valkey checks for the optional User cache."""
|
|
|
|
import os
|
|
import unittest
|
|
from contextlib import contextmanager
|
|
from unittest.mock import patch
|
|
from uuid import uuid4
|
|
|
|
from src import cache
|
|
from src.store import Store, connection
|
|
|
|
|
|
@unittest.skipUnless((os.environ.get("DATABASE_URL") or os.environ.get("DATABASE_URL_FILE"))
|
|
and os.environ.get("VALKEY_URL"),
|
|
"set DATABASE_URL or DATABASE_URL_FILE and VALKEY_URL for disposable services")
|
|
class CacheTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.store = Store()
|
|
self.user = self.store.register("u_" + uuid4().hex[:16], "Кэш", "Test-password-123")
|
|
self.token = self.store.create_session(self.user["username"], "Test-password-123")["token"]
|
|
|
|
def test_hit_miss_and_sql_counts(self):
|
|
statements = []
|
|
|
|
class CountingConnection:
|
|
def __init__(self, wrapped):
|
|
self.wrapped = wrapped
|
|
|
|
def execute(self, query, params=None):
|
|
statements.append(query)
|
|
return self.wrapped.execute(query, params)
|
|
|
|
@contextmanager
|
|
def counted_connection():
|
|
with connection() as conn:
|
|
yield CountingConnection(conn)
|
|
|
|
with patch("src.store.connection", counted_connection):
|
|
before = cache.command("INFO", "stats")
|
|
self.assertEqual(self.store.authenticated(self.token), self.user)
|
|
miss_sql = len(statements)
|
|
self.assertEqual(miss_sql, 2) # session plus User on miss
|
|
statements.clear()
|
|
self.assertEqual(self.store.authenticated(self.token), self.user)
|
|
hit_sql = len(statements)
|
|
self.assertEqual(hit_sql, 1) # session only on cache hit
|
|
cache.command("DEL", "user:" + self.user["id"])
|
|
statements.clear()
|
|
self.assertEqual(self.store.authenticated(self.token), self.user)
|
|
reload_sql = len(statements)
|
|
self.assertEqual(reload_sql, 2) # User reload after flush
|
|
after = cache.command("INFO", "stats")
|
|
def stat(info, name):
|
|
return int(next(line.split(":", 1)[1] for line in info.splitlines() if line.startswith(name + ":")))
|
|
self.assertGreaterEqual(stat(after, "keyspace_hits") - stat(before, "keyspace_hits"), 1)
|
|
self.assertGreaterEqual(stat(after, "keyspace_misses") - stat(before, "keyspace_misses"), 2)
|
|
print(f"SQL queries (miss/hit/reload): {miss_sql}/{hit_sql}/{reload_sql}; "
|
|
f"Valkey hit/miss deltas: {stat(after, 'keyspace_hits') - stat(before, 'keyspace_hits')}/"
|
|
f"{stat(after, 'keyspace_misses') - stat(before, 'keyspace_misses')}")
|
|
|
|
def test_cache_failure_does_not_change_authentication(self):
|
|
with patch.dict(os.environ, {"VALKEY_URL": "redis://127.0.0.1:1/0"}):
|
|
self.assertEqual(self.store.authenticated(self.token), self.user)
|
|
self.store.revoke_session(self.token)
|
|
with self.assertRaises(Exception) as failure:
|
|
self.store.authenticated(self.token)
|
|
self.assertEqual(failure.exception.status_code, 401)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|