File: utils.py

package info (click to toggle)
python-sparkpost 1.3.10-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 512 kB
  • sloc: python: 2,528; makefile: 31; sh: 10
file content (46 lines) | stat: -rw-r--r-- 1,719 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from __future__ import print_function
from collections import namedtuple

from responses import RequestsMock
from tornado import ioloop
from tornado.concurrent import Future
from tornado.httpclient import HTTPRequest, HTTPResponse, HTTPError

Request = namedtuple("Request", ["url", "method", "headers", "body"])


class ResponseGenerator(object):
    def get_adapter(self, url):
        return self

    def build_response(self, request, response):
        resp = HTTPResponse(request, response.status, headers=response.headers,
                            effective_url=request.url, error=None, buffer="")
        resp._body = response.data
        f = Future()
        f.content = None
        if response.status < 200 or response.status >= 300:
            resp.error = HTTPError(response.status, response=resp)
            ioloop.IOLoop().current().add_callback(f.set_exception, resp.error)
        else:
            ioloop.IOLoop().current().add_callback(f.set_result, resp)
        return f


class AsyncClientMock(RequestsMock):
    def start(self):
        from unittest import mock

        def unbound_on_send(client, request, callback=None, **kwargs):
            if not isinstance(request, HTTPRequest):
                request = Request(request,
                                  kwargs.get("method", "GET"),
                                  kwargs.get("headers", []),
                                  kwargs.get("body", ""))
            return self._on_request(ResponseGenerator(), request)
        self._patcher = mock.patch('tornado.httpclient.AsyncHTTPClient.fetch',
                                   unbound_on_send)
        self._patcher.start()

    def stop(self):
        self._patcher.stop()