Skip to content

Instantly share code, notes, and snippets.

@rchacon
Last active February 9, 2016 23:50
Show Gist options
  • Save rchacon/8000e19bb0fbfb1a9e69 to your computer and use it in GitHub Desktop.
Save rchacon/8000e19bb0fbfb1a9e69 to your computer and use it in GitHub Desktop.
Dependency Injection and Partial Mocking
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()
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