ЛР 3: балансировка, 2 реплики API и общая идемпотентность (оценка 3)

This commit is contained in:
Яковлев Матвей Дмитриевич
2026-11-16 23:34:49 +01:00
parent 0ab3a341aa
commit c8ee2a50b8
18 changed files with 1204 additions and 21 deletions
+91
View File
@@ -0,0 +1,91 @@
"""Own tests for the security helpers and keyset cursors (stdlib unittest)."""
import base64
import datetime as dt
import json
import sys
import unittest
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app import main as api
from app.security import (bearer_token, hash_password, parse_basic,
token_hash, verify_password)
class PasswordTests(unittest.TestCase):
def test_kdf_round_trip_and_uniqueness(self):
first = hash_password("T3st-passphrase-123")
second = hash_password("T3st-passphrase-123")
self.assertNotEqual(first, second, "salt must be unique")
self.assertTrue(first.startswith("scrypt$"))
self.assertTrue(verify_password("T3st-passphrase-123", first))
self.assertFalse(verify_password("wrong-password", first))
def test_unicode_and_colon_password(self):
secret = "пароль:с:двоеточием-123"
stored = hash_password(secret)
self.assertTrue(verify_password(secret, stored))
self.assertFalse(verify_password("пароль", stored))
class CredentialTests(unittest.TestCase):
def test_basic_colon_inside_password(self):
raw = "u_alice_123:T3st-with:colon-12345"
header = "Basic " + base64.b64encode(raw.encode()).decode()
self.assertEqual(parse_basic(header), ("u_alice_123", "T3st-with:colon-12345"))
def test_basic_rejects_short_password_and_bad_scheme(self):
raw = "u_alice_123:short"
self.assertIsNone(parse_basic("Basic " + base64.b64encode(raw.encode()).decode()))
self.assertIsNone(parse_basic("Bearer abcdef"))
def test_bearer_only(self):
self.assertEqual(bearer_token("Bearer abc"), "abc")
self.assertIsNone(bearer_token("Basic abc"))
self.assertIsNone(bearer_token(None))
def test_token_hash_is_stable_and_not_the_token(self):
token = "s" * 43
self.assertEqual(token_hash(token), token_hash(token))
self.assertNotEqual(token_hash(token), token)
class IdempotencyTests(unittest.TestCase):
def test_key_pattern(self):
self.assertIsNotNone(api.IDEMPOTENCY_KEY_RE.fullmatch('abc-123.XYZ:9_'))
self.assertIsNone(api.IDEMPOTENCY_KEY_RE.fullmatch('bad key'))
self.assertIsNone(api.IDEMPOTENCY_KEY_RE.fullmatch(''))
def test_canonical_body_hash_ignores_key_order(self):
import hashlib
a = json.dumps({'text': 'Привет'}, sort_keys=True, separators=(',', ':'))
b = json.dumps({'text': 'Привет'}, separators=(',', ':'))
self.assertEqual(hashlib.sha256(a.encode()).hexdigest(),
hashlib.sha256(b.encode()).hexdigest())
class CursorTests(unittest.TestCase):
def test_round_trip(self):
created = dt.datetime(2026, 11, 16, 12, 0, 0, 123456, tzinfo=dt.timezone.utc)
item_id = uuid.uuid4()
encoded = api.encode_cursor("messages", "scope-1", created, item_id)
back_created, back_id = api.decode_cursor(encoded, "messages", "scope-1")
self.assertEqual(back_created, created)
self.assertEqual(back_id, item_id)
def test_wrong_scope_rejected(self):
created = dt.datetime.now(dt.timezone.utc)
encoded = api.encode_cursor("messages", "chat-A", created, uuid.uuid4())
with self.assertRaises(api.ApiError):
api.decode_cursor(encoded, "messages", "chat-B")
def test_garbage_rejected(self):
with self.assertRaises(api.ApiError):
api.decode_cursor("not-a-cursor", "messages", "chat-A")
if __name__ == "__main__":
unittest.main(verbosity=2)