Ejemplo n.º 1
0
async def test_send_data(port, http_request):
    async with TrioRequestsTransport() as transport:
        req = http_request('PUT',
                           'http://localhost:{}/basic/anything'.format(port),
                           data=b"azerty")
        response = await transport.send(req)
        if is_rest(http_request):
            assert is_rest(response)
        assert json.loads(response.text())['data'] == "azerty"
def test_repr(http_response):
    res = _create_aiohttp_response(http_response, b'\xef\xbb\xbf56', {})
    res.content_type = "text/plain"

    class_name = "AsyncHttpResponse" if is_rest(
        http_response) else "AioHttpTransportResponse"
    assert repr(res) == f"<{class_name}: 200 OK, Content-Type: text/plain>"
def test_repr(http_response):
    res = _create_requests_response(http_response, b'\xef\xbb\xbf56',
                                    {'Content-Type': 'text/plain'})
    class_name = "HttpResponse" if is_rest(
        http_response) else "RequestsTransportResponse"
    assert repr(res) == "<{}: 200 OK, Content-Type: text/plain>".format(
        class_name)
        def on_request(self, request):
            assert is_rest(request.http_request)
            assert request.http_request.content == '{"hello": "world"}'

            # modify header to know we entered this callback
            request.http_request.headers = {
                "x-ms-date": "Thu, 14 Jun 2018 16:46:54 GMT",
                "Authorization": "SharedKey account:G4jjBXA7LI/RnWKIOQ8i9xH4p76pAQ+4Fs4R1VxasaE=",
                "Content-Length": "0",
            }
Ejemplo n.º 5
0
def create_transport_response(http_response, *args, **kwargs):
    # this creates transport-specific responses,
    # like requests responses / aiohttp responses
    if is_rest(http_response):
        block_size = args[2] if len(args) > 2 else None
        return http_response(request=args[0],
                             internal_response=args[1],
                             block_size=block_size,
                             **kwargs)
    return http_response(*args, **kwargs)
async def test_aiohttp_response_text(http_response):

    for encoding in ["utf-8", "utf-8-sig", None]:

        res = _create_aiohttp_response(http_response, b'\xef\xbb\xbf56',
                                       {'Content-Type': 'text/plain'})
        if is_rest(http_response):
            await res.read()
        assert res.text(encoding) == '56', "Encoding {} didn't work".format(
            encoding)
    def mock_send(http_request, http_response, method, status, headers=None, body=RESPONSE_BODY):
        if headers is None:
            headers = {}
        response = Response()
        response._content_consumed = True
        response._content = json.dumps(body).encode('ascii') if body is not None else None
        response.request = Request()
        response.request.method = method
        response.request.url = RESOURCE_URL
        response.request.headers = {
            'x-ms-client-request-id': '67f4dd4e-6262-45e1-8bed-5c45cf23b6d9'
        }
        response.status_code = status
        response.headers = headers
        response.headers.update({"content-type": "application/json; charset=utf8"})
        response.reason = "OK"

        if is_rest(http_request):
            request = http_request(
                response.request.method,
                response.request.url,
                headers=response.request.headers,
                content=body,
            )
        else:
            request = CLIENT._request(
                response.request.method,
                response.request.url,
                None,  # params
                response.request.headers,
                body,
                None,  # form_content
                None  # stream_content
            )
        response = create_transport_response(http_response, request, response)
        if is_rest(http_response):
            response.body()
        return PipelineResponse(
            request,
            response,
            None  # context
        )
 def on_request(self, request):
     assert is_rest(request.http_request)
     # don't want to deal with content in serialize, so let's first just remove it
     request.http_request.data = None
     expected = (
         b'DELETE http://localhost:5000/container0/blob0 HTTP/1.1\r\n'
         b'x-ms-date: Thu, 14 Jun 2018 16:46:54 GMT\r\n'
         b'Authorization: SharedKey account:G4jjBXA7LI/RnWKIOQ8i9xH4p76pAQ+4Fs4R1VxasaE=\r\n'  # fake key suppressed in credscan
         b'Content-Length: 0\r\n'
         b'\r\n')
     assert request.http_request.serialize() == expected
     raise ValueError("Passed through the policies!")
Ejemplo n.º 9
0
async def test_async_gen_data(port, http_request):
    class AsyncGen:
        def __init__(self):
            self._range = iter([b"azerty"])

        def __aiter__(self):
            return self

        async def __anext__(self):
            try:
                return next(self._range)
            except StopIteration:
                raise StopAsyncIteration

    async with TrioRequestsTransport() as transport:
        req = http_request('GET',
                           'http://localhost:{}/basic/anything'.format(port),
                           data=AsyncGen())
        response = await transport.send(req)
        if is_rest(http_request):
            assert is_rest(response)
        assert json.loads(response.text())['data'] == "azerty"
    def mock_update(http_request, http_response, url, headers=None):
        response = Response()
        response._content_consumed = True
        response.request = mock.create_autospec(Request)
        response.request.method = 'GET'
        response.headers = headers or {}
        response.headers.update({"content-type": "application/json; charset=utf8"})
        response.reason = "OK"

        if url == ASYNC_URL:
            response.request.url = url
            response.status_code = POLLING_STATUS
            response._content = ASYNC_BODY.encode('ascii')
            response.randomFieldFromPollAsyncOpHeader = None

        elif url == LOCATION_URL:
            response.request.url = url
            response.status_code = POLLING_STATUS
            response._content = LOCATION_BODY.encode('ascii')
            response.randomFieldFromPollLocationHeader = None

        elif url == ERROR:
            raise BadEndpointError("boom")

        elif url == RESOURCE_URL:
            response.request.url = url
            response.status_code = POLLING_STATUS
            response._content = RESOURCE_BODY.encode('ascii')

        else:
            raise Exception('URL does not match')

        request = http_request(
            response.request.method,
            response.request.url,
        )

        response = create_transport_response(http_response, request, response)
        if is_rest(http_response):
            response.body()

        return PipelineResponse(
            request,
            response,
            None  # context
        )
Ejemplo n.º 11
0
def create_http_response(http_response, *args, **kwargs):
    # since the actual http_response object is
    # an ABC for our new responses, it's a little more
    # complicated creating a pure http response.
    # here, we use the HttpResponsImpl, but we still have to pass
    # more things to the init, so making a separate operation
    if is_rest(http_response):
        block_size = args[2] if len(args) > 2 else None
        return http_response(request=args[0],
                             internal_response=args[1],
                             block_size=block_size,
                             status_code=kwargs.pop("status_code", 200),
                             reason=kwargs.pop("reason", "OK"),
                             content_type=kwargs.pop("content_type",
                                                     "application/json"),
                             headers=kwargs.pop("headers", {}),
                             stream_download_generator=kwargs.pop(
                                 "stream_download_generator", None),
                             **kwargs)
    return http_response(*args, **kwargs)
def test_http_client_response(port, http_request, http_response):
    # Create a core request
    request = http_request("GET", "http://localhost:{}".format(port))

    # Fake a transport based on http.client
    conn = HTTPConnection("localhost", port)
    conn.request("GET", "/get")
    r1 = conn.getresponse()

    response = create_transport_response(http_response, request, r1)
    if is_rest(http_response):
        response.read()

    # Don't assume too much in those assert, since we reach a real server
    assert response.internal_response is r1
    assert response.reason is not None
    assert isinstance(response.status_code, int)
    assert len(response.headers.keys()) != 0
    assert len(response.text()) != 0
    assert "content-type" in response.headers
    assert "Content-Type" in response.headers
Ejemplo n.º 13
0
    def build_response(body, content_type=None):
        if is_rest(http_response):

            class MockResponse(http_response):
                def __init__(self, body, content_type):
                    super(MockResponse, self).__init__(
                        request=None,
                        internal_response=None,
                        status_code=400,
                        reason="Bad Request",
                        content_type="application/json",
                        headers={},
                        stream_download_generator=None,
                    )
                    self._body = body
                    self.content_type = content_type

                def body(self):
                    return self._body

                def read(self):
                    self._content = self._body
                    return self.content

        else:

            class MockResponse(http_response):
                def __init__(self, body, content_type):
                    super(MockResponse, self).__init__(None, None)
                    self._body = body
                    self.content_type = content_type

                def body(self):
                    return self._body

        return PipelineResponse(request, MockResponse(body, content_type),
                                context)
 def callback(request):
     assert is_rest(request.http_request)
     raise ValueError("I entered the callback!")
 def on_request(self, pipeline_request):
     request = pipeline_request.http_request
     assert is_rest(request)
     assert request.body == '{"hello": "world"}'  # old request has property body
     request.set_text_body("change to me!")
     return pipeline_request
 def on_request(self, request):
     assert is_rest(request.http_request) # first make sure this is a new request
     # deals with request like an old request
     request.http_request.set_json_body({"hello": "world"})
 def on_request(self, pipeline_request):
     request = pipeline_request.http_request
     assert is_rest(request)
     assert request.content == 'change to me!'  # new request has property content
     raise ValueError("I entered the policies!")