[PYTHON] fixture of urllib.request

I've been looking for HTTPretty because it didn't work with python3.3 ```urllib.request.urlopen () `` `. There was a source that I referred to in, but I forgot somewhere ... The procedure is as follows. If you use urllib2, python2 is probably fine.

Preparation


from io import StringIO
import urllib.request as urllib2

def generate_response(req, return_data):
	resp = urllib2.addinfourl(StringIO(return_data),
								'mock header',
								req.get_full_url())
	resp.code = 200
	resp.msg = 'OK'
	return resp

expect_url = {}

def register(url, return_data):
	expect_url[url] = lambda req:generate_response(req, return_data)

def mock_response(req):
	return expect_url[req.get_full_url()](req)

class MyHTTPHandler(urllib2.HTTPHandler):
	def http_open(self, req):
		return mock_response(req)

Do this with install_opener. All you have to do now is put the URL to hack and the return value in expect_url.

Test body


from nose.tools import *

class TestUrlopen(object):
	def __init__(self):
		my_opener = urllib2.build_opener(MyHTTPHandler)
		urllib2.install_opener(my_opener)

	def test_urlopen(self):
		url = 'http://mock_server'
		register(url, "hello world")

		ret = urllib2.urlopen(url).read()
		eq_(ret, "hello world")

It's my idea to put expect_url in global and add a dynamic response, but the others are pretty much coded. Where was it ...

I haven't done it here, but if you want to return different data (with side effects) at the same URL, push with register () and pop with mock_response ().

I tried to make a class somehow. https://gist.github.com/norobust/8254063

Recommended Posts

fixture of urllib.request
urllib.request