def test_assign_nonstr_text(self):
        resp = Response(text="test")

        with self.assertRaises(TypeError):
            resp.text = b"123"
        self.assertEqual(b"test", resp.body)
        self.assertEqual(4, resp.content_length)
def test_delete_content_length_if_compression_enabled():
    req = make_request('GET', '/')
    resp = Response(body=b'answer')
    resp.enable_compression(ContentCoding.gzip)

    yield from resp.prepare(req)
    assert resp.content_length is None
Beispiel #3
0
async def test_content_length_on_chunked():
    req = make_request('GET', '/')
    resp = Response(body=b'answer')
    assert resp.content_length == 6
    resp.enable_chunked_encoding()
    assert resp.content_length is None
    await resp.prepare(req)
Beispiel #4
0
def test_assign_nonstr_text():
    resp = Response(text='test')

    with pytest.raises(TypeError):
        resp.text = b'123'
    assert b'test' == resp.body
    assert 4 == resp.content_length
Beispiel #5
0
def test_assign_nonbyteish_body():
    resp = Response(body=b'data')

    with pytest.raises(TypeError):
        resp.body = 123
    assert b'data' == resp.body
    assert 4 == resp.content_length
    def test_assign_nonbyteish_body(self):
        resp = Response(body=b'data')

        with self.assertRaises(TypeError):
            resp.body = 123
        self.assertEqual(b'data', resp.body)
        self.assertEqual(4, resp.content_length)
Beispiel #7
0
    def make_response(self, request, response):
        """Convert a handler result to web response."""
        while iscoroutine(response):
            response = yield from response

        if isinstance(response, StreamResponse):
            return response

        if isinstance(response, str):
            return Response(text=response, content_type='text/html')

        if isinstance(response, (list, dict)):
            return Response(text=json.dumps(response), content_type='application/json')

        if isinstance(response, (MultiDict, MultiDictProxy)):
            response = dict(response)
            return Response(text=json.dumps(response), content_type='application/json')

        if isinstance(response, bytes):
            response = Response(body=response, content_type='text/html')
            response.charset = self.app.cfg.ENCODING
            return response

        if response is None:
            response = ''

        return Response(text=str(response), content_type='text/html')
    def test_assign_nonstr_text(self):
        resp = Response(text='test')

        with self.assertRaises(TypeError):
            resp.text = b'123'
        self.assertEqual(b'test', resp.body)
        self.assertEqual(4, resp.content_length)
Beispiel #9
0
 def options(self, request, *args, **kwargs):
     """
     Handles responding to requests for the OPTIONS HTTP verb.
     """
     response = Response(status=204, text='')
     response.headers['Allow'] = ', '.join(self._allowed_methods())
     return response
Beispiel #10
0
        def ensure_response(request):

            rv = yield from self._provider.local_dispatcher(request)

            status_or_headers = headers = None
            if isinstance(rv, tuple):
                rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))

            if rv is None:
                raise HTTPInternalServerError()

            if isinstance(status_or_headers, (list, dict)):
                headers, status_or_headers = status_or_headers, None

            if not isinstance(rv, Response):

                data = rv

                rv = Response(headers=headers, status=status_or_headers or 200,
                              content_type='application/json')

                rv.text = json_serializer(data)
                headers = status_or_headers = None

            if status_or_headers is not None:
                if isinstance(status_or_headers, int):
                    rv.status = status_or_headers

            if headers:
                rv.headers.extend(headers)

            return rv
Beispiel #11
0
async def test_change_content_length_if_compression_enabled():
    req = make_request('GET', '/')
    resp = Response(body=b'answer')
    resp.enable_compression(ContentCoding.gzip)

    await resp.prepare(req)
    assert resp.content_length is not None and \
        resp.content_length != len(b'answer')
Beispiel #12
0
def test_set_text_with_content_type():
    resp = Response()
    resp.content_type = "text/html"
    resp.text = "text"

    assert "text" == resp.text
    assert b"text" == resp.body
    assert "text/html" == resp.content_type
Beispiel #13
0
    def test_set_text_with_content_type(self):
        resp = Response()
        resp.content_type = "text/html"
        resp.text = "text"

        self.assertEqual("text", resp.text)
        self.assertEqual(b"text", resp.body)
        self.assertEqual("text/html", resp.content_type)
Beispiel #14
0
    def test_assign_nonbyteish_body(self):
        req = self.make_request('GET', '/')
        resp = Response(req, b'data')

        with self.assertRaises(TypeError):
            resp.body = 123
        self.assertEqual(b'data', resp.body)
        self.assertEqual(4, resp.content_length)
Beispiel #15
0
    def test_set_text_with_charset(self):
        resp = Response()
        resp.content_type = 'text/plain'
        resp.charset = "KOI8-R"
        resp.text = "текст"

        self.assertEqual("текст", resp.text)
        self.assertEqual("текст".encode('koi8-r'), resp.body)
        self.assertEqual("koi8-r", resp.charset)
Beispiel #16
0
    def test_delete_content_length_if_compression_enabled(self, ResponseImpl):
        req = self.make_request('GET', '/')
        resp = Response(body=b'answer')
        self.assertEqual(6, resp.content_length)

        resp.enable_compression(ContentCoding.gzip)

        resp.start(req)
        self.assertIsNone(resp.content_length)
    def test_delete_content_length_if_compression_enabled(self, ResponseImpl):
        req = self.make_request("GET", "/")
        resp = Response(body=b"answer")
        self.assertEqual(6, resp.content_length)

        resp.enable_compression(ContentCoding.gzip)

        self.loop.run_until_complete(resp.prepare(req))
        self.assertIsNone(resp.content_length)
Beispiel #18
0
def test_set_text_with_charset():
    resp = Response()
    resp.content_type = 'text/plain'
    resp.charset = "KOI8-R"
    resp.text = "текст"

    assert "текст" == resp.text
    assert "текст".encode('koi8-r') == resp.body
    assert "koi8-r" == resp.charset
Beispiel #19
0
def test_delete_content_length_if_compression_enabled():
    req = make_request('GET', '/')
    resp = Response(body=b'answer')
    resp.enable_compression(ContentCoding.gzip)

    with mock.patch('aiohttp.web_response.PayloadWriter'):
        yield from resp.prepare(req)

    assert resp.content_length is None
Beispiel #20
0
async def test_change_content_threaded_compression_enabled() -> None:
    req = make_request('GET', '/')
    body_thread_size = 1024
    body = b'answer' * body_thread_size
    resp = Response(body=body,
                    zlib_executor_size=body_thread_size)
    resp.enable_compression(ContentCoding.gzip)

    await resp.prepare(req)
    assert gzip.decompress(resp._compressed_body) == body
Beispiel #21
0
def test_consecutive_write_eof():
    req = make_request('GET', '/')
    data = b'data'
    resp = Response(body=data)

    yield from resp.prepare(req)
    with mock.patch('aiohttp.web.StreamResponse.write_eof') as super_write_eof:
        yield from resp.write_eof()
        resp._eof_sent = True
        yield from resp.write_eof()
        super_write_eof.assert_called_once_with(data)
Beispiel #22
0
def test_ctor_with_headers_and_status():
    resp = Response(body=b'body', status=201,
                    headers={'Age': '12', 'DATE': 'date'})

    assert 201 == resp.status
    assert b'body' == resp.body
    assert resp.headers['AGE'] == '12'

    resp._start(mock.Mock(version=HttpVersion11))
    assert 4 == resp.content_length
    assert resp.headers['CONTENT-LENGTH'] == '4'
Beispiel #23
0
def user_info(request):
    resp = Response()
    client = AsyncWeChatClient(APPID, SECRET)
    try:
        user = yield from client.user.get(OPENID)
    except Exception as e:
        print(e)
        resp.body = str(e).encode('utf-8')
    else:
        resp.body = json.dumps(user).encode('utf-8')
    return resp
Beispiel #24
0
def user_group_id(request):
    resp = Response()
    client = AsyncWeChatClient(APPID, SECRET, timeout=10)
    try:
        group_id = yield from client.user.get_group_id(OPENID)
    except Exception as e:
        print(e)
        resp.body = str(e).encode('utf-8')
    else:
        resp.body = str(group_id).encode('utf-8')
    return resp
Beispiel #25
0
def test_assign_nonbyteish_body():
    resp = Response(body=b'data')

    with pytest.raises(AssertionError):
        resp.body = 123
    assert b'data' == resp.body
    assert 4 == resp.content_length

    resp._send_headers = mock.Mock()
    resp._start(mock.Mock())
    assert resp.headers['CONTENT-LENGTH'] == '4'
    assert 4 == resp.content_length
Beispiel #26
0
def test_assign_nonbyteish_body():
    resp = Response(body=b'data')

    with pytest.raises(ValueError):
        resp.body = 123
    assert b'data' == resp.body
    assert 4 == resp.content_length

    resp.headers['DATE'] = 'date'
    resp._start(mock.Mock(version=HttpVersion11))
    assert resp.headers['CONTENT-LENGTH'] == '4'
    assert 4 == resp.content_length
Beispiel #27
0
def test_send_headers_for_empty_body(buf, writer):
    req = make_request('GET', '/', payload_writer=writer)
    resp = Response()

    yield from resp.prepare(req)
    yield from resp.write_eof()
    txt = buf.decode('utf8')
    assert re.match('HTTP/1.1 200 OK\r\n'
                    'Content-Length: 0\r\n'
                    'Content-Type: application/octet-stream\r\n'
                    'Date: .+\r\n'
                    'Server: .+\r\n\r\n', txt)
Beispiel #28
0
async def test_assign_nonbyteish_body():
    resp = Response(body=b'data')

    with pytest.raises(ValueError):
        resp.body = 123
    assert b'data' == resp.body
    assert 4 == resp.content_length

    resp.headers['DATE'] = 'date'
    req = make_mocked_request('GET', '/', version=HttpVersion11)
    await resp._start(req)
    assert resp.headers['CONTENT-LENGTH'] == '4'
    assert 4 == resp.content_length
Beispiel #29
0
async def test_rm_content_length_if_compression_enabled_on_payload_http10():
    writer = mock.Mock()

    async def write_headers(status_line, headers):
        assert hdrs.CONTENT_LENGTH not in headers
        assert hdrs.TRANSFER_ENCODING not in headers

    writer.write_headers.side_effect = write_headers
    req = make_request('GET', '/', version=HttpVersion10,
                       writer=writer)
    resp = Response(body=BytesPayload(b'answer'))
    resp.enable_compression(ContentCoding.gzip)
    await resp.prepare(req)
    assert resp.content_length is None
Beispiel #30
0
async def test_force_compression_identity_response():
    writer = mock.Mock()

    async def write_headers(status_line, headers):
        assert headers[hdrs.CONTENT_LENGTH] == "6"
        assert hdrs.TRANSFER_ENCODING not in headers

    writer.write_headers.side_effect = write_headers
    req = make_request('GET', '/',
                       writer=writer)
    resp = Response(body=b'answer')
    resp.enable_compression(ContentCoding.identity)
    await resp.prepare(req)
    assert resp.content_length == 6
Beispiel #31
0
def json_response(data):
    body = ujson.dumps(data)
    return Response(body=body.encode(), content_type='application/json')
Beispiel #32
0
async def plaintext(request):
    """
    Test 6
    """
    return Response(body=b'Hello, World!', content_type='text/plain')
Beispiel #33
0
def raw_json_response(json_str, status_=200):
    return Response(
        body=json_str.encode() + b'\n',
        status=status_,
        content_type=JSON_CONTENT_TYPE,
    )
Beispiel #34
0
 def test_ctor_text_body_combined(self):
     with self.assertRaises(ValueError):
         Response(body=b'123', text='test text')
Beispiel #35
0
def test_nonstr_text_in_ctor() -> None:
    with pytest.raises(TypeError):
        Response(text=b"data")
 async def delete(self):
     TagTask.delete_object(self.uuid)
     return Response()
Beispiel #37
0
def simple(request):
    return Response(body=b'Simple answer')
Beispiel #38
0
        _LOGGER.warning(
            "Received message for unregistered webhook %s from %s",
            webhook_id,
            received_from,
        )
        # Look at content to provide some context for received webhook
        # Limit to 64 chars to avoid flooding the log
        content = await request.content.read(64)
        _LOGGER.debug("%s", content)
        return Response(status=HTTPStatus.OK)

    try:
        response = await webhook["handler"](hass, webhook_id, request)
        if response is None:
            response = Response(status=HTTPStatus.OK)
        return response
    except Exception:  # pylint: disable=broad-except
        _LOGGER.exception("Error processing webhook %s", webhook_id)
        return Response(status=HTTPStatus.OK)


async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Initialize the webhook component."""
    hass.http.register_view(WebhookView)
    hass.components.websocket_api.async_register_command(
        WS_TYPE_LIST, websocket_list, SCHEMA_WS_LIST)
    return True


class WebhookView(HomeAssistantView):
Beispiel #39
0
def test_text_in_ctor_with_content_type_header():
    resp = Response(text='текст',
                    headers={'Content-Type': 'text/html; charset=koi8-r'})
    assert 'текст'.encode('koi8-r') == resp.body
    assert 'text/html' == resp.content_type
    assert 'koi8-r' == resp.charset
Beispiel #40
0
def test_text_in_ctor_with_content_type():
    resp = Response(text='data', content_type='text/html')
    assert 'data' == resp.text
    assert 'text/html' == resp.content_type
Beispiel #41
0
async def post(request, obj):
    message = await request.json()
    request.app.broadcast_object_message(obj, message)
    return Response(status=204)
Beispiel #42
0
async def get(request, obj):
    if not utils.is_hal_request(request):
        return Response(body=b'Unacceptable', status=406)
    return utils.json_response(utils.halify_object(obj))
def function1605(arg1239):
    var666 = arg1239.app['args']
    var2962 = '\n'.join(([var666.message] * var666.repeat))
    return Response(text=var2962)
Beispiel #44
0
def json_response(*, status_=200, list_=None, headers_=None, **data):
    return Response(body=json.dumps(data if list_ is None else list_).encode(),
                    status=status_,
                    content_type=JSON_CONTENT_TYPE,
                    headers=headers_)
 async def delete(self):
     todoObj = TodoTask.get_object(self.uuid)
     todoObj['tags'] = []
     TodoTask.update_object(self.uuid, todoObj)
     return Response()
Beispiel #46
0
def test_ctor_both_content_type_param_and_header() -> None:
    with pytest.raises(ValueError):
        Response(headers={"Content-Type": "application/json"},
                 content_type="text/html")
Beispiel #47
0
def test_text_in_ctor_with_content_type() -> None:
    resp = Response(text="data", content_type="text/html")
    assert "data" == resp.text
    assert "text/html" == resp.content_type
Beispiel #48
0
def test_content_type_with_set_body() -> None:
    resp = Response(body=b"body")
    assert resp.content_type == "application/octet-stream"
Beispiel #49
0
def test_default_content_type_in_response() -> None:
    resp = Response()
    assert resp.content_type == "application/octet-stream"
Beispiel #50
0
def test_response_set_content_length() -> None:
    resp = Response()
    with pytest.raises(RuntimeError):
        resp.content_length = 1
    async def delete(self):
        TodoTask.decouple_one_tag(self.todos_uuid, self.tags_uuid)

        return Response()
async def wshandler(request):
    resp = WebSocketResponse()
    ok, protocol = resp.can_prepare(request)
    if not ok:
        with open(WS_FILE, 'rb') as fp:
            return Response(body=fp.read(), content_type='text/html')

    await resp.prepare(request)

    try:
        # перебираем всех уже подключенных пользователей и рассылаем им сообщение
        # for ws in request.app['sockets']:
        #     ws.send_str('Someone joined')
        # добавляем новое соединение
        # if resp not in request.app['sockets']:
        request.app['sockets'].append(resp)

        # перебираем свои сообщения
        async for msg in resp:
            if msg.type == WSMsgType.TEXT:
                try:
                    # if msg.data:
                    #     message_obj = Message()
                    #     message_obj.id_from = 80
                    #     message_obj.id_to_user = 94
                    #     message_obj.message = msg.data
                    #     message_obj.save()
                    json_data = json.loads(msg.data)
                except:
                    json_data = {}

                data = json_data.get('data')
                if data is None or type(data) is not dict:
                    data = {}
                try:
                    from sockets.routes.routes import routes_map
                    command = json_data.get('command')
                    command_not_found = True
                    if type(command) is str and command:
                        for route in routes_map:
                            if command == route[0]:
                                handler = route[1](data, route=route)
                                if getattr(handler, command):
                                    command_not_found = False
                                    before_return = True
                                    if hasattr(handler, '_before'):
                                        before_return = getattr(
                                            handler, '_before')(resp)
                                    if before_return:
                                        is_async = asyncio.iscoroutinefunction(
                                            getattr(handler, command))
                                        if is_async:
                                            await getattr(handler,
                                                          command)(resp)
                                        else:
                                            getattr(handler, command)(resp)
                    if command_not_found is True:
                        from sockets.handlers.BaseHandler import BaseHandler
                        handler = BaseHandler(resp)
                        handler.make_response({"command": command},
                                              'command_not_found', resp)
                except Exception as e:
                    handler.make_response({"error": "exception"}, str(e), resp)
            else:
                return resp
        return resp
    finally:
        # разрываем соединение
        from sockets.helpers.Socket import Socket
        Socket.update_last_connection(resp)
        Socket.del_client(resp)
        request.app['sockets'].remove(resp)
Beispiel #53
0
def test_content_type_with_set_text() -> None:
    resp = Response(text="text")
    assert resp.content_type == "text/plain"
Beispiel #54
0
def allow_cors(response: web.Response) -> web.Response:
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response
 async def delete(self):
     TagTask.delete_all_objects()
     return Response()
Beispiel #56
0
def test_text_in_ctor_with_content_type_header() -> None:
    resp = Response(text="текст",
                    headers={"Content-Type": "text/html; charset=koi8-r"})
    assert "текст".encode("koi8-r") == resp.body
    assert "text/html" == resp.content_type
    assert "koi8-r" == resp.charset
Beispiel #57
0
def test_ctor_both_charset_param_and_header() -> None:
    with pytest.raises(ValueError):
        Response(headers={"Content-Type": "application/json"},
                 charset="koi8-r")
Beispiel #58
0
def change_body(request):
    resp = Response()
    resp.body = b"Body changed"
    return resp
 async def get() -> Response:
     """Ready route function."""
     return Response(text="OK")
Beispiel #60
0
 def handler(request):
     return Response(request)  # pragma: no cover