Last active
February 9, 2016 23:50
-
-
Save rchacon/8000e19bb0fbfb1a9e69 to your computer and use it in GitHub Desktop.
Dependency Injection and Partial Mocking
This file contains 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
class XmasTest(unittest.TestCase): | |
@mock.patch('xmas.date') | |
def test_days_til_xmas_when_xmas(self, mock_date): | |
mock_date.today.return_value = date(2020, 12, 25) | |
mock_date.side_effect = lambda *args, **kw: date(*args, **kw) | |
days = days_til_xmas() | |
self.assertEqual(days, 0) | |
@mock.patch('xmas.date') | |
def test_days_til_xmas(self, mock_date): | |
mock_date.today.return_value = date(2020, 10, 12) | |
mock_date.side_effect = lambda *args, **kw: date(*args, **kw) | |
days = days_til_xmas() | |
self.assertEqual(days, 74) | |
@mock.patch('xmas.date') | |
def test_days_til_xmas_when_xmas_passed(self, mock_date): | |
mock_date.today.return_value = date(2020, 12, 26) | |
mock_date.side_effect = lambda *args, **kw: date(*args, **kw) | |
days = days_til_xmas() | |
self.assertEqual(days, 364) | |
def test_days_til_xmas_di_when_xmas(self): | |
from_date = date(2020, 12, 25) | |
days = days_til_xmas_di(from_date) | |
self.assertEqual(days, 0) | |
def test_days_til_xmas_di(self): | |
from_date = date(2020, 10, 12) | |
days = days_til_xmas_di(from_date) | |
self.assertEqual(days, 74) | |
def test_days_til_xmas_di_when_xmas_passed(self): | |
from_date = date(2020, 12, 26) | |
days = days_til_xmas_di(from_date) | |
self.assertEqual(days, 364) | |
if __name__ == '__main__': | |
unittest.main() |
This file contains 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
from datetime import date | |
from dateutil.relativedelta import relativedelta | |
def days_til_xmas(): | |
"""Returns number of days until xmas. | |
Doesn't use dependency injection. | |
""" | |
from_date = date.today() | |
xmas = date(from_date.year, 12, 25) | |
diff = (xmas - from_date).days | |
if diff >= 0: | |
return diff | |
xmas += relativedelta(years=1) | |
return (xmas - from_date).days | |
def days_til_xmas_di(from_date): | |
"""Returns number of days until xmas. | |
Uses dependency injection. | |
""" | |
xmas = date(from_date.year, 12, 25) | |
diff = (xmas - from_date).days | |
if diff >= 0: | |
return diff | |
xmas += relativedelta(years=1) | |
return (xmas - from_date).days |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment