Created
July 29, 2014 18:50
-
-
Save arnaldopereira/aba525f976cb91e8a2b9 to your computer and use it in GitHub Desktop.
mock AsyncHTTPClient.fetch - generator
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 | |
from tornado import gen | |
from tornado.ioloop import IOLoop | |
from tornado.concurrent import Future | |
from tornado.httpclient import AsyncHTTPClient | |
from tornado.httpclient import HTTPRequest | |
from tornado.httpclient import HTTPResponse | |
import mock | |
import StringIO | |
def setup_fetch(fetch_mock, status_code, body=None): | |
def side_effect(request, **kwargs): | |
if request is not HTTPRequest: | |
request = HTTPRequest(request) | |
buffer = StringIO.StringIO(body) | |
response = HTTPResponse(request, status_code, None, buffer) | |
future = Future() | |
future.set_result(response) | |
return future | |
fetch_mock.side_effect = side_effect | |
@gen.coroutine | |
def main(): | |
client = AsyncHTTPClient() | |
with mock.patch.object(client, 'fetch') as fetch_mock: | |
setup_fetch(fetch_mock, 200, 'hello') | |
response = yield client.fetch('http://google.com') | |
print response.body | |
IOLoop.instance().run_sync(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment