diff --git a/aiosonic/__init__.py b/aiosonic/__init__.py index 472aba1..a662628 100644 --- a/aiosonic/__init__.py +++ b/aiosonic/__init__.py @@ -437,6 +437,17 @@ def __init__(self, connector: TCPConnector = None): """ self.connector = connector or TCPConnector() + async def __aenter__(self): + return self + + async def __aexit__(self, *_args, **_kwargs): + await self.shutdown() + + async def shutdown(self): + """Cleanup connections, this method makes client unusable.""" + await self.connector.cleanup() + + async def _request_with_body(self, url: str, method: str, diff --git a/aiosonic/connection.py b/aiosonic/connection.py index e546835..7a65313 100644 --- a/aiosonic/connection.py +++ b/aiosonic/connection.py @@ -72,8 +72,7 @@ def is_closing(): return True # noqa if not (self.key and key == self.key and not is_closing()): - if self.writer: - self.writer.close() + self.close() if urlparsed.scheme == 'https': ssl_context = ssl_context or ssl.create_default_context( @@ -125,7 +124,7 @@ async def __aexit__(self, exc_type, exc, tb): self.key = None self.h2conn = None if self.writer: - self.writer.close() + self.close() if not self.blocked: await self.release() @@ -142,10 +141,14 @@ def timeouts(self) -> Timeouts: def __del__(self): """Cleanup.""" + self.close(True) + + def close(self, check_closing=False): + """Close connection if opened.""" if self.writer: is_closing = getattr(self.writer, 'is_closing', self.writer._transport.is_closing) - if is_closing(): + if not check_closing or is_closing(): self.writer.close() async def http2_request(self, headers: Dict[str, str], diff --git a/aiosonic/connectors.py b/aiosonic/connectors.py index 14f8131..f2960c7 100644 --- a/aiosonic/connectors.py +++ b/aiosonic/connectors.py @@ -59,3 +59,7 @@ async def wait_free_pool(self): if self.pool.is_all_free(): return True asyncio_sleep(0.02) + + async def cleanup(self): + """Cleanup connector connections.""" + await self.pool.cleanup() diff --git a/aiosonic/pools.py b/aiosonic/pools.py index 104ad19..cbb3347 100644 --- a/aiosonic/pools.py +++ b/aiosonic/pools.py @@ -25,6 +25,12 @@ def is_all_free(self): """Indicates if all pool is free.""" return self.pool_size == self.pool.qsize() + async def cleanup(self): + """Get all conn and close them, this method let this pool unusable.""" + for _ in range(self.pool_size): + conn = self.pool.get() + conn.close() + class SmartPool: """Pool which utilizes alive connections.""" @@ -55,3 +61,9 @@ def release(self, conn): def is_all_free(self): """Indicates if all pool is free.""" return self.pool_size == self.sem._value + + async def cleanup(self): + """Get all conn and close them, this method let this pool unusable.""" + for count in range(self.pool_size): + conn = await self.acquire() + conn.close() diff --git a/tests/test_aiosonic.py b/tests/test_aiosonic.py index 7525e88..bbbea4c 100644 --- a/tests/test_aiosonic.py +++ b/tests/test_aiosonic.py @@ -31,12 +31,12 @@ async def test_simple_get(app, aiohttp_server): url = 'http://localhost:%d' % server.port connector = TCPConnector(timeouts=Timeouts(sock_connect=3, sock_read=4)) - client = aiosonic.HTTPClient(connector) - res = await client.get(url) - assert res.status_code == 200 - assert await res.content() == b'Hello, world' - assert await res.text() == 'Hello, world' - await server.close() + async with aiosonic.HTTPClient(connector) as client: + res = await client.get(url) + assert res.status_code == 200 + assert await res.content() == b'Hello, world' + assert await res.text() == 'Hello, world' + await server.close() @pytest.mark.asyncio @@ -47,16 +47,16 @@ async def test_get_python(http2_serv): url = http2_serv connector = TCPConnector(timeouts=Timeouts(sock_connect=3, sock_read=4)) - client = aiosonic.HTTPClient(connector) - res = await client.get( - url, - verify=False, - headers={ - 'user-agent': - ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0)' - ' Gecko/20100101 Firefox/70.0') - }, http2=True) - assert 'Hello World' in await res.text() + async with aiosonic.HTTPClient(connector) as client: + res = await client.get( + url, + verify=False, + headers={ + 'user-agent': + ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0)' + ' Gecko/20100101 Firefox/70.0') + }, http2=True) + assert 'Hello World' in await res.text() @pytest.mark.asyncio @@ -67,10 +67,10 @@ async def test_get_http2(http2_serv): url = http2_serv connector = TCPConnector(timeouts=Timeouts(sock_connect=3, sock_read=4)) - client = aiosonic.HTTPClient(connector) - res = await client.get(url, verify=False) - assert res.status_code == 200 - assert 'Hello World' == await res.text() + async with aiosonic.HTTPClient(connector) as client: + res = await client.get(url, verify=False) + assert res.status_code == 200 + assert 'Hello World' == await res.text() @pytest.mark.asyncio @@ -79,10 +79,10 @@ async def test_get_http2(http2_serv): async def test_method_lower(http2_serv): """Test simple get to node http2 server.""" url = http2_serv - client = aiosonic.HTTPClient() - res = await client.request(url, method="get", verify=False) - assert res.status_code == 200 - assert 'Hello World' == await res.text() + async with aiosonic.HTTPClient() as client: + res = await client.request(url, method="get", verify=False) + assert res.status_code == 200 + assert 'Hello World' == await res.text() class MyConnection(Connection): @@ -105,15 +105,15 @@ async def test_keep_alive_smart_pool(app, aiohttp_server): urlparsed = urlparse(url) connector = TCPConnector(pool_size=2, connection_cls=MyConnection) - client = aiosonic.HTTPClient(connector) + async with aiosonic.HTTPClient(connector) as client: - for _ in range(5): - res = await client.get(url) - connection = await connector.pool.acquire(urlparsed) - assert res.status_code == 200 - assert await res.text() == 'Hello, world' - assert connection.counter == 5 - await server.close() + for _ in range(5): + res = await client.get(url) + async with await connector.pool.acquire(urlparsed) as connection: + assert res.status_code == 200 + assert await res.text() == 'Hello, world' + assert connection.counter == 5 + await server.close() @pytest.mark.asyncio @@ -125,15 +125,15 @@ async def test_keep_alive_cyclic_pool(app, aiohttp_server): connector = TCPConnector(pool_size=2, connection_cls=MyConnection, pool_cls=CyclicQueuePool) - client = aiosonic.HTTPClient(connector) + async with aiosonic.HTTPClient(connector) as client: - for _ in range(5): - res = await client.get(url) - connection = await connector.pool.acquire() - assert res.status_code == 200 - assert await res.text() == 'Hello, world' - assert connection.counter == 2 - await server.close() + for _ in range(5): + res = await client.get(url) + async with await connector.pool.acquire() as connection: + assert res.status_code == 200 + assert await res.text() == 'Hello, world' + assert connection.counter == 2 + await server.close() @pytest.mark.asyncio @@ -143,11 +143,11 @@ async def test_get_with_params(app, aiohttp_server): url = 'http://localhost:%d' % server.port params = {'foo': 'bar'} - client = aiosonic.HTTPClient() - res = await client.get(url, params=params) - assert res.status_code == 200 - assert await res.text() == 'bar' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, params=params) + assert res.status_code == 200 + assert await res.text() == 'bar' + await server.close() @pytest.mark.asyncio @@ -157,11 +157,11 @@ async def test_get_with_params_tuple(app, aiohttp_server): url = 'http://localhost:%d' % server.port params = (('foo', 'bar'), ) - client = aiosonic.HTTPClient() - res = await client.get(url, params=params) - assert res.status_code == 200 - assert await res.text() == 'bar' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, params=params) + assert res.status_code == 200 + assert await res.text() == 'bar' + await server.close() @pytest.mark.asyncio @@ -171,11 +171,11 @@ async def test_post_form_urlencoded(app, aiohttp_server): url = 'http://localhost:%d/post' % server.port data = {'foo': 'bar'} - client = aiosonic.HTTPClient() - res = await client.post(url, data=data) - assert res.status_code == 200 - assert await res.text() == 'bar' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.post(url, data=data) + assert res.status_code == 200 + assert await res.text() == 'bar' + await server.close() @pytest.mark.asyncio @@ -185,11 +185,11 @@ async def test_post_tuple_form_urlencoded(app, aiohttp_server): url = 'http://localhost:%d/post' % server.port data = (('foo', 'bar'), ) - client = aiosonic.HTTPClient() - res = await client.post(url, data=data) - assert res.status_code == 200 - assert await res.text() == 'bar' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.post(url, data=data) + assert res.status_code == 200 + assert await res.text() == 'bar' + await server.close() @pytest.mark.asyncio @@ -199,11 +199,11 @@ async def test_post_json(app, aiohttp_server): url = 'http://localhost:%d/post_json' % server.port data = {'foo': 'bar'} - client = aiosonic.HTTPClient() - res = await client.post(url, json=data, headers=[['x-foo', 'bar']]) - assert res.status_code == 200 - assert await res.text() == 'bar' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.post(url, json=data, headers=[['x-foo', 'bar']]) + assert res.status_code == 200 + assert await res.text() == 'bar' + await server.close() @pytest.mark.asyncio @@ -212,16 +212,16 @@ async def test_put_patch(app, aiohttp_server): server = await aiohttp_server(app) url = 'http://localhost:%d/put_patch' % server.port - client = aiosonic.HTTPClient() - res = await client.put(url) - assert res.status_code == 200 - assert await res.text() == 'put_patch' + async with aiosonic.HTTPClient() as client: + res = await client.put(url) + assert res.status_code == 200 + assert await res.text() == 'put_patch' - client = aiosonic.HTTPClient() - res = await client.patch(url) - assert res.status_code == 200 - assert await res.text() == 'put_patch' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.patch(url) + assert res.status_code == 200 + assert await res.text() == 'put_patch' + await server.close() @pytest.mark.asyncio @@ -230,11 +230,11 @@ async def test_delete(app, aiohttp_server): server = await aiohttp_server(app) url = 'http://localhost:%d/delete' % server.port - client = aiosonic.HTTPClient() - res = await client.delete(url) - assert res.status_code == 200 - assert await res.text() == 'deleted' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.delete(url) + assert res.status_code == 200 + assert await res.text() == 'deleted' + await server.close() @pytest.mark.asyncio @@ -243,10 +243,10 @@ async def test_post_multipart_to_django(live_server): url = live_server.url + '/post_file' data = {'foo': open('tests/files/bar.txt', 'rb'), 'field1': 'foo'} - client = aiosonic.HTTPClient() - res = await client.post(url, data=data, multipart=True) - assert res.status_code == 200 - assert await res.text() == 'bar-foo' + async with aiosonic.HTTPClient() as client: + res = await client.post(url, data=data, multipart=True) + assert res.status_code == 200 + assert await res.text() == 'bar-foo' @pytest.mark.asyncio @@ -263,8 +263,8 @@ async def long_connect(*_args, **_kwargs): connector = TCPConnector(timeouts=Timeouts(sock_connect=0.2)) with pytest.raises(ConnectTimeout): - client = aiosonic.HTTPClient(connector) - await client.get(url) + async with aiosonic.HTTPClient(connector) as client: + await client.get(url) @pytest.mark.asyncio @@ -273,11 +273,10 @@ async def test_read_timeout(app, aiohttp_server, mocker): server = await aiohttp_server(app) url = 'http://localhost:%d/slow_request' % server.port connector = TCPConnector(timeouts=Timeouts(sock_read=0.2)) - client = aiosonic.HTTPClient(connector) - - with pytest.raises(ReadTimeout): - await client.get(url) - await server.close() + async with aiosonic.HTTPClient(connector) as client: + with pytest.raises(ReadTimeout): + await client.get(url) + await server.close() @pytest.mark.asyncio @@ -290,13 +289,13 @@ async def test_timeouts_overriden(app, aiohttp_server, mocker): # instead the one provided by request call connector = TCPConnector(timeouts=Timeouts(sock_read=2)) - client = aiosonic.HTTPClient(connector) - response = await client.get(url) - assert response.status_code == 200 + async with aiosonic.HTTPClient(connector) as client: + response = await client.get(url) + assert response.status_code == 200 - with pytest.raises(ReadTimeout): - await client.get(url, timeouts=Timeouts(sock_read=0.3)) - await server.close() + with pytest.raises(ReadTimeout): + await client.get(url, timeouts=Timeouts(sock_read=0.3)) + await server.close() @pytest.mark.asyncio @@ -311,11 +310,11 @@ async def long_request(*_args, **_kwargs): _connect = mocker.patch('aiosonic._do_request', new=long_request) _connect.return_value = long_request() connector = TCPConnector(timeouts=Timeouts(request_timeout=0.2)) - client = aiosonic.HTTPClient(connector) + async with aiosonic.HTTPClient(connector) as client: - with pytest.raises(RequestTimeout): - await client.get(url) - await server.close() + with pytest.raises(RequestTimeout): + await client.get(url) + await server.close() @pytest.mark.asyncio @@ -325,14 +324,14 @@ async def test_pool_acquire_timeout(app, aiohttp_server, mocker): url = 'http://localhost:%d/slow_request' % server.port connector = TCPConnector(pool_size=1, timeouts=Timeouts(pool_acquire=0.3)) - client = aiosonic.HTTPClient(connector) + async with aiosonic.HTTPClient(connector) as client: - with pytest.raises(ConnectionPoolAcquireTimeout): - await asyncio.gather( - client.get(url), - client.get(url), - ) - await server.close() + with pytest.raises(ConnectionPoolAcquireTimeout): + await asyncio.gather( + client.get(url), + client.get(url), + ) + await server.close() @pytest.mark.asyncio @@ -341,11 +340,11 @@ async def test_simple_get_ssl(app, aiohttp_server, ssl_context): server = await aiohttp_server(app, ssl=ssl_context) url = 'https://localhost:%d' % server.port - client = aiosonic.HTTPClient() - res = await client.get(url, verify=False) - assert res.status_code == 200 - assert await res.text() == 'Hello, world' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, verify=False) + assert res.status_code == 200 + assert await res.text() == 'Hello, world' + await server.close() @pytest.mark.asyncio @@ -357,11 +356,11 @@ async def test_simple_get_ssl_ctx(app, aiohttp_server, ssl_context): ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, ) ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE - client = aiosonic.HTTPClient() - res = await client.get(url, ssl=ssl_context) - assert res.status_code == 200 - assert await res.text() == 'Hello, world' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, ssl=ssl_context) + assert res.status_code == 200 + assert await res.text() == 'Hello, world' + await server.close() @pytest.mark.asyncio @@ -369,12 +368,11 @@ async def test_simple_get_ssl_no_valid(app, aiohttp_server, ssl_context): """Test simple get with https no valid.""" server = await aiohttp_server(app, ssl=ssl_context) url = 'https://localhost:%d' % server.port - client = aiosonic.HTTPClient() + async with aiosonic.HTTPClient() as client: - # python 3.5 compatibility - with pytest.raises(getattr(ssl, 'SSLCertVerificationError', ssl.SSLError)): - await client.get(url) - await server.close() + with pytest.raises(ssl.SSLError): + await client.get(url) + await server.close() @pytest.mark.asyncio @@ -383,17 +381,17 @@ async def test_get_chunked_response(app, aiohttp_server): server = await aiohttp_server(app) url = 'http://localhost:%d/chunked' % server.port - client = aiosonic.HTTPClient() - res = await client.get(url) - assert res.connection - assert res.status_code == 200 + async with aiosonic.HTTPClient() as client: + res = await client.get(url) + assert res.connection + assert res.status_code == 200 - chunks = [b'foo', b'bar'] + chunks = [b'foo', b'bar'] - async for chunk in res.read_chunks(): - assert chunk in chunks - assert await res.text() == '' # chunks already readed manually - await server.close() + async for chunk in res.read_chunks(): + assert chunk in chunks + assert await res.text() == '' # chunks already readed manually + await server.close() @pytest.mark.asyncio @@ -402,13 +400,13 @@ async def test_read_chunks_by_text_method(app, aiohttp_server): server = await aiohttp_server(app) url = 'http://localhost:%d/chunked' % server.port - client = aiosonic.HTTPClient() - res = await client.get(url) - assert res.connection - assert res.status_code == 200 - assert await res.text() == 'foobar' - assert await res.text() == 'foobar' # cached body in response object - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.get(url) + assert res.connection + assert res.status_code == 200 + assert await res.text() == 'foobar' + assert await res.text() == 'foobar' # cached body in response object + await server.close() @pytest.mark.asyncio @@ -417,13 +415,13 @@ async def test_get_body_gzip(app, aiohttp_server): server = await aiohttp_server(app) url = 'http://localhost:%d/gzip' % server.port - client = aiosonic.HTTPClient() - res = await client.get(url, - headers={'Accept-Encoding': 'gzip, deflate, br'}) - content = await res.content() - assert res.status_code == 200 - assert content == b'Hello, world' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, + headers={'Accept-Encoding': 'gzip, deflate, br'}) + content = await res.content() + assert res.status_code == 200 + assert content == b'Hello, world' + await server.close() @pytest.mark.asyncio @@ -432,13 +430,13 @@ async def test_get_body_deflate(app, aiohttp_server): server = await aiohttp_server(app) url = 'http://localhost:%d/deflate' % server.port - client = aiosonic.HTTPClient() - res = await client.get(url, - headers=[('Accept-Encoding', 'gzip, deflate, br')]) - content = await res.content() - assert res.status_code == 200 - assert content == b'Hello, world' - await server.close() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, + headers=[('Accept-Encoding', 'gzip, deflate, br')]) + content = await res.content() + assert res.status_code == 200 + assert content == b'Hello, world' + await server.close() @pytest.mark.asyncio @@ -446,25 +444,25 @@ async def test_post_chunked(app, aiohttp_server): """Test post chunked.""" server = await aiohttp_server(app) url = 'http://localhost:%d/post' % server.port - client = aiosonic.HTTPClient() + async with aiosonic.HTTPClient() as client: - async def data(): - yield b'foo' - yield b'bar' + async def data(): + yield b'foo' + yield b'bar' - res = await client.post(url, data=data()) - assert res.status_code == 200 - assert await res.text() == 'foobar' + res = await client.post(url, data=data()) + assert res.status_code == 200 + assert await res.text() == 'foobar' - def data(): - yield b'foo' - yield b'bar' - yield b'a' * 14 + def data(): + yield b'foo' + yield b'bar' + yield b'a' * 14 - res = await client.post(url, data=data()) - assert res.status_code == 200 - assert await res.text() == 'foobaraaaaaaaaaaaaaa' - await server.close() + res = await client.post(url, data=data()) + assert res.status_code == 200 + assert await res.text() == 'foobaraaaaaaaaaaaaaa' + await server.close() @pytest.mark.asyncio @@ -474,29 +472,29 @@ async def test_close_connection(app, aiohttp_server): url = 'http://localhost:%d/post' % server.port connector = TCPConnector(pool_size=1, connection_cls=MyConnection) - client = aiosonic.HTTPClient(connector) + async with aiosonic.HTTPClient(connector) as client: - res = await client.post(url, data=b'close') - connection = await connector.pool.acquire() + res = await client.post(url, data=b'close') + async with await connector.pool.acquire() as connection: - assert res.status_code == 200 - assert not connection.keep - assert await res.text() == 'close' + assert res.status_code == 200 + assert not connection.keep + assert await res.text() == 'close' @pytest.mark.asyncio async def test_cache(app, aiohttp_server): """Test simple get.""" server = await aiohttp_server(app) - client = aiosonic.HTTPClient() + async with aiosonic.HTTPClient() as client: - for time in range(520): - url = 'http://localhost:%d/%d' % (server.port, time) + for time in range(520): + url = 'http://localhost:%d/%d' % (server.port, time) - await client.get(url, headers={'Accept-Encoding': 'gzip, deflate, br'}) - assert len(_get_url_parsed.cache) == 512 - assert next(iter(_get_url_parsed.cache)) == url.replace('/519', '/8') - await server.close() + await client.get(url, headers={'Accept-Encoding': 'gzip, deflate, br'}) + assert len(_get_url_parsed.cache) == 512 + assert next(iter(_get_url_parsed.cache)) == url.replace('/519', '/8') + await server.close() @pytest.mark.asyncio @@ -507,22 +505,21 @@ async def test_close_old_keeped_conn(app, aiohttp_server): url1 = 'http://localhost:%d' % server1.port url2 = 'http://localhost:%d' % server2.port connector = TCPConnector(pool_size=1, connection_cls=MyConnection) - client = aiosonic.HTTPClient(connector) + async with aiosonic.HTTPClient(connector) as client: - await client.get(url1) - # get used writer - connection = await connector.pool.acquire() - writer = connection.writer - connection = connector.pool.release(connection) + await client.get(url1) + # get used writer + async with await connector.pool.acquire() as connection: + writer = connection.writer - await client.get(url2) - # python 3.6 doesn't have writer.is_closing - is_closing = getattr(writer, 'is_closing', writer._transport.is_closing) + await client.get(url2) + # python 3.6 doesn't have writer.is_closing + is_closing = getattr(writer, 'is_closing', writer._transport.is_closing) - # check that old writer is closed - assert is_closing() - await server1.close() - await server2.close() + # check that old writer is closed + assert is_closing() + await server1.close() + await server2.close() @pytest.mark.asyncio @@ -531,20 +528,20 @@ async def test_get_redirect(app, aiohttp_server): server = await aiohttp_server(app) url = 'http://localhost:%d/get_redirect' % server.port - client = aiosonic.HTTPClient() - res = await client.get(url) - assert res.status_code == 302 + async with aiosonic.HTTPClient() as client: + res = await client.get(url) + assert res.status_code == 302 - res = await client.get(url, follow=True) - assert res.status_code == 200 - assert await res.content() == b'Hello, world' - assert await res.text() == 'Hello, world' + res = await client.get(url, follow=True) + assert res.status_code == 200 + assert await res.content() == b'Hello, world' + assert await res.text() == 'Hello, world' - url = 'http://localhost:%d/get_redirect_full' % server.port - res = await client.get(url, follow=True) - assert res.status_code == 200 + url = 'http://localhost:%d/get_redirect_full' % server.port + res = await client.get(url, follow=True) + assert res.status_code == 200 - await server.close() + await server.close() @pytest.mark.asyncio @@ -552,11 +549,11 @@ async def test_max_redirects(app, aiohttp_server): """Test simple get.""" server = await aiohttp_server(app) url = 'http://localhost:%d/max_redirects' % server.port - client = aiosonic.HTTPClient() + async with aiosonic.HTTPClient() as client: - with pytest.raises(MaxRedirects): - await client.get(url, follow=True) - await server.close() + with pytest.raises(MaxRedirects): + await client.get(url, follow=True) + await server.close() def test_parse_response_line(): @@ -623,18 +620,18 @@ async def connect(*args, **kwargs): connector.release.return_value = asyncio.Future() connector.release.return_value.set_result(True) - client = aiosonic.HTTPClient() + async with aiosonic.HTTPClient() as client: - with pytest.raises(ConnectionError): - await client.get('foo') + with pytest.raises(ConnectionError): + await client.get('foo') @pytest.mark.asyncio async def test_request_multipart_value_error(): """Connection error check.""" - client = aiosonic.HTTPClient() - with pytest.raises(ValueError): - await client.post('foo', data=b'foo', multipart=True) + async with aiosonic.HTTPClient() as client: + with pytest.raises(ValueError): + await client.post('foo', data=b'foo', multipart=True) def test_encoding_from_header(): @@ -688,21 +685,21 @@ async def test_get_no_hostname(app, aiohttp_server): """Test simple get.""" server = await aiohttp_server(app) url = 'http://:%d' % server.port - client = aiosonic.HTTPClient() + async with aiosonic.HTTPClient() as client: - with pytest.raises(HttpParsingError): - await client.get(url) + with pytest.raises(HttpParsingError): + await client.get(url) @pytest.mark.asyncio async def test_wait_connections_empty(mocker): """Test simple get.""" - client = aiosonic.HTTPClient() - assert await client.wait_requests() + async with aiosonic.HTTPClient() as client: + assert await client.wait_requests() connector = TCPConnector(pool_cls=CyclicQueuePool) - client = aiosonic.HTTPClient(connector) - assert await client.wait_requests() + async with aiosonic.HTTPClient(connector) as client: + assert await client.wait_requests() @pytest.mark.asyncio @@ -716,12 +713,12 @@ async def long_connect(*_args, **_kwargs): new=long_connect) _connect.return_value = long_connect() - client = aiosonic.HTTPClient() - assert not await client.wait_requests(0) + async with aiosonic.HTTPClient() as client: + assert not await client.wait_requests(0) connector = TCPConnector(pool_cls=CyclicQueuePool) - client = aiosonic.HTTPClient(connector) - assert not await client.wait_requests(0) + async with aiosonic.HTTPClient(connector) as client: + assert not await client.wait_requests(0) @pytest.mark.asyncio @@ -730,12 +727,12 @@ async def test_get_image(http2_serv): """Test get image.""" url = http2_serv + 'sample.png' - client = aiosonic.HTTPClient() - res = await client.get(url, verify=False) - assert res.status_code == 200 - assert res.chunked - with open('tests/sample.png', 'rb') as _file: - assert (await res.content()) == _file.read() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, verify=False) + assert res.status_code == 200 + assert res.chunked + with open('tests/sample.png', 'rb') as _file: + assert (await res.content()) == _file.read() @pytest.mark.asyncio @@ -744,12 +741,12 @@ async def test_get_image_chunked(http2_serv): """Test get image chunked.""" url = http2_serv + 'sample.png' - client = aiosonic.HTTPClient() - res = await client.get(url, verify=False) - assert res.status_code == 200 - assert res.chunked - filebytes = b'' - async for chunk in res.read_chunks(): - filebytes += chunk - with open('tests/sample.png', 'rb') as _file: - assert filebytes == _file.read() + async with aiosonic.HTTPClient() as client: + res = await client.get(url, verify=False) + assert res.status_code == 200 + assert res.chunked + filebytes = b'' + async for chunk in res.read_chunks(): + filebytes += chunk + with open('tests/sample.png', 'rb') as _file: + assert filebytes == _file.read()