コード例 #1
0
ファイル: test_client_ws.py プロジェクト: cr0hn/aiohttp
def test_close_exc(loop, ws_key, key_data):
    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
    }
    with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter:
        with mock.patch('aiohttp.client.os') as m_os:
            with mock.patch('aiohttp.client.ClientSession.get') as m_req:
                m_os.urandom.return_value = key_data
                m_req.return_value = helpers.create_future(loop)
                m_req.return_value.set_result(resp)
                WebSocketWriter.return_value = mock.Mock()
                reader = mock.Mock()
                resp.connection.reader.set_parser.return_value = reader

                resp = yield from aiohttp.ws_connect('http://test.org',
                                                     loop=loop)
                assert not resp.closed

                exc = ValueError()
                reader.read.return_value = helpers.create_future(loop)
                reader.read.return_value.set_exception(exc)

                yield from resp.close()
                assert resp.closed
                assert resp.exception() is exc
コード例 #2
0
ファイル: test_worker.py プロジェクト: kpidata/aiohttp
def test__run_exc(worker, loop):
    with mock.patch('aiohttp.worker.os') as m_os:
        m_os.getpid.return_value = 1
        m_os.getppid.return_value = 1

        worker.servers = [mock.Mock()]
        worker.ppid = 1
        worker.alive = True
        worker.sockets = []
        worker.log = mock.Mock()
        worker.loop = mock.Mock()
        worker.notify = mock.Mock()
        worker.cfg.is_ssl = False

        with mock.patch('aiohttp.worker.asyncio.sleep') as m_sleep:
            slp = helpers.create_future(loop)
            slp.set_exception(KeyboardInterrupt)
            m_sleep.return_value = slp

            worker.close = mock.Mock()
            worker.close.return_value = helpers.create_future(loop)
            worker.close.return_value.set_result(1)

            loop.run_until_complete(worker._run())

        assert m_sleep.called
        assert worker.close.called
コード例 #3
0
ファイル: test_worker.py プロジェクト: IlyaSemenov/aiohttp
def test__run_ok(worker, loop):
    worker.ppid = 1
    worker.alive = True
    worker.servers = {}
    sock = mock.Mock()
    sock.cfg_addr = ('localhost', 8080)
    worker.sockets = [sock]
    worker.wsgi = mock.Mock()
    worker.close = mock.Mock()
    worker.close.return_value = helpers.create_future(loop)
    worker.close.return_value.set_result(())
    worker.log = mock.Mock()
    worker.notify = mock.Mock()
    worker.loop = loop
    ret = helpers.create_future(loop)
    loop.create_server = mock.Mock(
        wraps=asyncio.coroutine(lambda *a, **kw: ret))
    ret.set_result(sock)
    worker.wsgi.make_handler.return_value.num_connections = 1
    worker.cfg.max_requests = 100

    with mock.patch('aiohttp.worker.asyncio') as m_asyncio:
        m_asyncio.sleep = mock.Mock(
            wraps=asyncio.coroutine(lambda *a, **kw: None))
        loop.run_until_complete(worker._run())

    assert worker.notify.called
    assert worker.log.info.called
コード例 #4
0
    def test_close(self, m_req, m_os, WebSocketWriter):
        resp = mock.Mock()
        resp.status = 101
        resp.headers = {
            hdrs.UPGRADE: hdrs.WEBSOCKET,
            hdrs.CONNECTION: hdrs.UPGRADE,
            hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key,
        }
        m_os.urandom.return_value = self.key_data
        m_req.return_value = helpers.create_future(self.loop)
        m_req.return_value.set_result(resp)
        writer = WebSocketWriter.return_value = mock.Mock()
        reader = resp.connection.reader.set_parser.return_value = mock.Mock()

        resp = self.loop.run_until_complete(
            aiohttp.ws_connect('http://test.org', loop=self.loop))
        self.assertFalse(resp.closed)

        msg = websocket.Message(websocket.MSG_CLOSE, b'', b'')
        reader.read.return_value = helpers.create_future(self.loop)
        reader.read.return_value.set_result(msg)

        res = self.loop.run_until_complete(resp.close())
        writer.close.assert_called_with(1000, b'')
        self.assertTrue(resp.closed)
        self.assertTrue(res)
        self.assertIsNone(resp.exception())

        # idempotent
        res = self.loop.run_until_complete(resp.close())
        self.assertFalse(res)
        self.assertEqual(writer.close.call_count, 1)
コード例 #5
0
    def test_close_exc(self, m_req, m_os, WebSocketWriter):
        resp = mock.Mock()
        resp.status = 101
        resp.headers = {
            hdrs.UPGRADE: hdrs.WEBSOCKET,
            hdrs.CONNECTION: hdrs.UPGRADE,
            hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key,
        }
        m_os.urandom.return_value = self.key_data
        m_req.return_value = helpers.create_future(self.loop)
        m_req.return_value.set_result(resp)
        WebSocketWriter.return_value = mock.Mock()
        reader = resp.connection.reader.set_parser.return_value = mock.Mock()

        resp = self.loop.run_until_complete(
            aiohttp.ws_connect(
                'http://test.org', loop=self.loop))
        self.assertFalse(resp.closed)

        exc = ValueError()
        reader.read.return_value = helpers.create_future(self.loop)
        reader.read.return_value.set_exception(exc)

        self.loop.run_until_complete(resp.close())
        self.assertTrue(resp.closed)
        self.assertIs(resp.exception(), exc)
コード例 #6
0
    def test_reader_read_exception(self, m_req, m_os, WebSocketWriter):
        hresp = mock.Mock()
        hresp.status = 101
        hresp.headers = {
            hdrs.UPGRADE: hdrs.WEBSOCKET,
            hdrs.CONNECTION: hdrs.UPGRADE,
            hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key,
        }
        m_os.urandom.return_value = self.key_data
        m_req.return_value = helpers.create_future(self.loop)
        m_req.return_value.set_result(hresp)
        WebSocketWriter.return_value = mock.Mock()
        reader = hresp.connection.reader.set_parser.return_value = mock.Mock()

        resp = self.loop.run_until_complete(
            aiohttp.ws_connect(
                'http://test.org', loop=self.loop))

        exc = ValueError()
        reader.read.return_value = helpers.create_future(self.loop)
        reader.read.return_value.set_exception(exc)

        msg = self.loop.run_until_complete(resp.receive())
        self.assertEqual(msg.tp, aiohttp.MsgType.error)
        self.assertIs(resp.exception(), exc)
コード例 #7
0
ファイル: test_wsgi.py プロジェクト: cr0hn/aiohttp
 def wsgi_app(env, start):
     start('200 OK', [('Content-Type', 'text/plain')])
     f1 = helpers.create_future(self.loop)
     f1.set_result(b'data')
     fut = helpers.create_future(self.loop)
     fut.set_result([f1])
     return fut
コード例 #8
0
ファイル: test_client_ws.py プロジェクト: cr0hn/aiohttp
def test_reader_read_exception(ws_key, key_data, loop):
    hresp = mock.Mock()
    hresp.status = 101
    hresp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
    }
    with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter:
        with mock.patch('aiohttp.client.os') as m_os:
            with mock.patch('aiohttp.client.ClientSession.get') as m_req:
                m_os.urandom.return_value = key_data
                m_req.return_value = helpers.create_future(loop)
                m_req.return_value.set_result(hresp)
                WebSocketWriter.return_value = mock.Mock()
                reader = mock.Mock()
                hresp.connection.reader.set_parser.return_value = reader

                resp = yield from aiohttp.ws_connect('http://test.org',
                                                     loop=loop)

                exc = ValueError()
                reader.read.return_value = helpers.create_future(loop)
                reader.read.return_value.set_exception(exc)

                msg = yield from resp.receive()
                assert msg.type == aiohttp.MsgType.ERROR
                assert msg.type is msg.tp
                assert resp.exception() is exc
コード例 #9
0
ファイル: test_streams.py プロジェクト: singulared/aiohttp
def test_feed_eof_waiters(loop):
    reader = streams.StreamReader(loop=loop)
    waiter = reader._waiter = helpers.create_future(loop)
    eof_waiter = reader._eof_waiter = helpers.create_future(loop)

    reader.feed_eof()
    assert reader._eof

    assert waiter.done()
    assert eof_waiter.done()
    assert reader._waiter is None
    assert reader._eof_waiter is None
コード例 #10
0
ファイル: test_streams.py プロジェクト: singulared/aiohttp
def test_set_exception(loop):
    reader = streams.StreamReader(loop=loop)
    waiter = reader._waiter = helpers.create_future(loop)
    eof_waiter = reader._eof_waiter = helpers.create_future(loop)

    exc = ValueError()
    reader.set_exception(exc)

    assert waiter.exception() is exc
    assert eof_waiter.exception() is exc
    assert reader._waiter is None
    assert reader._eof_waiter is None
コード例 #11
0
ファイル: test_streams.py プロジェクト: singulared/aiohttp
def test_feed_data_waiters(loop):
    reader = streams.StreamReader(loop=loop)
    waiter = reader._waiter = helpers.create_future(loop)
    eof_waiter = reader._eof_waiter = helpers.create_future(loop)

    reader.feed_data(b'1')
    assert list(reader._buffer) == [b'1']
    assert reader._size == 1
    assert reader.total_bytes == 1

    assert waiter.done()
    assert not eof_waiter.done()
    assert reader._waiter is None
    assert reader._eof_waiter is eof_waiter
コード例 #12
0
ファイル: test_streams.py プロジェクト: singulared/aiohttp
def test_feed_eof_cancelled(loop):
    reader = streams.StreamReader(loop=loop)
    waiter = reader._waiter = helpers.create_future(loop)
    eof_waiter = reader._eof_waiter = helpers.create_future(loop)

    waiter.set_result(1)
    eof_waiter.set_result(1)

    reader.feed_eof()

    assert waiter.done()
    assert eof_waiter.done()
    assert reader._waiter is None
    assert reader._eof_waiter is None
コード例 #13
0
ファイル: test_client_request.py プロジェクト: Eyepea/aiohttp
def test_data_stream_exc(loop, conn):
    fut = helpers.create_future(loop)

    @aiohttp.streamer
    def gen(writer):
        writer.write(b'binary data')
        yield from fut

    req = ClientRequest(
        'POST', URL('http://python.org/'), data=gen(), loop=loop)
    assert req.chunked
    assert req.headers['TRANSFER-ENCODING'] == 'chunked'

    @asyncio.coroutine
    def exc():
        yield from asyncio.sleep(0.01, loop=loop)
        fut.set_exception(ValueError)

    helpers.ensure_future(exc(), loop=loop)

    req.send(conn)
    yield from req._writer
    # assert conn.close.called
    assert conn.protocol.set_exception.called
    yield from req.close()
コード例 #14
0
def test_send_recv_bytes(create_app_and_client, loop):

    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_bytes()
        ws.send_bytes(msg+b'/answer')
        yield from ws.close()
        closed.set_result(1)
        return ws

    app, client = yield from create_app_and_client()
    app.router.add_route('GET', '/', handler)

    ws = yield from client.ws_connect('/')
    ws.send_bytes(b'ask')
    msg = yield from ws.receive()
    assert msg.type == aiohttp.WSMsgType.BINARY
    assert b'ask/answer' == msg.data

    msg = yield from ws.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE
    assert msg.data == 1000
    assert msg.extra == ''

    assert ws.closed
    assert ws.close_code == 1000

    yield from closed
コード例 #15
0
def test_send_recv_json(create_app_and_client, loop):
    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)
        data = yield from ws.receive_json()
        ws.send_json({'response': data['request']})
        yield from ws.close()
        closed.set_result(1)
        return ws

    app, client = yield from create_app_and_client()
    app.router.add_route('GET', '/', handler)

    ws = yield from client.ws_connect('/')

    ws.send_str('{"request": "test"}')
    msg = yield from ws.receive()
    data = msg.json()
    assert msg.type == aiohttp.WSMsgType.TEXT
    assert data['response'] == 'test'

    msg = yield from ws.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE
    assert msg.data == 1000
    assert msg.extra == ''

    yield from ws.close()

    yield from closed
コード例 #16
0
ファイル: test_client_request.py プロジェクト: Eyepea/aiohttp
def test_data_stream_exc_chain(loop, conn):
    fut = helpers.create_future(loop)

    @aiohttp.streamer
    def gen(writer):
        yield from fut

    req = ClientRequest('POST', URL('http://python.org/'),
                        data=gen(), loop=loop)

    inner_exc = ValueError()

    @asyncio.coroutine
    def exc():
        yield from asyncio.sleep(0.01, loop=loop)
        fut.set_exception(inner_exc)

    helpers.ensure_future(exc(), loop=loop)

    req.send(conn)
    yield from req._writer
    # assert connection.close.called
    assert conn.protocol.set_exception.called
    outer_exc = conn.protocol.set_exception.call_args[0][0]
    assert isinstance(outer_exc, ValueError)
    assert inner_exc is outer_exc
    assert inner_exc is outer_exc
    yield from req.close()
コード例 #17
0
    def test_data_stream_exc_chain(self):
        fut = helpers.create_future(self.loop)

        def gen():
            yield from fut

        req = ClientRequest("POST", "http://python.org/", data=gen(), loop=self.loop)

        inner_exc = ValueError()

        @asyncio.coroutine
        def exc():
            yield from asyncio.sleep(0.01, loop=self.loop)
            fut.set_exception(inner_exc)

        asyncio.async(exc(), loop=self.loop)

        resp = req.send(self.transport, self.protocol)
        resp._connection = self.connection
        self.loop.run_until_complete(req._writer)
        self.assertTrue(self.connection.close.called)
        self.assertTrue(self.protocol.set_exception.called)
        outer_exc = self.protocol.set_exception.call_args[0][0]
        self.assertIsInstance(outer_exc, aiohttp.ClientRequestError)
        self.assertIs(inner_exc, outer_exc.__context__)
        self.assertIs(inner_exc, outer_exc.__cause__)
        self.loop.run_until_complete(req.close())
コード例 #18
0
async def test_server_ws_async_for(loop, test_server):
    closed = helpers.create_future(loop)

    async def handler(request):
        ws = web.WebSocketResponse()
        await ws.prepare(request)
        async for msg in ws:
            assert msg.type == aiohttp.MsgType.TEXT
            s = msg.data
            ws.send_str(s + '/answer')
        await ws.close()
        closed.set_result(1)
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    server = await test_server(app)
    resp = await aiohttp.ws_connect(server.make_url('/'), loop=loop)

    items = ['q1', 'q2', 'q3']
    for item in items:
        resp.send_str(item)
        msg = await resp.receive()
        assert msg.type == aiohttp.MsgType.TEXT
        assert item + '/answer' == msg.data

    await resp.close()
    await closed
コード例 #19
0
def test_POST_STREAM_DATA(create_app_and_client, fname, loop):
    @asyncio.coroutine
    def handler(request):
        assert request.content_type == 'application/octet-stream'
        content = yield from request.read()
        with fname.open('rb') as f:
            expected = f.read()
        assert request.content_length == str(len(expected))
        assert content == expected

        return web.HTTPOk()

    app, client = yield from create_app_and_client()
    app.router.add_post('/', handler)

    with fname.open() as f:
        data = f.read()
        fut = create_future(loop)

        @asyncio.coroutine
        def stream():
            yield from fut
            yield data

        loop.call_later(0.01, fut.set_result, None)

        resp = yield from client.post(
            '/', data=stream(),
            headers={'Content-Length': str(len(data))})
        assert 200 == resp.status
        resp.close()
コード例 #20
0
ファイル: test_connector.py プロジェクト: cynecx/aiohttp
def test_close_with_acquired_connection(loop):

    tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
    proto.is_connected.return_value = True

    req = ClientRequest('GET', URL('http://host:80'),
                        loop=loop,
                        response_class=unittest.mock.Mock())

    conn = aiohttp.BaseConnector(loop=loop, limit=1)
    key = ('host', 80, False)
    conn._conns[key] = [(tr, proto, loop.time())]
    conn._create_connection = unittest.mock.Mock()
    conn._create_connection.return_value = helpers.create_future(loop)
    conn._create_connection.return_value.set_result((tr, proto))

    connection = yield from conn.connect(req)

    assert 1 == len(conn._acquired)
    conn.close()
    assert 0 == len(conn._acquired)
    assert conn.closed
    tr.close.assert_called_with()

    assert not connection.closed
    connection.close()
    assert connection.closed
コード例 #21
0
def test_close_from_server(loop, test_client):

    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        try:
            yield from ws.receive_bytes()
            yield from ws.close()
        finally:
            closed.set_result(1)
        return ws

    app = web.Application()
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/')

    yield from resp.send_bytes(b'ask')

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE
    assert resp.closed

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSED

    yield from closed
コード例 #22
0
ファイル: test_connector.py プロジェクト: cynecx/aiohttp
def test_connect_with_limit_cancelled(loop):

    tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
    proto.is_connected.return_value = True

    req = ClientRequest('GET', URL('http://host:80'),
                        loop=loop,
                        response_class=unittest.mock.Mock())

    conn = aiohttp.BaseConnector(loop=loop, limit=1)
    key = ('host', 80, False)
    conn._conns[key] = [(tr, proto, loop.time())]
    conn._create_connection = unittest.mock.Mock()
    conn._create_connection.return_value = helpers.create_future(loop)
    conn._create_connection.return_value.set_result((tr, proto))

    connection = yield from conn.connect(req)
    assert connection._transport == tr

    assert 1 == len(conn._acquired[key])

    with pytest.raises(asyncio.TimeoutError):
        # limit exhausted
        yield from asyncio.wait_for(conn.connect(req), 0.01,
                                    loop=loop)
    connection.close()
コード例 #23
0
ファイル: test_connector.py プロジェクト: boylea/aiohttp
        def go():
            tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
            proto.is_connected.return_value = True

            class Req:
                host = 'host'
                port = 80
                ssl = False
                response = unittest.mock.Mock()

            conn = aiohttp.BaseConnector(loop=self.loop, limit=1)
            key = ('host', 80, False)
            conn._conns[key] = [(tr, proto, self.loop.time())]
            conn._create_connection = unittest.mock.Mock()
            conn._create_connection.return_value = helpers.create_future(
                self.loop)
            conn._create_connection.return_value.set_result((tr, proto))

            connection = yield from conn.connect(Req())
            self.assertEqual(connection._transport, tr)

            self.assertEqual(1, len(conn._acquired[key]))

            with self.assertRaises(asyncio.TimeoutError):
                # limit exhausted
                yield from asyncio.wait_for(conn.connect(Req), 0.01,
                                            loop=self.loop)
            connection.close()
コード例 #24
0
async def test_server_ws_async_for(loop, create_server):
    closed = helpers.create_future(loop)

    async def handler(request):
        ws = web.WebSocketResponse()
        await ws.prepare(request)
        async for msg in ws:
            assert msg.type == aiohttp.MsgType.TEXT
            s = msg.data
            ws.send_str(s + "/answer")
        await ws.close()
        closed.set_result(1)
        return ws

    app, url = await create_server(proto="ws")
    app.router.add_route("GET", "/", handler)
    resp = await aiohttp.ws_connect(url, loop=loop)

    items = ["q1", "q2", "q3"]
    for item in items:
        resp.send_str(item)
        msg = await resp.receive()
        assert msg.type == aiohttp.MsgType.TEXT
        assert item + "/answer" == msg.data

    await resp.close()
    await closed
コード例 #25
0
    def test_client_close_handshake(self):

        closed = helpers.create_future(self.loop)

        @asyncio.coroutine
        def handler(request):
            ws = web.WebSocketResponse(
                autoclose=False, protocols=('foo', 'bar'))
            yield from ws.prepare(request)

            msg = yield from ws.receive()
            self.assertEqual(msg.type, WSMsgType.CLOSE)
            self.assertFalse(ws.closed)
            yield from ws.close()
            self.assertTrue(ws.closed)
            self.assertEqual(ws.close_code, 1007)

            msg = yield from ws.receive()
            self.assertEqual(msg.type, WSMsgType.CLOSED)

            closed.set_result(None)
            return ws

        @asyncio.coroutine
        def go():
            _, _, url = yield from self.create_server('GET', '/', handler)
            resp, reader, writer = yield from self.connect_ws(url, 'eggs, bar')

            writer.close(code=1007)
            msg = yield from reader.read()
            self.assertEqual(msg.type, WSMsgType.CLOSE)
            yield from closed
            resp.close()

        self.loop.run_until_complete(go())
コード例 #26
0
    def test_client_ping(self):

        closed = helpers.create_future(self.loop)

        @asyncio.coroutine
        def handler(request):
            ws = web.WebSocketResponse()
            yield from ws.prepare(request)

            yield from ws.receive()
            closed.set_result(None)
            return ws

        @asyncio.coroutine
        def go():
            _, _, url = yield from self.create_server('GET', '/', handler)
            resp, reader, writer = yield from self.connect_ws(url)
            writer.ping('data')
            msg = yield from reader.read()
            self.assertEqual(msg.type, WSMsgType.PONG)
            self.assertEqual(msg.data, b'data')
            writer.pong()
            writer.close()
            yield from closed
            resp.close()

        self.loop.run_until_complete(go())
コード例 #27
0
    def test_server_close_handshake_server_eats_client_messages(self):

        closed = helpers.create_future(self.loop)

        @asyncio.coroutine
        def handler(request):
            ws = web.WebSocketResponse(protocols=('foo', 'bar'))
            yield from ws.prepare(request)
            yield from ws.close()
            closed.set_result(None)
            return ws

        @asyncio.coroutine
        def go():
            _, _, url = yield from self.create_server('GET', '/', handler)
            response, reader, writer = yield from self.connect_ws(
                url, 'eggs, bar')

            msg = yield from reader.read()
            self.assertEqual(msg.type, WSMsgType.CLOSE)

            writer.send('text')
            writer.send(b'bytes', binary=True)
            writer.ping()

            writer.close()
            yield from closed

            response.close()

        self.loop.run_until_complete(go())
コード例 #28
0
ファイル: test_connector.py プロジェクト: boylea/aiohttp
        def go():
            tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
            proto.is_connected.return_value = True

            class Req:
                host = 'host'
                port = 80
                ssl = False
                response = unittest.mock.Mock()

            conn = aiohttp.BaseConnector(loop=self.loop, limit=1)
            key = ('host', 80, False)
            conn._conns[key] = [(tr, proto, self.loop.time())]
            conn._create_connection = unittest.mock.Mock()
            conn._create_connection.return_value = helpers.create_future(
                self.loop)
            conn._create_connection.return_value.set_result((tr, proto))

            connection = yield from conn.connect(Req())

            self.assertEqual(1, len(conn._acquired))
            conn.close()
            self.assertEqual(0, len(conn._acquired))
            self.assertTrue(conn.closed)
            tr.close.assert_called_with()

            self.assertFalse(connection.closed)
            connection.close()
            self.assertTrue(connection.closed)
コード例 #29
0
    def test_auto_pong_with_closing_by_peer(self):

        closed = helpers.create_future(self.loop)

        @asyncio.coroutine
        def handler(request):
            ws = web.WebSocketResponse()
            yield from ws.prepare(request)
            yield from ws.receive()

            msg = yield from ws.receive()
            self.assertEqual(msg.type, WSMsgType.CLOSE)
            self.assertEqual(msg.data, 1000)
            self.assertEqual(msg.extra, 'exit message')
            closed.set_result(None)
            return ws

        @asyncio.coroutine
        def go():
            _, _, url = yield from self.create_server('GET', '/', handler)
            resp, reader, writer = yield from self.connect_ws(url)
            writer.ping()
            writer.send('ask')

            msg = yield from reader.read()
            self.assertEqual(msg.type, WSMsgType.PONG)
            writer.close(1000, 'exit message')
            yield from closed
            resp.close()

        self.loop.run_until_complete(go())
コード例 #30
0
    def test_data_stream_exc(self):
        fut = helpers.create_future(self.loop)

        def gen():
            yield b"binary data"
            yield from fut

        req = ClientRequest("POST", "http://python.org/", data=gen(), loop=self.loop)
        self.assertTrue(req.chunked)
        self.assertTrue(inspect.isgenerator(req.body))
        self.assertEqual(req.headers["TRANSFER-ENCODING"], "chunked")

        @asyncio.coroutine
        def exc():
            yield from asyncio.sleep(0.01, loop=self.loop)
            fut.set_exception(ValueError)

        asyncio.async(exc(), loop=self.loop)

        resp = req.send(self.transport, self.protocol)
        resp._connection = self.connection
        self.loop.run_until_complete(req._writer)
        self.assertTrue(self.connection.close.called)
        self.assertTrue(self.protocol.set_exception.called)
        self.loop.run_until_complete(req.close())
コード例 #31
0
ファイル: test_client_ws.py プロジェクト: psuresh39/aiohttp
def test_ws_connect_err_upgrade(loop, ws_key, key_data):
    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: 'test',
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key
    }
    with mock.patch('aiohttp.client.os') as m_os:
        with mock.patch('aiohttp.client.ClientSession.get') as m_req:
            m_os.urandom.return_value = key_data
            m_req.return_value = helpers.create_future(loop)
            m_req.return_value.set_result(resp)

            with pytest.raises(errors.WSServerHandshakeError) as ctx:
                yield from aiohttp.ws_connect('http://test.org',
                                              protocols=('t1', 't2', 'chat'),
                                              loop=loop)
    assert ctx.value.message == 'Invalid upgrade header'
 def function1665(arg1231, arg132):
     var3476 = asyncio.new_event_loop()
     asyncio.set_event_loop(var3476)
     (var4510, var57) = listen_addr
     var2451 = var3476.create_server((lambda : Class224(web.Server(function1639, loop=var3476), keepalive_timeout=0.5)), var4510, var57, ssl=var3674)
     var1618 = var3476.run_until_complete(var2451)
     var954 = helpers.create_future(var3476)
     arg1231.call_soon_threadsafe(arg132.set_result, (var3476, var954, var1618.sockets[0].getsockname()))
     try:
         var3476.run_until_complete(var954)
     finally:
         run_briefly(var3476)
         for var3651 in var653:
             var3651.close()
         run_briefly(var3476)
         var1618.close()
         var3476.stop()
         var3476.close()
         gc.collect()
コード例 #33
0
ファイル: test_client_ws.py プロジェクト: psuresh39/aiohttp
def test_ws_connect_close_resp_on_err(loop, ws_key, key_data):
    resp = mock.Mock()
    resp.status = 500
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key
    }
    with mock.patch('aiohttp.client.os') as m_os:
        with mock.patch('aiohttp.client.ClientSession.get') as m_req:
            m_os.urandom.return_value = key_data
            m_req.return_value = helpers.create_future(loop)
            m_req.return_value.set_result(resp)

            with pytest.raises(errors.WSServerHandshakeError):
                yield from aiohttp.ws_connect('http://test.org',
                                              protocols=('t1', 't2', 'chat'),
                                              loop=loop)
            resp.close.assert_called_with()
コード例 #34
0
def test_connect(loop):
    proto = mock.Mock()
    proto.is_connected.return_value = True

    req = ClientRequest('GET', URL('http://host:80'), loop=loop)

    conn = aiohttp.BaseConnector(loop=loop)
    key = ('host', 80, False)
    conn._conns[key] = [(proto, loop.time())]
    conn._create_connection = mock.Mock()
    conn._create_connection.return_value = helpers.create_future(loop)
    conn._create_connection.return_value.set_result(proto)

    connection = yield from conn.connect(req)
    assert not conn._create_connection.called
    assert connection._protocol is proto
    assert connection.transport is proto.transport
    assert isinstance(connection, Connection)
    connection.close()
コード例 #35
0
def test_connect_with_limit(loop, key):
    proto = mock.Mock()
    proto.is_connected.return_value = True

    req = ClientRequest('GET',
                        URL('http://localhost1:80'),
                        loop=loop,
                        response_class=mock.Mock())

    conn = aiohttp.BaseConnector(loop=loop, limit=1)
    conn._conns[key] = [(proto, loop.time())]
    conn._create_connection = mock.Mock()
    conn._create_connection.return_value = helpers.create_future(loop)
    conn._create_connection.return_value.set_result(proto)

    connection1 = yield from conn.connect(req)
    assert connection1._protocol == proto

    assert 1 == len(conn._acquired)
    assert proto in conn._acquired
    assert key in conn._acquired_per_host
    assert proto in conn._acquired_per_host[key]

    acquired = False

    @asyncio.coroutine
    def f():
        nonlocal acquired
        connection2 = yield from conn.connect(req)
        acquired = True
        assert 1 == len(conn._acquired)
        assert 1 == len(conn._acquired_per_host[key])
        connection2.release()

    task = helpers.ensure_future(f(), loop=loop)

    yield from asyncio.sleep(0.01, loop=loop)
    assert not acquired
    connection1.release()
    yield from asyncio.sleep(0, loop=loop)
    assert acquired
    yield from task
    conn.close()
コード例 #36
0
ファイル: test_connector.py プロジェクト: rolepoint/aiohttp
        def go():
            tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
            proto.is_connected.return_value = True

            class Req:
                host = 'host'
                port = 80
                ssl = False
                response = unittest.mock.Mock()

            conn = aiohttp.BaseConnector(loop=self.loop, limit=1)
            key = ('host', 80, False)
            conn._conns[key] = [(tr, proto, self.loop.time())]
            conn._create_connection = unittest.mock.Mock()
            conn._create_connection.return_value = helpers.create_future(
                self.loop)
            conn._create_connection.return_value.set_result((tr, proto))

            connection1 = yield from conn.connect(Req())
            self.assertEqual(connection1._transport, tr)

            self.assertEqual(1, len(conn._acquired[key]))

            acquired = False

            @asyncio.coroutine
            def f():
                nonlocal acquired
                connection2 = yield from conn.connect(Req())
                acquired = True
                self.assertEqual(1, len(conn._acquired[key]))
                connection2.release()

            task = asyncio. async (f(), loop=self.loop)

            yield from asyncio.sleep(0.01, loop=self.loop)
            self.assertFalse(acquired)
            connection1.release()
            yield from asyncio.sleep(0, loop=self.loop)
            self.assertTrue(acquired)
            yield from task
            conn.close()
コード例 #37
0
    def test_ws_connect_err_challenge(self, m_req, m_os):
        resp = mock.Mock()
        resp.status = 101
        resp.headers = {
            hdrs.UPGRADE: hdrs.WEBSOCKET,
            hdrs.CONNECTION: hdrs.UPGRADE,
            hdrs.SEC_WEBSOCKET_ACCEPT: 'asdfasdfasdfasdfasdfasdf'
        }
        m_os.urandom.return_value = self.key_data
        m_req.return_value = helpers.create_future(self.loop)
        m_req.return_value.set_result(resp)

        with self.assertRaises(errors.WSServerHandshakeError) as ctx:
            self.loop.run_until_complete(
                aiohttp.ws_connect(
                    'http://test.org',
                    protocols=('t1', 't2', 'chat'),
                    loop=self.loop))
        self.assertEqual(
            ctx.exception.message, 'Invalid challenge response')
コード例 #38
0
def test_ws_connect_non_overlapped_protocols(ws_key, loop, key_data):
    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
        hdrs.SEC_WEBSOCKET_PROTOCOL: 'other,another'
    }
    with mock.patch('aiohttp.client.os') as m_os:
        with mock.patch('aiohttp.client.ClientSession.get') as m_req:
            m_os.urandom.return_value = key_data
            m_req.return_value = helpers.create_future(loop)
            m_req.return_value.set_result(resp)

            res = yield from aiohttp.ClientSession(loop=loop).ws_connect(
                'http://test.org',
                protocols=('t1', 't2', 'chat'))

    assert res.protocol is None
コード例 #39
0
def function2180(function539, arg1977, function1058):
    var2162 = mock.Mock()
    var2162.status = 101
    var2162.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
        hdrs.SEC_WEBSOCKET_PROTOCOL: 'chat',
    }
    with mock.patch('aiohttp.client.os') as var2849:
        with mock.patch('aiohttp.client.ClientSession.get') as var2296:
            var2849.urandom.return_value = function1058
            var2296.return_value = helpers.create_future(arg1977)
            var2296.return_value.set_result(var2162)
            var3475 = yield from aiohttp.ClientSession(
                loop=arg1977).ws_connect('http://test.org',
                                         protocols=('t1', 't2', 'chat'))
    assert isinstance(var3475, client.ClientWebSocketResponse)
    assert (var3475.protocol == 'chat')
    assert (hdrs.ORIGIN not in var2296.call_args[1]['headers'])
コード例 #40
0
def function957(function539, function1058, arg95):
    var390 = mock.Mock()
    var390.status = 101
    var390.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
    }
    with mock.patch('aiohttp.client.WebSocketWriter') as var4401:
        with mock.patch('aiohttp.client.os') as var3432:
            with mock.patch('aiohttp.client.ClientSession.get') as var1628:
                var3432.urandom.return_value = function1058
                var1628.return_value = helpers.create_future(arg95)
                var1628.return_value.set_result(var390)
                var4401.return_value = mock.Mock()
                var390 = yield from aiohttp.ClientSession(
                    loop=arg95).ws_connect('http://test.org')
                pytest.raises(TypeError, var390.send_str, b's')
                pytest.raises(TypeError, var390.send_bytes, 'b')
                pytest.raises(TypeError, var390.send_json, set())
コード例 #41
0
ファイル: test_server.py プロジェクト: tumb1er/aiohttp
def test_keep_alive_close_existing(make_srv, loop):
    transport = mock.Mock()
    srv = make_srv(keep_alive=0)
    srv.connection_made(transport)
    assert srv._keep_alive_handle is None

    srv._keep_alive_period = 15
    keep_alive_handle = srv._keep_alive_handle = mock.Mock()
    srv.handle_request = mock.Mock()
    srv.handle_request.return_value = helpers.create_future(loop)
    srv.handle_request.return_value.set_result(1)

    srv.data_received(
        b'GET / HTTP/1.0\r\n'
        b'HOST: example.com\r\n\r\n')

    loop.run_until_complete(srv._request_handler)
    assert keep_alive_handle.cancel.called
    assert srv._keep_alive_handle is None
    assert transport.close.called
コード例 #42
0
ファイル: test_client_ws.py プロジェクト: narzeja/aiohttp
def test_ws_connect_global_loop(loop, ws_key, key_data):
    asyncio.set_event_loop(loop)

    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key
    }
    with mock.patch('aiohttp.client.os') as m_os:
        with mock.patch('aiohttp.client.ClientSession.get') as m_req:
            m_os.urandom.return_value = key_data
            m_req.return_value = helpers.create_future(loop)
            m_req.return_value.set_result(resp)

            resp = yield from aiohttp.ws_connect('http://test.org')
    assert resp._loop is loop

    asyncio.set_event_loop(None)
コード例 #43
0
def function2656(arg1944, arg1961):
    var1276 = helpers.create_future(arg1944)

    @asyncio.coroutine
    def function1387(arg1985):
        var2800 = web.WebSocketResponse()
        var2800.set_status(200)
        assert (200 == var2800.status)
        yield from var2800.prepare(arg1985)
        assert (101 == var2800.status)
        yield from var2800.close()
        var1276.set_result(None)
        return var2800
    var4472 = web.Application()
    var4472.router.add_get('/', function1387)
    var3887 = yield from arg1961(var4472)
    var2800 = yield from var3887.ws_connect('/', autoping=False)
    yield from var2800.close()
    yield from closed
    yield from var2800.close()
コード例 #44
0
    def test_send_data_type_errors(self, m_req, m_os, WebSocketWriter):
        resp = mock.Mock()
        resp.status = 101
        resp.headers = {
            hdrs.UPGRADE: hdrs.WEBSOCKET,
            hdrs.CONNECTION: hdrs.UPGRADE,
            hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key,
        }
        m_os.urandom.return_value = self.key_data
        m_req.return_value = helpers.create_future(self.loop)
        m_req.return_value.set_result(resp)
        WebSocketWriter.return_value = mock.Mock()

        resp = self.loop.run_until_complete(
            aiohttp.ws_connect(
                'http://test.org', loop=self.loop))

        self.assertRaises(TypeError, resp.send_str, b's')
        self.assertRaises(TypeError, resp.send_bytes, 'b')
        self.assertRaises(TypeError, resp.send_json, set())
コード例 #45
0
def test_close_during_connect(loop):
    proto = mock.Mock()
    proto.is_connected.return_value = True

    fut = helpers.create_future(loop)
    req = ClientRequest('GET', URL('http://host:80'), loop=loop)

    conn = aiohttp.BaseConnector(loop=loop)
    conn._create_connection = mock.Mock()
    conn._create_connection.return_value = fut

    task = helpers.ensure_future(conn.connect(req), loop=loop)
    yield from asyncio.sleep(0, loop=loop)
    conn.close()

    fut.set_result(proto)
    with pytest.raises(aiohttp.ClientConnectionError):
        yield from task

    assert proto.close.called
コード例 #46
0
async def test_handle_protocol(loop, test_client):

    closed = helpers.create_future(loop)

    async def handler(request):
        ws = web.WebSocketResponse(protocols=('foo', 'bar'))
        await ws.prepare(request)
        await ws.close()
        assert 'bar' == ws.ws_protocol
        closed.set_result(None)
        return ws

    app = web.Application()
    app.router.add_get('/', handler)
    client = await test_client(app)

    ws = await client.ws_connect('/', protocols=('eggs', 'bar'))

    await ws.close()
    await closed
コード例 #47
0
def test_ws_connect_deflate(loop, ws_key, key_data):
    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
        hdrs.SEC_WEBSOCKET_EXTENSIONS: 'permessage-deflate',
    }
    with mock.patch('aiohttp.client.os') as m_os:
        with mock.patch('aiohttp.client.ClientSession.get') as m_req:
            m_os.urandom.return_value = key_data
            m_req.return_value = helpers.create_future(loop)
            m_req.return_value.set_result(resp)

            res = yield from aiohttp.ClientSession(loop=loop).ws_connect(
                'http://test.org', compress=15)

    assert res.compress == 15
    assert res.client_notakeover is False
コード例 #48
0
def function1492(arg1944, arg1961):
    var2230 = helpers.create_future(arg1944)

    @asyncio.coroutine
    def function1387(arg1709):
        var2800 = web.WebSocketResponse()
        yield from var2800.prepare(arg1709)
        yield from var2800.receive()
        var2230.set_result(None)
        return var2800
    var4472 = web.Application()
    var4472.router.add_get('/', function1387)
    var3887 = yield from arg1961(var4472)
    var2800 = yield from var3887.ws_connect('/', autoping=False)
    var2800.ping('data')
    var3676 = yield from var2800.receive()
    assert (var3676.type == WSMsgType.PONG)
    assert (var3676.data == b'data')
    var2800.pong()
    yield from var2800.close()
コード例 #49
0
ファイル: test_connector.py プロジェクト: Zagrebelin/aiohttp
def test_connect_with_capacity(loop):

    tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
    proto.is_connected.return_value = True

    req = ClientRequest('GET',
                        URL('http://host:80'),
                        loop=loop,
                        response_class=unittest.mock.Mock())

    conn = aiohttp.BaseConnector(loop=loop, capacity=1)
    key = ('host', 80, False)
    conn._conns[key] = [(tr, proto, loop.time())]
    conn._create_connection = unittest.mock.Mock()
    conn._create_connection.return_value = helpers.create_future(loop)
    conn._create_connection.return_value.set_result((tr, proto))

    connection1 = yield from conn.connect(req)
    assert connection1._transport == tr

    assert 1 == len(conn._acquired)

    acquired = False

    @asyncio.coroutine
    def f():
        nonlocal acquired
        connection2 = yield from conn.connect(req)
        acquired = True
        assert 1 == len(conn._acquired)
        connection2.release()

    task = helpers.ensure_future(f(), loop=loop)

    yield from asyncio.sleep(0.01, loop=loop)
    assert not acquired
    connection1.release()
    yield from asyncio.sleep(0, loop=loop)
    assert acquired
    yield from task
    conn.close()
コード例 #50
0
def function417(arg1944, arg1961):
    var1045 = helpers.create_future(arg1944)

    @asyncio.coroutine
    def function1387(arg1477):
        var2800 = web.WebSocketResponse(protocols=('foo', 'bar'))
        yield from var2800.prepare(arg1477)
        yield from var2800.close()
        var1045.set_result(None)
        return var2800
    var4472 = web.Application()
    var4472.router.add_get('/', function1387)
    var3887 = yield from arg1961(var4472)
    var2800 = yield from var3887.ws_connect('/', autoclose=False, autoping=False, protocols=('eggs', 'bar'))
    var3676 = yield from var2800.receive()
    assert (var3676.type == WSMsgType.CLOSE)
    yield from var2800.send_str('text')
    yield from var2800.send_bytes(b'bytes')
    var2800.ping()
    yield from var2800.close()
    yield from closed
コード例 #51
0
async def test_ws_connect_err_challenge(loop, ws_key, key_data):
    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: 'asdfasdfasdfasdfasdfasdf'
    }
    with mock.patch('aiohttp.client.os') as m_os:
        with mock.patch('aiohttp.client.ClientSession.get') as m_req:
            m_os.urandom.return_value = key_data
            m_req.return_value = helpers.create_future(loop)
            m_req.return_value.set_result(resp)

            with pytest.raises(client.WSServerHandshakeError) as ctx:
                await aiohttp.ClientSession(loop=loop
                                            ).ws_connect('http://test.org',
                                                         protocols=('t1', 't2',
                                                                    'chat'))

    assert ctx.value.message == 'Invalid challenge response'
コード例 #52
0
 async def test_call_dialogflow(self):
     mock_connector = Connector({})
     message = Message("Hello world", "user", "default", mock_connector)
     config = {'name': 'dialogflow', 'access-token': 'test'}
     result = amock.Mock()
     result.json = amock.CoroutineMock()
     result.json.return_value = {
         "result": {
             "action": "myaction",
             "score": 0.7
         },
         "status": {
             "code": 200,
             "errorType": "success"
         }
     }
     with amock.patch('aiohttp.ClientSession.post') as patched_request:
         patched_request.return_value = helpers.create_future(self.loop)
         patched_request.return_value.set_result(result)
         await dialogflow.call_dialogflow(message, config)
         self.assertTrue(patched_request.called)
コード例 #53
0
def function463(function539, arg2031, function1058):
    var4179 = mock.Mock()
    var4179.status = 101
    var4179.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
        hdrs.SEC_WEBSOCKET_PROTOCOL: 'other,another',
    }
    with mock.patch('aiohttp.client.os') as var1009:
        with mock.patch('aiohttp.client.ClientSession.get') as var110:
            var1009.urandom.return_value = function1058
            var110.return_value = helpers.create_future(arg2031)
            var110.return_value.set_result(var4179)
            var2855 = aiohttp.TCPConnector(loop=arg2031, force_close=True)
            var2565 = yield from aiohttp.ClientSession(
                connector=var2855,
                loop=arg2031).ws_connect('http://test.org',
                                         protocols=('t1', 't2', 'chat'))
    assert (var2565.protocol is None)
    del res
コード例 #54
0
def function1817(arg1192, function539, function1058):
    class Class132(client.ClientWebSocketResponse):
        def function2718(self, arg363=False):
            return 'customized!'

    var1258 = mock.Mock()
    var1258.status = 101
    var1258.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
    }
    with mock.patch('aiohttp.client.os') as var2749:
        with mock.patch('aiohttp.client.ClientSession.get') as var1071:
            var2749.urandom.return_value = function1058
            var1071.return_value = helpers.create_future(arg1192)
            var1071.return_value.set_result(var1258)
            var188 = yield from aiohttp.ClientSession(
                ws_response_class=Class132,
                loop=arg1192).ws_connect('http://test.org')
    assert (var188.read() == 'customized!')
コード例 #55
0
    def test_connect(self):
        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()
        proto.is_connected.return_value = True

        req = ClientRequest('GET', 'http://host:80',
                            loop=self.loop,
                            response_class=unittest.mock.Mock())

        conn = aiohttp.BaseConnector(loop=self.loop)
        key = ('host', 80, False)
        conn._conns[key] = [(tr, proto, self.loop.time())]
        conn._create_connection = unittest.mock.Mock()
        conn._create_connection.return_value = helpers.create_future(self.loop)
        conn._create_connection.return_value.set_result((tr, proto))

        connection = self.loop.run_until_complete(conn.connect(req))
        self.assertFalse(conn._create_connection.called)
        self.assertEqual(connection._transport, tr)
        self.assertEqual(connection._protocol, proto)
        self.assertIsInstance(connection, Connection)
        connection.close()
コード例 #56
0
    def test_ws_connect(self, m_req, m_os):
        resp = mock.Mock()
        resp.status = 101
        resp.headers = {
            hdrs.UPGRADE: hdrs.WEBSOCKET,
            hdrs.CONNECTION: hdrs.UPGRADE,
            hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key,
            hdrs.SEC_WEBSOCKET_PROTOCOL: 'chat'
        }
        m_os.urandom.return_value = self.key_data
        m_req.return_value = helpers.create_future(self.loop)
        m_req.return_value.set_result(resp)

        res = self.loop.run_until_complete(
            aiohttp.ws_connect('http://test.org',
                               protocols=('t1', 't2', 'chat'),
                               loop=self.loop))

        self.assertIsInstance(res, ClientWebSocketResponse)
        self.assertEqual(res.protocol, 'chat')
        self.assertNotIn(hdrs.ORIGIN, m_req.call_args[1]["headers"])
コード例 #57
0
ファイル: test_client_ws.py プロジェクト: jen-soft/aiohttp
def test_ws_connect(ws_key, loop, key_data):
    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
        hdrs.SEC_WEBSOCKET_PROTOCOL: 'chat'
    }
    with mock.patch('aiohttp.client.os') as m_os:
        with mock.patch('aiohttp.client.ClientSession.get') as m_req:
            m_os.urandom.return_value = key_data
            m_req.return_value = helpers.create_future(loop)
            m_req.return_value.set_result(resp)

            res = yield from aiohttp.ClientSession(loop=loop).ws_connect(
                'http://test.org', protocols=('t1', 't2', 'chat'))

    assert isinstance(res, client.ClientWebSocketResponse)
    assert res.protocol == 'chat'
    assert hdrs.ORIGIN not in m_req.call_args[1]["headers"]
コード例 #58
0
def test_keep_alive(make_srv, loop, transport, ceil):
    srv = make_srv(keepalive_timeout=0.05)
    srv.connection_made(transport)

    srv.keep_alive(True)
    srv.handle_request = mock.Mock()
    srv.handle_request.return_value = helpers.create_future(loop)
    srv.handle_request.return_value.set_result(1)

    srv.data_received(b'GET / HTTP/1.1\r\n'
                      b'Host: example.com\r\n'
                      b'Content-Length: 0\r\n\r\n')

    yield from asyncio.sleep(0, loop=loop)
    assert len(srv._waiters) == 1
    assert srv._keepalive_handle is not None
    assert not transport.close.called

    yield from asyncio.sleep(0.1, loop=loop)
    assert transport.close.called
    assert srv._waiters[0].cancelled
    def function78(self):
        with function147(self.attribute2267, router=Class273) as var3378:
            var3302 = var3378.var3302('method', 'post')
            var1996 = os.path.dirname(__file__)
            var4222 = os.path.join(var1996, 'sample.key')
            with open(var4222, 'rb') as var1661:
                var4344 = var1661.read()
            var2930 = helpers.create_future(self.attribute2267)

            @aiohttp.streamer
            def function2826(arg1131):
                yield from fut
                arg1131.write(var4344)
            self.attribute2267.call_later(0.01, var2930.set_result, True)
            var3796 = client.ClientSession(loop=self.attribute2267)
            var3190 = self.attribute2267.run_until_complete(var3796.request('post', var3302, data=function2826(), headers={'Content-Length': str(len(var4344)), }))
            var1778 = self.attribute2267.run_until_complete(var3190.json())
            var3190.close()
            var3796.close()
            self.assertEqual(str(len(var4344)), var1778['headers']['Content-Length'])
            self.assertEqual('application/octet-stream', var1778['headers']['Content-Type'])
コード例 #60
0
def test_ping_pong_manual(loop, test_client):

    closed = helpers.create_future(loop)

    @asyncio.coroutine
    def handler(request):
        ws = web.WebSocketResponse()
        yield from ws.prepare(request)

        msg = yield from ws.receive_bytes()
        ws.ping()
        ws.send_bytes(msg+b'/answer')
        try:
            yield from ws.close()
        finally:
            closed.set_result(1)
        return ws

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handler)
    client = yield from test_client(app)
    resp = yield from client.ws_connect('/', autoping=False)

    resp.ping()
    resp.send_bytes(b'ask')

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.PONG

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.PING
    resp.pong()

    msg = yield from resp.receive()
    assert msg.data == b'ask/answer'

    msg = yield from resp.receive()
    assert msg.type == aiohttp.WSMsgType.CLOSE

    yield from closed