Files
speaking-practice/tests/auth_helpers_test.py
T
TTlaji 2d3ff21222
Deploy Speaking Practice / deploy (push) Successful in 24s
feat: add activation-code auth
2026-06-05 16:56:30 +08:00

74 lines
2.3 KiB
Python

import tempfile
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import db
from backend.auth import create_auth_token, hash_password, verify_auth_token, verify_password
class TempDatabase:
def __enter__(self):
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
self.original = db.DATABASE_PATH
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
db.initialize_database()
return db.DATABASE_PATH
def __exit__(self, exc_type, exc, tb):
db.DATABASE_PATH = self.original
self.temp_dir.cleanup()
def test_password_hash_roundtrip():
stored = hash_password("secret123")
assert stored != "secret123"
assert verify_password("secret123", stored) is True
assert verify_password("wrong", stored) is False
def test_auth_token_roundtrip_and_tamper_rejection():
token = create_auth_token({"username": "student", "role": "user", "userId": 1}, "secret")
payload = verify_auth_token(token, "secret")
assert payload["username"] == "student"
assert payload["role"] == "user"
assert verify_auth_token(token + "x", "secret") is None
def test_activation_code_registers_user_once():
with TempDatabase():
created = db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
assert created[0]["status"] == "unused"
user = db.register_user_with_activation(
username="student",
password_hash=hash_password("secret123"),
activation_code="SL-ABC123-DEF456-GHI789",
)
assert user["username"] == "student"
codes = db.list_activation_codes()
assert codes[0]["status"] == "used"
assert codes[0]["usedByUsername"] == "student"
try:
db.register_user_with_activation(
username="student2",
password_hash=hash_password("secret123"),
activation_code="SL-ABC123-DEF456-GHI789",
)
except ValueError as error:
assert str(error) == "activation_code_unavailable"
else:
raise AssertionError("used activation code should not register another user")
if __name__ == "__main__":
test_password_hash_roundtrip()
test_auth_token_roundtrip_and_tamper_rejection()
test_activation_code_registers_user_once()