4
0

test_services.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """
  2. Tests for services layer — auth, user, quota logic.
  3. """
  4. import secrets
  5. from unittest.mock import patch
  6. from database.models.models import QuotaGroup, QuotaUser
  7. class TestAuthService:
  8. """Test AuthService password hashing and token logic."""
  9. def test_hash_password_bcrypt_returns_tuple(self):
  10. from services.auth.auth_service import AuthService
  11. pw_hash, salt = AuthService.hash_password_bcrypt("testpassword123")
  12. assert isinstance(pw_hash, str)
  13. assert isinstance(salt, str)
  14. assert len(pw_hash) > 0
  15. assert len(salt) > 0
  16. def test_hash_password_bcrypt_different_salts(self):
  17. from services.auth.auth_service import AuthService
  18. h1, s1 = AuthService.hash_password_bcrypt("samepassword")
  19. h2, s2 = AuthService.hash_password_bcrypt("samepassword")
  20. # Different salts should produce different hashes
  21. assert s1 != s2
  22. def test_verify_password(self):
  23. from services.auth.auth_service import AuthService
  24. pw_hash, salt = AuthService.hash_password_bcrypt("mypassword")
  25. assert AuthService.verify_password("mypassword", pw_hash, salt) is True
  26. assert AuthService.verify_password("wrongpassword", pw_hash, salt) is False
  27. def test_generate_token(self):
  28. from services.auth.auth_service import AuthService
  29. secret_key = secrets.token_urlsafe(32)
  30. with patch("services.auth.auth_service.Config") as mock_config:
  31. mock_config.JWT_SECRET_KEY = secret_key
  32. user_data = {"id": 1, "username": "admin", "role": "admin"}
  33. token = AuthService.generate_token(user_data)
  34. assert isinstance(token, str)
  35. assert len(token) > 0
  36. def test_verify_token_roundtrip(self):
  37. from services.auth.auth_service import AuthService
  38. secret_key = secrets.token_urlsafe(32)
  39. with patch("services.auth.auth_service.Config") as mock_config:
  40. mock_config.JWT_SECRET_KEY = secret_key
  41. user_data = {"id": 42, "username": "testuser", "role": "admin"}
  42. token = AuthService.generate_token(user_data)
  43. payload = AuthService.validate_token(token)
  44. assert payload is not None
  45. assert payload["sub"] == "testuser"
  46. assert payload["role"] == "admin"
  47. class TestUserService:
  48. """Test user_service functions."""
  49. def test_create_user_empty_username(self):
  50. from services.auth.user_service import create_user
  51. ok, msg = create_user("", "password123")
  52. assert ok is False
  53. assert "obligatorios" in msg.lower() or "obligatorios" in msg
  54. def test_create_user_short_password(self):
  55. from services.auth.user_service import create_user
  56. ok, msg = create_user("admin", "123")
  57. assert ok is False
  58. assert "8 caracteres" in msg
  59. def test_update_user_short_password(self):
  60. from services.auth.user_service import update_user
  61. ok, msg = update_user(1, "admin", "123", "admin", 1)
  62. assert ok is False
  63. assert "8 caracteres" in msg
  64. class TestQuotaModels:
  65. """Test quota-related DB operations."""
  66. def test_quota_user_exceeds_limit(self, db_session):
  67. user = QuotaUser(username="heavy_user", quota_mb=1024, used_mb=2048)
  68. db_session.add(user)
  69. db_session.commit()
  70. result = db_session.query(QuotaUser).first()
  71. assert result.used_mb > result.quota_mb
  72. def test_group_quota_tracking(self, db_session):
  73. group = QuotaGroup(group_name="marketing", quota_mb=5120)
  74. db_session.add(group)
  75. users = [
  76. QuotaUser(username="u1", group_name="marketing", quota_mb=0, used_mb=1000),
  77. QuotaUser(username="u2", group_name="marketing", quota_mb=0, used_mb=2000),
  78. QuotaUser(username="u3", group_name="marketing", quota_mb=0, used_mb=3000),
  79. ]
  80. db_session.add_all(users)
  81. db_session.commit()
  82. total_usage = sum(
  83. u.used_mb
  84. for u in db_session.query(QuotaUser).filter_by(group_name="marketing").all()
  85. )
  86. assert total_usage == 6000
  87. assert total_usage > group.quota_mb # Group exceeded
  88. class TestLogsService:
  89. """Test logs service output cleaning and fallback behavior."""
  90. def test_read_logs_strips_ansi_sequences(self, tmp_path):
  91. from services.system.logs_service import read_logs
  92. log_file = tmp_path / "app.log"
  93. log_file.write_text("\x1b[32mINFO\x1b[0m: Test log line\n")
  94. result = read_logs([str(log_file)], max_lines=10, debug=True)
  95. assert "app.log" in result
  96. assert result["app.log"] == ["INFO: Test log line"]
  97. def test_read_logs_file_not_found(self):
  98. from services.system.logs_service import read_logs
  99. result = read_logs(["/no/such/file.log"], max_lines=10, debug=True)
  100. assert "/no/such/file.log" not in result # key is basename
  101. assert result.get("file.log") == ["Log file not found"]