test_services.py 4.8 KB

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