test_auth_utils.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import pytest
  2. import sys
  3. from datetime import timedelta
  4. from unittest.mock import patch
  5. # Force reload to bypass the global mock in conftest
  6. if "session_utils" in sys.modules:
  7. del sys.modules["session_utils"]
  8. import session_utils
  9. if "auth_utils" in sys.modules:
  10. del sys.modules["auth_utils"]
  11. import auth_utils
  12. from auth_utils import verify_password, get_password_hash, create_access_token, decode_token
  13. def test_password_hashing():
  14. pwd = "secret-password"
  15. hashed = get_password_hash(pwd)
  16. assert verify_password(pwd, hashed) is True
  17. assert verify_password("wrong", hashed) is False
  18. def test_token_creation_and_decoding():
  19. user_data = {"id": 1, "email": "test@example.com", "role": "admin"}
  20. with patch("auth_utils.session_utils") as mock_session:
  21. mock_session.create_session.return_value = "mock-sid"
  22. mock_session.validate_session.return_value = True
  23. token = create_access_token(user_data)
  24. assert token is not None
  25. decoded = decode_token(token)
  26. assert decoded is not None
  27. assert decoded["id"] == 1
  28. assert decoded["email"] == "test@example.com"
  29. assert decoded["role"] == "admin"
  30. assert decoded["sid"] == "mock-sid"
  31. def test_decode_invalid_token():
  32. assert decode_token("invalid.token.here") is None
  33. def test_decode_expired_or_revoked_session():
  34. user_data = {"id": 1, "sid": "revoked-sid"}
  35. with patch("auth_utils.session_utils") as mock_session:
  36. mock_session.validate_session.return_value = False
  37. # We manually create a token that looks valid but whose SID is revoked
  38. from jose import jwt
  39. from auth_utils import SECRET_KEY, ALGORITHM
  40. token = jwt.encode(user_data, SECRET_KEY, algorithm=ALGORITHM)
  41. decoded = decode_token(token)
  42. assert decoded is None