from examples import get_user # test_examples.py - Hit a 3rd-party API def test_get_user(): with patch('examples.Github') as mock_github: mock_gh = mock_github.return_value get_user('foo') # call our function mock_github.assert_has_calls([ call() ]) mock_gh.assert_has_calls([ call.users.get('foo') ]) Monday, April 15, 13
fetch # test_examples.py - Side Effects def test_fetch(): config = { 'get.side_effect': Exception, 'HTTPError': Exception, } with patch('examples.requests', **config) as mock_requests: result = fetch() assert result is None mock_requests.assert_has_calls([ call.get('http://example.com') ]) Monday, April 15, 13
activities(self): """does expensive DB queries""" # ... return '' def dashboard(self): """groups user activities""" results = [] for activity in self.activities(): # do some stuff results.append(activity) return results Monday, April 15, 13
# Assume there's an ORM attached to User u = User.objects.get(username=username) # Assume the ``activities`` method returns an iterable # of Activity objects that have a ``title`` attribute. return [a.title for a in u.activities()] Monday, April 15, 13
will raise an # AttributeError if any attr is not in the spec mock_activity = Mock(spec=['title']) # provide a return value for the ``activities`` method config = {'activities.return_value': [mock_activity]} mock_user_instance = Mock(**config) # Mock User Class (via patch) config = {'objects.get.return_value': mock_user_instance} with patch('examples.User', **config) as mock_user_class: list_user_activities('xavier') mock_user_class.assert_has_calls([ call.objects.get(username='xavier') ]) mock_user_instance.assert_has_calls([ call.activities() ]) Monday, April 15, 13