Skip to content

Instantly share code, notes, and snippets.

@bradmontgomery
Last active January 15, 2018 03:47
Show Gist options
  • Save bradmontgomery/5390439 to your computer and use it in GitHub Desktop.
Save bradmontgomery/5390439 to your computer and use it in GitHub Desktop.
Sample code illustrating some uses of Mock; These tests will pass if you have nose, but the code doesn't really do anything.
import requests
from pygithub3 import Github
# Example: Hit a 3rd-party API
# ----------------------------
def get_user(username):
gh = Github()
return gh.users.get(username)
# Example: Side Effects
# ---------------------
def fetch():
"""Asumme you're hitting some API."""
try:
response = requests.get('http://example.com')
return response.content
except requests.HTTPError:
return None
# Example: "expensive" calls
# --------------------------
class User(object):
def 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
# Example: Lots of Setup
# ----------------------
def list_user_activities(username):
# 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()]
from mock import call, patch, Mock
from examples import fetch, get_user, list_user_activities, User
# Example: 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')
])
# Example: 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')
])
# Example: "expensive" calls
# --------------------------
def test_user_dashboard():
u = User()
u.activities = Mock(return_value=['blah'])
result = u.dashboard()
assert result == ['blah']
assert u.activities.called
# Example: Lots of Setup
# ----------------------
def test_list_user_activities():
# Mock an activity object; If you attempt to access an attribute that's
# not in the spec, this Mock will raise an AttributeError.
mock_activity = Mock(spec=['title'])
# Mock User instance; 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()
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment