Skip to content

Instantly share code, notes, and snippets.

@SeanHayes
Created November 28, 2012 06:16
Show Gist options
  • Save SeanHayes/4159361 to your computer and use it in GitHub Desktop.
Save SeanHayes/4159361 to your computer and use it in GitHub Desktop.
Mock example usage
def mocked_urlopen_side_effect(url, *args, **kwargs):
"Returns string content in a file-like interface for a variety of possible URLs."
#StringIO is a file-like object, much like we'd expect urlopen to return
#responses is a dict (defined elsewhere) containing various string responses as the values for the keys.
if 'http://search.twitter.com/search.json' in url:
return StringIO(responses['twitter_success_1'])
elif 'http://api.twitter.com/1/geo/search.json' in url:
return StringIO(responses['twitter_geo_success_1'])
elif 'http://api.flickr.com/services/rest/' in url:
return StringIO(responses['flickr_success_1'])
elif 'https://api.instagram.com/v1/media/search' in url or 'https://api.instagram.com/v1/tags/' in url:
return StringIO(responses['instagram_success_1'])
elif 'http://maps.googleapis.com/maps/api/geocode/json' in url:
return StringIO(responses['google_maps'])
raise Exception('URL unsupported by mocked function.')
def test():
with mock.patch('urllib2.urlopen') as mocked_urlopen:
mocked_urlopen.side_effect = mocked_urlopen_side_effect
#call some code that makes a request using urllib2.urlopen
import_social_media_data()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment