Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Django User Group 21.02.2012 - Mock

1,395 views

Published on

The slides of a talk I held at the "Django User Group Meetup Berlin" on the 02-21-2012.

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

Django User Group 21.02.2012 - Mock

  1. 1. from mock import Mock mocking for python
  2. 2. Mocking >>> from mock import Mock >>> Mock() <Mock id=4419885840>Calling an undefined method on the mock returns the mock.
  3. 3. Mocking>>> m = Mock(return_value=foo)>>> m()foo Mocks can have return values.
  4. 4. Mocking>>> m(bar, answer=42)foo>>> m.calledTrue>>> m.call_argscall(bar, answer=42)>>> m.call_count1 Calls to the mock can be inspected.
  5. 5. Mocking>>> mock = Mock()>>> mock.side_effect = Exception(Bam)>>> mock()Traceback (most recent call last): ...Exception: Bam>>> mock.side_effect = [3, 2, 1]>>> mock(), mock(), mock()(3, 2, 1) Mocks can have side effects.
  6. 6. Documentationhttp://www.voidspace.org.uk/python/mock/mock.html
  7. 7. Patching>>> class Class(object):... def method(self):... pass...>>> with patch(__main__.Class) as M:... instance = M()... instance.method.return_value = foo... assert Class() is instance... assert Class().method() == foo...
  8. 8. Live example
  9. 9. Patching@patch(paperc.base.utils.mail.EmailMultiAlternatives)def test_html_parameter_is_optional(self, EmailMultiAlternatives): Omitting the html parameter should send the email with plain text only. msg = Mock() EmailMultiAlternatives.return_value = msg send_email(*[email, subject, text, {}]) self.assertEquals(msg.attach_alternative.call_count, 0)
  10. 10. mock Library Author• Michael Foord• http://www.voidspace.org.uk/python/mock/ index.html• @voidspace

×