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 == [] 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") def test_initialize_database_removes_legacy_used_activation_codes(): with TempDatabase(): with db.get_connection() as connection: cursor = connection.execute( """ INSERT INTO users (email, password_hash, display_name) VALUES ('legacy-user', 'hash', 'legacy-user') """ ) connection.execute( """ INSERT INTO activation_codes ( code, created_by, used_by_user_id, used_at, status ) VALUES ('SL-USED12-USED34-USED56', 'admin', ?, CURRENT_TIMESTAMP, 'used') """, (int(cursor.lastrowid),), ) with db.get_connection() as connection: count = connection.execute( "SELECT COUNT(*) AS count FROM activation_codes WHERE status = 'used'" ).fetchone()["count"] assert count == 1 db.initialize_database() with db.get_connection() as connection: count = connection.execute("SELECT COUNT(*) AS count FROM activation_codes").fetchone()["count"] assert count == 0 if __name__ == "__main__": test_password_hash_roundtrip() test_auth_token_roundtrip_and_tamper_rejection() test_activation_code_registers_user_once() test_initialize_database_removes_legacy_used_activation_codes()