Skip to content

Instantly share code, notes, and snippets.

@urschrei
Created March 14, 2011 10:17
Show Gist options
  • Save urschrei/868976 to your computer and use it in GitHub Desktop.
Save urschrei/868976 to your computer and use it in GitHub Desktop.
Build and install an OpenDirector instance to mock urllib2.open() http(s) calls
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
from StringIO import StringIO
def mock_response(req, resp_obj, resp_code):
""" Mock response for MyHTTPSHandler
"""
resp = urllib2.addinfourl(StringIO(resp_obj),
'This is a mocked URI!',
req.get_full_url())
resp.code = resp_code
resp.msg = "OK"
return resp
class MyHTTPSHandler(urllib2.HTTPSHandler):
""" Mock response for urllib2
takes a single argument, a string or a reference to a file
this is what's returned by .read()
"""
def __init__(self, resp_obj, resp_code = None):
self.resp_obj = resp_obj
# Use 200 if no code is passed
if not resp_code:
self.resp_code = 200
else: self.resp_code = resp_code
# Change HTTPSHandler and https_open to http for non-https calls
def https_open(self, req):
return mock_response(req, self.resp_obj, self.resp_code)
# Monkeypatch your imported module's urllib2:
import mymodule as m
opener = urllib2.build_opener(MyHTTPSHandler('foo'))
m.urllib2.install_opener(opener)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment