Code effortlessly with Sourcery as your partner at every stage of the development lifecycle.
Trusted by 150,000+ developers
class User:
def __init__(self, username, email, password):
self.username = username
self._hashed_password = self._hash_password(password)
self.is_authenticated = False
def _hash_password(self, password):
return hashlib.sha256(password.encode()).hexdigest()
def authenticate(self, password):
if self._hashed_password == self._hash_password(password):
self.is_authenticated = True
class User:
def __init__(self, username, email, password):
self.username = username
self._hashed_password = self._hash_password(password)
self.is_authenticated = False
def _hash_password(self, password):
return hashlib.sha256(password.encode()).hexdigest()
def change_password(self, old_password, new_password):
if self.authenticate(old_password):
self._hashed_password = self._hash_password(new_password)
return True
return False
def logout(self):
self.is_authenticated = False
def authenticate(self, password):
if self._hashed_password == self._hash_password(password):
self.is_authenticated = True
Venturing into unfamiliar code? Sourcery is your navigator through new projects, legacy systems, or unfamiliar languages. Understand complex code instantly and get best-practice tips to sharpen your programming.
def change_password(self, old_password, new_password):
if self.authenticate(old_password):
self._hashed_password = self._hash_password(new_password)
return True
return False
def change_password(self, old_password, new_password):
"""
Changes the user's password.
Args:
old_password (str): The old password to authenticate.
new_password (str): The new password to set.
Returns:
bool: True if the password is successfully changed, False otherwise.
"""
if self.authenticate(old_password):
self._hashed_password = self._hash_password(new_password)
return True
return False
import pytest
from demo import change_password
@pytest.mark.parametrize(
"password, old_password, new_password, expected_result,
[
("password", "password", "new_password", True),
("password", "wrong_password" , "new_password", False),
...,
]
)
def test_change_password(password, old_password, new_password, expected_result):
# Arrange
user = User("username", password)
# Act
result = user.change_password(old_password, new_password)
# Assert
assert result == expected_result
Discover how Sourcery can enhance your code, offer immediate feedback, and simplify code generation.
3,000,000+
Loc removed
150,000+
Downloads
400,000+
Monthly Improvements
git commit -m “love”
Loved by developers