Exemplo n.º 1
0
    async def test_create_http_json_response(self, query_with_answer):
        headers = Headers()
        headers.add(key="accept", value=DOH_CONTENT_TYPE)
        request = Request(
            headers=headers,
            method="GET",
            scheme="https",
            path="/dns-query",
            http_version="1.1",
            query_string=
            b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAAAgACAAEAAEAAA",
            root_path="",
            send_push_promise=None,
        )
        result = await create_http_json_response(request, query_with_answer)
        assert result.status_code == 200
        assert result.headers.get("content-length") == "2"
        assert result.headers.get("content-type") == DOH_JSON_CONTENT_TYPE
        assert await result.get_data() == b"{}"

        result = await create_http_json_response(request, "query_with_answer")
        assert result.status_code == 200
        assert result.headers.get("content-length") == "32"
        assert result.headers.get("content-type") == "text/html; charset=utf-8"
        assert await result.get_data() == b'{"content": "query_with_answer"}'
Exemplo n.º 2
0
def test_headers_bytes() -> None:
    headers = Headers()
    headers[b'X-Foo'] = b'something'
    headers.add(b'X-Bar', b'something')
    headers.setdefault(b'X-Bob', 'something')

    assert headers['x-foo'] == 'something'
    assert headers['x-bar'] == 'something'
    assert headers['x-bob'] == 'something'
    headers.add('X-Foo', 'different')
    assert headers.getlist('X-Foo') == ['something', 'different']
Exemplo n.º 3
0
def test_headers_bytes() -> None:
    headers = Headers()
    headers[b"X-Foo"] = b"something"
    headers.add(b"X-Bar", b"something")
    headers.setdefault(b"X-Bob", "something")

    assert headers["x-foo"] == "something"
    assert headers["x-bar"] == "something"
    assert headers["x-bob"] == "something"
    headers.add("X-Foo", "different")
    assert headers.getlist("X-Foo") == ["something", "different"]
Exemplo n.º 4
0
async def test_websocket_accept_connection_warns() -> None:
    connection = ASGIWebsocketConnection(Quart(__name__), {})

    async def mock_send(message: dict) -> None:
        pass

    with pytest.warns(None):
        await connection.accept_connection(mock_send, Headers({"a": "b"}), None)
Exemplo n.º 5
0
def test_headers_add_kwargs() -> None:
    headers = Headers()
    headers.add("Content-Disposition", "attachment", filename="abc")
    assert headers["content-disposition"] == "attachment; filename=abc"
Exemplo n.º 6
0
def test_headers_non_strings() -> None:
    headers = Headers()
    headers['X-Foo'] = 12
    headers['X-Bar'] = True
    assert headers['x-foo'] == '12'
    assert headers['x-bar'] == 'True'
Exemplo n.º 7
0
def test__encode_headers() -> None:
    assert _encode_headers(Headers({"Foo": "Bar"})) == [(b"foo", b"Bar")]
Exemplo n.º 8
0
        'scheme': 'wss',
        'path': 'ws://quart/path',
        'query_string': b'',
        'subprotocols': [],
        'extensions': {'websocket.http.response': {}},
    }
    connection = ASGIWebsocketConnection(app, scope)
    websocket = connection._create_websocket_from_scope(lambda: None)
    assert websocket.path == '/path'


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "scope, headers, subprotocol, has_headers",
    [
        ({}, Headers(), None, False),
        ({}, Headers(), "abc", False),
        ({"asgi": {"spec_version": "2.1"}}, Headers({"a": "b"}), None, True),
        ({"asgi": {"spec_version": "2.1.1"}}, Headers({"a": "b"}), None, True),
    ],
)
async def test_websocket_accept_connection(
        scope: dict, headers: Headers, subprotocol: Optional[str], has_headers: bool,
) -> None:
    connection = ASGIWebsocketConnection(Quart(__name__), scope)
    mock_send = CoroutineMock()
    await connection.accept_connection(mock_send, headers, subprotocol)

    if has_headers:
        mock_send.assert_called_with({
            "subprotocol": subprotocol,
Exemplo n.º 9
0
        "query_string": b"",
        "subprotocols": [],
        "extensions": {
            "websocket.http.response": {}
        },
    }
    connection = ASGIWebsocketConnection(app, scope)
    websocket = connection._create_websocket_from_scope(lambda: None)
    assert websocket.path == "/path"


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "scope, headers, subprotocol, has_headers",
    [
        ({}, Headers(), None, False),
        ({}, Headers(), "abc", False),
        ({
            "asgi": {
                "spec_version": "2.1"
            }
        }, Headers({"a": "b"}), None, True),
        ({
            "asgi": {
                "spec_version": "2.1.1"
            }
        }, Headers({"a": "b"}), None, True),
    ],
)
async def test_websocket_accept_connection(scope: dict, headers: Headers,
                                           subprotocol: Optional[str],
Exemplo n.º 10
0
def test_headers_non_strings() -> None:
    headers = Headers()
    headers["X-Foo"] = 12
    headers["X-Bar"] = True
    assert headers["x-foo"] == "12"
    assert headers["x-bar"] == "True"
Exemplo n.º 11
0
    async def handle_error(self, e):
        """
        Error handler for the API transforms a raised exception into a Quart response,
        with the appropriate HTTP status code and body.

        :param Exception e: the raised Exception object

        """
        await got_request_exception.send(current_app._get_current_object(),
                                         exception=e)

        include_message_in_response = current_app.config.get(
            'ERROR_INCLUDE_MESSAGE', True)
        default_data = {}

        headers = Headers()

        for typecheck, handler in self._own_and_child_error_handlers.items():
            if isinstance(e, typecheck):
                result = handler(e)
                default_data, code, headers = unpack(
                    result, HTTPStatus.INTERNAL_SERVER_ERROR)
                break
        else:
            if isinstance(e, HTTPException):
                code = HTTPStatus(e.status_code)
                if include_message_in_response:
                    default_data = {
                        'message': getattr(e, 'description', code.phrase)
                    }
                headers.update(e.get_headers())
            elif self._default_error_handler:
                result = self._default_error_handler(e)
                default_data, code, headers = unpack(
                    result, HTTPStatus.INTERNAL_SERVER_ERROR)
            else:
                code = HTTPStatus.INTERNAL_SERVER_ERROR
                if include_message_in_response:
                    default_data = {
                        'message': code.phrase,
                    }

        if include_message_in_response:
            default_data['message'] = default_data.get('message', str(e))

        data = getattr(e, 'data', default_data)
        supported_mediatypes = list(self.representations.keys())
        fallback_mediatype = supported_mediatypes[
            0] if supported_mediatypes else 'text/plain'

        if code >= HTTPStatus.INTERNAL_SERVER_ERROR:
            exc_info = sys.exc_info()
            if exc_info[1] is None:
                exc_info = None
            current_app.log_exception(exc_info)
        elif (code == HTTPStatus.NOT_FOUND
              and current_app.config.get('ERROR_404_HELP', True)
              and include_message_in_response):
            data['message'] = self._help_on_404(data.get('message', None))

        # Remove blacklisted headers
        for header in HEADERS_BLACKLIST:
            headers.pop(header, None)

        resp = await self.make_response(data,
                                        code,
                                        headers,
                                        fallback_mediatype=fallback_mediatype)

        if code == HTTPStatus.UNAUTHORIZED:
            resp = self.unauthorized(resp)
        return resp
Exemplo n.º 12
0
    async def test_get_name_and_type_from_dns_question(self):
        headers = Headers()
        headers.add(key="accept", value=DOH_CONTENT_TYPE)
        request = Request(
            headers=headers,
            method="GET",
            scheme="https",
            path="/dns-query",
            http_version="1.1",
            query_string=
            b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAAAgACAAEAAEAAA",
            root_path="",
            send_push_promise=None,
        )
        result = await get_name_and_type_from_dns_question(request)
        assert str(result.question[0]) == "s0.wp.com. IN AAAA"

        headers = Headers()
        headers.add(key="accept", value=DOH_JSON_CONTENT_TYPE)
        request = Request(
            headers=headers,
            method="GET",
            scheme="https",
            path="/dns-query",
            http_version="1.1",
            query_string=b"name=example.com&type=A",
            root_path="",
            send_push_promise=None,
        )
        result = await get_name_and_type_from_dns_question(request)
        assert str(result.question[0]) == "example.com. IN A"

        headers = Headers()
        headers.add(key="content-type", value=DOH_CONTENT_TYPE)
        request = Request(
            headers=headers,
            method="POST",
            scheme="https",
            path="/dns-query",
            http_version="1.1",
            query_string=
            b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAAAgACAAEAAEAAA",
            root_path="",
            send_push_promise=None,
        )
        request.body = return_body()
        result = await get_name_and_type_from_dns_question(request)
        assert result is None

        request = Request(
            headers=headers,
            method="GET",
            scheme="https",
            path="/dns-query",
            http_version="1.1",
            query_string=
            b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAgACAAEAAEAAA",
            root_path="",
            send_push_promise=None,
        )
        result = await get_name_and_type_from_dns_question(request)
        assert result is None