Skip to content

Instantly share code, notes, and snippets.

@kesor
Created August 30, 2011 00:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kesor/1179782 to your computer and use it in GitHub Desktop.
Save kesor/1179782 to your computer and use it in GitHub Desktop.
Google AppEngine URLFetch in Unit Tests
from google.appengine.api import apiproxy_stub
from google.appengine.api import apiproxy_stub_map
class FetchServiceMock(apiproxy_stub.APIProxyStub):
def __init__(self, service_name='urlfetch'):
super(FetchServiceMock, self).__init__(service_name)
def set_return_values(self, **kwargs):
self.return_values = kwargs
def _Dynamic_Fetch(self, request, response):
rv = self.return_values
response.set_content(rv.get('content', ''))
response.set_statuscode(rv.get('status_code', 500))
for header_key, header_value in rv.get('headers', {}):
new_header = response.add_header() # prototype for a header
new_header.set_key(header_key)
new_header.set_value(header_value)
response.set_finalurl(rv.get('final_url', request.url))
response.set_contentwastruncated(rv.get('content_was_truncated', False))
# allow to query the object after it is used
self.request = request
self.response = response
class TestSomeApi(unittest.TestCase):
def setUp(self):
# initialize apiproxy
self.fetch_mock = FetchServiceMock()
apiproxy_stub_map.apiproxy.RegisterStub('urlfetch', self.fetch_mock)
def test_my_method(self):
self.fetch_mock.set_return_values(
status_code=200,
content="success"
)
# call some method of the api
stuff = SomeApi().get_some_important_stuff(goody_company)
self.assertEquals("http://good.com/stuff", self.fetch_mock.request.url())
self.assertEquals("success", stuff.data)
@patkujawa-wf
Copy link

Mocking AppEngine's urlfetch service in your unittest | Jeff's Ramblings is very much like this, but some commenters have added fixes and improvements.

@lastorset
Copy link

I forked it and turned it into a context manager.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment