Created
February 24, 2015 12:02
-
-
Save blaix/b32554eae8ba563b3a32 to your computer and use it in GitHub Desktop.
Unit vs Integration testing in python using mocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# consider this simple password hasher (over-simplified of course): | |
def password_hash(self, salt, password): | |
return (salt + password).reverse | |
# the unit tests are simple input vs output style: | |
def test_password_hash_returns_reverse_concatenated_salt_and_password(self): | |
hashed = password_hash('foo', 'bar') | |
self.assertEqual(hashed, 'raboof') | |
# now consider this more complicated example that interacts with user objects and hasing functions: | |
class UserPasswordHasher: | |
def __init__(self, user, hasher=sha123): | |
self.user = user | |
self.hasher = hasher | |
def salted_hash(self, password): | |
return self.hasher(self.user.email + password) | |
# the unit tests verify interaction with other units using mock objects: | |
# (Mock()s are special objects that let you fake and verify attributes/calls) | |
class TestUserPasswordHasher(TestCase): | |
def setUp(self): | |
fake_user = Mock(email='[email protected]') | |
self.fake_hasher = Mock() | |
user_password_hasher = UserPasswordHasher(fake_user, self.fake_hasher) | |
self.salted_hash = user_password_hasher.salted_hash('password') | |
def test_salted_hash_returns_results_of_hasher(self): | |
self.assertEqual(self.salted_hash, self.fake_hasher.return_value) | |
def test_salted_hash_salts_password_with_user_email(self): | |
self.fake_hasher.assert_called_with('[email protected]') | |
# the integration tests verify the behavior when the real units are interacting with each other: | |
class TestUserPasswordHasher(TestCase): | |
def test_returns_same_hash_for_same_user_and_password(self): | |
user = User() | |
hash1 = UserPasswordHasher(user).salted_hash('password') | |
hash2 = UserPasswordHasher(user).salted_hash('password') | |
self.assertEqual(hash1, hash2) | |
def test_returns_different_hash_for_same_user_with_different_passwords(self): | |
user = User() | |
hash1 = UserPasswordHasher(user).salted_hash('password1') | |
hash2 = UserPasswordHasher(user).salted_hash('password2') | |
self.assertNotEqual(hash1, hash2) | |
def test_returns_different_hash_for_different_user_with_same_passwords(self): | |
user1 = User(email='[email protected]') | |
user2 = User(email='[email protected]') | |
hash1 = UserPasswordHasher(user1).salted_hash('password') | |
hash2 = UserPasswordHasher(user2).salted_hash('password') | |
self.assertNotEqual(hash1, hash2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment