Created
March 14, 2011 10:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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