Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Testing with unittest.mock

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

Testing with unittest.mock

Avatar for Ana Yankova

Ana Yankova

May 20, 2014
Tweet

More Decks by Ana Yankova

Other Decks in Programming

Transcript

  1. >>> comment.create = Mock(return_value=True) >>> comment.create(text=‘hello') True >>> comment.create. \

    ... assert_called_once_with(text=‘hello’) >>> comment.create.called True >>> comment.create.call_args call(text='hello') >>> comment.call_count 1
  2. >>> mock = Mock() >>> mock <Mock id='4353021072'> >>> mock.method

    <Mock name='mock.method' id=‘4352854800'> >>> mock.assetr_called_with(keyword=None)
  3. ... AttributeError: Mock object has no attribute 'remove' >>> comment.remove

    >>> from unittest.mock import create_autospec >>> >>> comment = create_autospec(Comment)
  4. >>> comment.create.side_effect = \ ... ConnectionError(“Connection refused”) >>> ... ConnectionError:

    Connection refused >>> comment.create.mock_calls [call(parent=None, text='Hello')] >>> >>> comment.create(text="Hello", parent=None)
  5. >>> mock = MagicMock() >>> int(mock) 1 >>> len(mock) 0

    >>> list(mock) [] >>> mock.__int__.called True
  6. #event.py from datetime import date ! class Event(): ! def

    get_state(self): if self.end_date < date.today(): return "PAST" if self.start_date > date.today(): return "FUTURE" if self.start_date <= date.today() <= self.end_date: return "CURRENT"
  7. #test.py from datetime import date ! class EventTests(TestCase): def setUp(self):

    self.pycon = Event() self.pycon.start_date = date(2014, 5, 20) self.pycon.end_date = date(2014, 5, 21) ! @patch('event.date') def test_event_has_passed(self, mock_date): mock_date.today.return_value = date(2014, 5, 22) assert self.pycon.get_state() == "PAST"
  8. class UserProfileSaveTests(TestCase): ! def setUp(self): self.profile = UserProfileFactory.build(user=UserFactory()) ! !

    @patch("notifications.tasks.subscribe_to_newsletter.delay") def test_subscribe_to_newsletter(self, subscribe_mock): self.profile.newsletter = True self.profile.save() subscribe_mock.assert_called_once_with(self.profile.user)