You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import base64
  2. import binascii
  3. import os
  4. import pytest
  5. from libs.password import compare_password, hash_password, valid_password
  6. class TestValidPassword:
  7. """Test password format validation"""
  8. def test_should_accept_valid_passwords(self):
  9. """Test accepting valid password formats"""
  10. assert valid_password("password123") == "password123"
  11. assert valid_password("test1234") == "test1234"
  12. assert valid_password("Test123456") == "Test123456"
  13. def test_should_reject_invalid_passwords(self):
  14. """Test rejecting invalid password formats"""
  15. # Too short
  16. with pytest.raises(ValueError) as exc_info:
  17. valid_password("abc123")
  18. assert "Password must contain letters and numbers" in str(exc_info.value)
  19. # No numbers
  20. with pytest.raises(ValueError):
  21. valid_password("abcdefgh")
  22. # No letters
  23. with pytest.raises(ValueError):
  24. valid_password("12345678")
  25. # Empty
  26. with pytest.raises(ValueError):
  27. valid_password("")
  28. class TestPasswordHashing:
  29. """Test password hashing and comparison"""
  30. def setup_method(self):
  31. """Setup test data"""
  32. self.password = "test123password"
  33. self.salt = os.urandom(16)
  34. self.salt_base64 = base64.b64encode(self.salt).decode()
  35. password_hash = hash_password(self.password, self.salt)
  36. self.password_hash_base64 = base64.b64encode(password_hash).decode()
  37. def test_should_verify_correct_password(self):
  38. """Test correct password verification"""
  39. result = compare_password(self.password, self.password_hash_base64, self.salt_base64)
  40. assert result is True
  41. def test_should_reject_wrong_password(self):
  42. """Test rejection of incorrect passwords"""
  43. result = compare_password("wrongpassword", self.password_hash_base64, self.salt_base64)
  44. assert result is False
  45. def test_should_handle_invalid_base64(self):
  46. """Test handling of invalid base64 data"""
  47. # Invalid base64 hash
  48. with pytest.raises(binascii.Error):
  49. compare_password(self.password, "invalid_base64!", self.salt_base64)
  50. # Invalid base64 salt
  51. with pytest.raises(binascii.Error):
  52. compare_password(self.password, self.password_hash_base64, "invalid_base64!")
  53. def test_should_be_case_sensitive(self):
  54. """Test password case sensitivity"""
  55. result = compare_password(self.password.upper(), self.password_hash_base64, self.salt_base64)
  56. assert result is False