Exemple #1
0
    def handle(environ, start_response):

        req = webob.Request(environ)
        vers = aiohttp.HttpVersion10 if req.http_version == 'HTTP/1.0' else aiohttp.HttpVersion11
        message = aiohttp.RawRequestMessage(req.method, req.path_qs, vers,
                                            aiohttp.CIMultiDict(req.headers),
                                            req.headers, False, False)
        payload = aiohttp.StreamReader(loop=loop_)
        payload.feed_data(req.body)
        payload.feed_eof()
        factory = aiohttp.web.RequestHandlerFactory(app_,
                                                    app_.router,
                                                    loop=loop_,
                                                    keep_alive_on=False)
        handler = factory()
        handler.transport = io.BytesIO()
        handler.transport.is_closing = lambda: False
        handler.transport._conn_lost = 0
        handler.transport.get_extra_info = lambda s: ('127.0.0.1', 80)
        handler.writer = aiohttp.parsers.StreamWriter(handler.transport,
                                                      handler, handler.reader,
                                                      handler._loop)
        coro = handler.handle_request(message, payload)
        if loop_.is_running():
            raise RuntimeError(
                'Client cannot start durring another coroutine is running.')

        loop_.run_until_complete(coro)
        handler.transport.seek(9)
        res = webob.Response.from_file(handler.transport)
        start_response(res.status, res.headerlist)
        return res.app_iter
Exemple #2
0
async def test_get(bot, monkeypatch, event_loop):
    '''Tests the get() method.'''
    test_json = {'var1': 1, 'var2': 2}
    test_url = URL('http://www.google.com')

    # Create a ClientResponse object that will be returned as a result of the
    # mocked request.
    mock_response = aiohttp.client_reqrep.ClientResponse('get', test_url)

    # Encode the test JSON and store it in the ClientResponse
    mock_response._content = bytes(json.dumps(test_json), encoding='ASCII')

    # Add empty headers to the ClientResponse
    mock_response.headers = aiohttp.CIMultiDictProxy(aiohttp.CIMultiDict([]))

    # A function which mocks aiohttp's ClientSession._request to return
    # the mock response.
    async def mock_request(method, url, *args, **kwargs):
        return mock_response

    monkeypatch.setattr(aiohttp.client.ClientSession, '_request', mock_request)

    # Make the get request
    async with aiohttp.ClientSession(loop=event_loop) as session:
        response = await bot.get(session, 'http://www.google.com')

    # Check that the response matches the desired JSON
    assert response == test_json