Files
mtusi2026lab3/tests_local/test_helpers.py

73 lines
2.7 KiB
Python

"""Fast pure-function checks; can run even without a local PostgreSQL/Docker install."""
import base64
from datetime import datetime, timezone
import importlib
import json
import sys
import types
import unittest
import uuid
try:
import psycopg # noqa: F401
except ImportError:
pg = types.ModuleType("psycopg")
pg.OperationalError = type("OperationalError", (Exception,), {})
pg.errors = types.SimpleNamespace(
UniqueViolation=type("UniqueViolation", (Exception,), {}),
QueryCanceled=type("QueryCanceled", (Exception,), {}),
)
sys.modules["psycopg"] = pg
rows = types.ModuleType("psycopg.rows")
rows.dict_row = lambda *args: None
sys.modules["psycopg.rows"] = rows
import server
class HelpersTest(unittest.TestCase):
def test_password_kdf(self):
h1 = server.password_hash("test-pass-123456789")
h2 = server.password_hash("test-pass-123456789")
self.assertNotEqual(h1, h2)
self.assertTrue(server.password_matches("test-pass-123456789", h1))
self.assertFalse(server.password_matches("WRONG", h1))
def test_uuid(self):
value = str(uuid.uuid4())
self.assertEqual(server.uuid_string(value), value)
for invalid in ("abc", None, value.upper()):
with self.assertRaises(server.ApiError):
server.uuid_string(invalid)
def test_cursor_page(self):
scope = "messages:" + str(uuid.uuid4())
a, b = str(uuid.uuid4()), str(uuid.uuid4())
items = [{"id": x, "created_at": "2026-11-16T12:00:00.000001Z"} for x in [a, b]]
result = server.next_page(items, 1, scope)
self.assertEqual(len(result["items"]), 1)
self.assertIsNotNone(result["next_cursor"])
limit, position = server.pagination({"limit": ["1"], "cursor": [result["next_cursor"]]}, scope)
self.assertEqual(limit, 1)
self.assertEqual(position[1], a)
self.assertEqual(position[0], datetime(2026, 11, 16, 12, 0, 0, 1, tzinfo=timezone.utc))
with self.assertRaises(server.ApiError):
server.pagination({"cursor": [result["next_cursor"]]}, "messages:another-chat")
def test_limits(self):
with self.assertRaises(server.ApiError):
server.pagination({"limit": ["0"]}, "chats:alice")
with self.assertRaises(server.ApiError):
server.pagination({"limit": ["101"]}, "chats:alice")
with self.assertRaises(server.ApiError):
server.require_fields({"text": "hi", "extra": "no"}, {"text"})
def test_keys(self):
self.assertTrue(server.IDEMPOTENCY_RE.fullmatch("aB12_:-.z"))
self.assertFalse(server.IDEMPOTENCY_RE.fullmatch("bad key"))
self.assertFalse(server.IDEMPOTENCY_RE.fullmatch(""))
if __name__ == "__main__":
unittest.main()