| 1 |
from __future__ import print_function |
| 2 |
from collections import namedtuple |
| 3 |
|
| 4 |
from responses import RequestsMock |
| 5 |
from tornado import ioloop |
| 6 |
from tornado.concurrent import Future |
| 7 |
from tornado.httpclient import HTTPRequest, HTTPResponse, HTTPError |
| 8 |
|
| 9 |
Request = namedtuple("Request", ["url", "method", "headers", "body"]) |
| 10 |
|
| 11 |
|
| 12 |
class ResponseGenerator(object): |
| 13 |
def get_adapter(self, url): |
| 14 |
return self |
| 15 |
|
| 16 |
def build_response(self, request, response): |
| 17 |
resp = HTTPResponse(request, response.status, headers=response.headers, |
| 18 |
effective_url=request.url, error=None, buffer="") |
| 19 |
resp._body = response.data |
| 20 |
f = Future() |
| 21 |
f.content = None |
| 22 |
if response.status < 200 or response.status >= 300: |
| 23 |
resp.error = HTTPError(response.status, response=resp) |
| 24 |
ioloop.IOLoop().current().add_callback(f.set_exception, resp.error) |
| 25 |
else: |
| 26 |
ioloop.IOLoop().current().add_callback(f.set_result, resp) |
| 27 |
return f |
| 28 |
|
| 29 |
|
| 30 |
class AsyncClientMock(RequestsMock): |
| 31 |
def start(self): |
| •32 |
from unittest import mock |
| 33 |
|
| 34 |
def unbound_on_send(client, request, callback=None, **kwargs): |
| 35 |
if not isinstance(request, HTTPRequest): |
| 36 |
request = Request(request, |
| 37 |
kwargs.get("method", "GET"), |
| 38 |
kwargs.get("headers", []), |
| 39 |
kwargs.get("body", "")) |
| 40 |
return self._on_request(ResponseGenerator(), request) |
| 41 |
self._patcher = mock.patch('tornado.httpclient.AsyncHTTPClient.fetch', |
| 42 |
unbound_on_send) |
| 43 |
self._patcher.start() |
| 44 |
|
| 45 |
def stop(self): |
| 46 |
self._patcher.stop() |