dh binary --with mkdocs,python3 --buildsystem=pybuild dh_update_autotools_config -O--buildsystem=pybuild dh_autoreconf -O--buildsystem=pybuild dh_auto_configure -O--buildsystem=pybuild running config debian/rules override_dh_auto_build make[1]: Entering directory '/build/python-uvicorn-0.15.0' dh_auto_build running build running build_py running egg_info writing uvicorn.egg-info/PKG-INFO writing dependency_links to uvicorn.egg-info/dependency_links.txt writing entry points to uvicorn.egg-info/entry_points.txt writing requirements to uvicorn.egg-info/requires.txt writing top-level names to uvicorn.egg-info/top_level.txt reading manifest file 'uvicorn.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' adding license file 'LICENSE.md' writing manifest file 'uvicorn.egg-info/SOURCES.txt' LC_ALL=C.UTF-8 LANG=C.UTF-8 mkdocs build && mv site html make[1]: Leaving directory '/build/python-uvicorn-0.15.0' debian/rules override_dh_auto_test make[1]: Entering directory '/build/python-uvicorn-0.15.0' http_proxy= https_proxy= dh_auto_test ============================= test session starts ============================== platform linux -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-0.13.0 rootdir: /build/python-uvicorn-0.15.0, configfile: setup.cfg plugins: anyio-3.3.4, mock-3.6.1, asyncio-0.15.1 collected 348 items / 24 deselected / 324 selected tests/test_auto_detection.py ... [ 0%] tests/test_cli.py . [ 1%] tests/test_config.py ............................................... [ 15%] tests/test_lifespan.py ............... [ 20%] tests/test_main.py F [ 20%] tests/importer/test_importer.py ...... [ 22%] tests/middleware/test_debug.py .... [ 23%] tests/middleware/test_logging.py FFFFFF [ 25%] tests/middleware/test_message_logger.py .. [ 26%] tests/middleware/test_proxy_headers.py ........... [ 29%] tests/middleware/test_wsgi.py ..... [ 31%] tests/protocols/test_http.py ........................................... [ 44%] ..............................F.............. [ 58%] tests/protocols/test_utils.py ...... [ 60%] tests/protocols/test_websocket.py FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF [ 71%] FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF [ 92%] tests/supervisors/test_multiprocess.py . [ 92%] tests/supervisors/test_reload.py ........................ [100%] =================================== FAILURES =================================== ___________________________ test_return_close_header ___________________________ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: > yield /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:62: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): ( status_code, headers, byte_stream, extensions, > ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:276: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'connection', b'close'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: if not url[0]: raise UnsupportedProtocol( "Request URL missing either an 'http://' or 'https://' protocol." ) if url[0] not in (b"http", b"https"): protocol = url[0].decode("ascii") raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{protocol}://'." ) if not url[1]: raise LocalProtocolError("Missing hostname in URL.") origin = url_to_origin(url) timeout = cast(TimeoutDict, extensions.get("timeout", {})) await self._keepalive_sweep() connection: Optional[AsyncHTTPConnection] = None while connection is None: async with self._connection_acquiry_lock: # We get-or-create a connection as an atomic operation, to ensure # that HTTP/2 requests issued in close concurrency will end up # on the same connection. logger.trace("get_connection_from_pool=%r", origin) connection = await self._get_connection_from_pool(origin) if connection is None: connection = self._create_connection(origin=origin) logger.trace("created connection=%r", connection) await self._add_to_pool(connection, timeout=timeout) else: logger.trace("reuse connection=%r", connection) try: > response = await connection.handle_async_request( method, url, headers=headers, stream=stream, extensions=extensions ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection_pool.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'connection', b'close'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: assert url_to_origin(url) == self.origin timeout = cast(TimeoutDict, extensions.get("timeout", {})) async with self.request_lock: if self.connection is None: if self._connect_failed: raise NewConnectionRequired() if not self.socket: logger.trace( "open_socket origin=%r timeout=%r", self.origin, timeout ) > self.socket = await self._open_socket(timeout) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:136: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def _open_socket(self, timeout: TimeoutDict = None) -> AsyncSocketStream: scheme, hostname, port = self.origin timeout = {} if timeout is None else timeout ssl_context = self._ssl_context if scheme == b"https" else None retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) while True: try: if self._uds is None: > return await self._backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=self._local_address, ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:163: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: > return await self.backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=local_address ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/auto.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: connect_timeout = timeout.get("connect") unicode_host = hostname.decode("utf-8") exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(connect_timeout): stream: anyio.abc.ByteStream stream = await anyio.connect_tcp( unicode_host, port, local_host=local_address ) if ssl_context: > stream = await TLSStream.wrap( stream, hostname=unicode_host, ssl_context=ssl_context, standard_compatible=False, ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/anyio.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = , value = OSError('All connection attempts failed') traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ map = {: , : , : } @contextlib.contextmanager def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): > raise to_exc(exc) from None E httpcore.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpcore/_exceptions.py:12: ConnectError The above exception was the direct cause of the following exception: config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @pytest.mark.asyncio async def test_return_close_header(): config = Config(app=app, host="localhost", loop="asyncio", limit_max_requests=1) async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get( "http://127.0.0.1:8000", headers={"connection": "close"} ) tests/test_main.py:19: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = url = 'http://127.0.0.1:8000' async def get( self, url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1704: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = 'GET' url = 'http://127.0.0.1:8000' async def request( self, method: str, url: URLTypes, *, content: RequestContent = None, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Build and send a request. Equivalent to: ```python request = client.build_request(...) response = await client.send(request, ...) ``` See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration. [0]: /advanced/#merging-of-configuration """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, ) > response = await self.send( request, auth=auth, follow_redirects=follow_redirects ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1483: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request. The request is sent as-is, unmodified. Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well. See also: [Request instances][0] [0]: /advanced/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.") self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects ) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1571: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , follow_redirects = False history = [] async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__() while True: > response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1599: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = , follow_redirects = False history = [] async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) for hook in self._event_hooks["request"]: await hook(request) > response = await self._send_single_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1636: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." ) with request_context(request=request): > response = await transport.handle_async_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1673: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): > ( status_code, headers, byte_stream, extensions, ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:271: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = value = ConnectError(OSError('All connection attempts failed')) traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: yield except Exception as exc: mapped_exc = None for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc if mapped_exc is None: # pragma: nocover raise message = str(exc) > raise mapped_exc(message) from exc E httpx.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:79: ConnectError During handling of the above exception, another exception occurred: @pytest.mark.asyncio async def test_return_close_header(): config = Config(app=app, host="localhost", loop="asyncio", limit_max_requests=1) async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get( "http://127.0.0.1:8000", headers={"connection": "close"} ) tests/test_main.py:19: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:on.py:45 Waiting for application startup. INFO uvicorn.error:on.py:92 ASGI 'lifespan' protocol appears unsupported. INFO uvicorn.error:on.py:59 Application startup complete. INFO uvicorn.error:server.py:263 Shutting down __________________________ test_access_logging[True] ___________________________ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: > yield /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:62: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): ( status_code, headers, byte_stream, extensions, > ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:276: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: if not url[0]: raise UnsupportedProtocol( "Request URL missing either an 'http://' or 'https://' protocol." ) if url[0] not in (b"http", b"https"): protocol = url[0].decode("ascii") raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{protocol}://'." ) if not url[1]: raise LocalProtocolError("Missing hostname in URL.") origin = url_to_origin(url) timeout = cast(TimeoutDict, extensions.get("timeout", {})) await self._keepalive_sweep() connection: Optional[AsyncHTTPConnection] = None while connection is None: async with self._connection_acquiry_lock: # We get-or-create a connection as an atomic operation, to ensure # that HTTP/2 requests issued in close concurrency will end up # on the same connection. logger.trace("get_connection_from_pool=%r", origin) connection = await self._get_connection_from_pool(origin) if connection is None: connection = self._create_connection(origin=origin) logger.trace("created connection=%r", connection) await self._add_to_pool(connection, timeout=timeout) else: logger.trace("reuse connection=%r", connection) try: > response = await connection.handle_async_request( method, url, headers=headers, stream=stream, extensions=extensions ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection_pool.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: assert url_to_origin(url) == self.origin timeout = cast(TimeoutDict, extensions.get("timeout", {})) async with self.request_lock: if self.connection is None: if self._connect_failed: raise NewConnectionRequired() if not self.socket: logger.trace( "open_socket origin=%r timeout=%r", self.origin, timeout ) > self.socket = await self._open_socket(timeout) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:136: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def _open_socket(self, timeout: TimeoutDict = None) -> AsyncSocketStream: scheme, hostname, port = self.origin timeout = {} if timeout is None else timeout ssl_context = self._ssl_context if scheme == b"https" else None retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) while True: try: if self._uds is None: > return await self._backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=self._local_address, ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:163: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: > return await self.backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=local_address ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/auto.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: connect_timeout = timeout.get("connect") unicode_host = hostname.decode("utf-8") exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(connect_timeout): stream: anyio.abc.ByteStream stream = await anyio.connect_tcp( unicode_host, port, local_host=local_address ) if ssl_context: > stream = await TLSStream.wrap( stream, hostname=unicode_host, ssl_context=ssl_context, standard_compatible=False, ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/anyio.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = , value = OSError('All connection attempts failed') traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ map = {: , : , : } @contextlib.contextmanager def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): > raise to_exc(exc) from None E httpcore.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpcore/_exceptions.py:12: ConnectError The above exception was the direct cause of the following exception: config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ use_colors = True caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c240a790> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False), (None)]) async def test_access_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:105: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = url = 'http://127.0.0.1:8000' async def get( self, url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1704: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = 'GET' url = 'http://127.0.0.1:8000' async def request( self, method: str, url: URLTypes, *, content: RequestContent = None, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Build and send a request. Equivalent to: ```python request = client.build_request(...) response = await client.send(request, ...) ``` See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration. [0]: /advanced/#merging-of-configuration """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, ) > response = await self.send( request, auth=auth, follow_redirects=follow_redirects ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1483: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request. The request is sent as-is, unmodified. Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well. See also: [Request instances][0] [0]: /advanced/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.") self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects ) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1571: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , follow_redirects = False history = [] async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__() while True: > response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1599: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = , follow_redirects = False history = [] async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) for hook in self._event_hooks["request"]: await hook(request) > response = await self._send_single_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1636: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." ) with request_context(request=request): > response = await transport.handle_async_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1673: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): > ( status_code, headers, byte_stream, extensions, ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:271: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = value = ConnectError(OSError('All connection attempts failed')) traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: yield except Exception as exc: mapped_exc = None for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc if mapped_exc is None: # pragma: nocover raise message = str(exc) > raise mapped_exc(message) from exc E httpx.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:79: ConnectError During handling of the above exception, another exception occurred: use_colors = True caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c240a790> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False), (None)]) async def test_access_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:105: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:on.py:45 Waiting for application startup. INFO uvicorn.error:on.py:92 ASGI 'lifespan' protocol appears unsupported. INFO uvicorn.error:on.py:59 Application startup complete. INFO uvicorn.error:server.py:263 Shutting down __________________________ test_access_logging[False] __________________________ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: > yield /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:62: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): ( status_code, headers, byte_stream, extensions, > ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:276: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: if not url[0]: raise UnsupportedProtocol( "Request URL missing either an 'http://' or 'https://' protocol." ) if url[0] not in (b"http", b"https"): protocol = url[0].decode("ascii") raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{protocol}://'." ) if not url[1]: raise LocalProtocolError("Missing hostname in URL.") origin = url_to_origin(url) timeout = cast(TimeoutDict, extensions.get("timeout", {})) await self._keepalive_sweep() connection: Optional[AsyncHTTPConnection] = None while connection is None: async with self._connection_acquiry_lock: # We get-or-create a connection as an atomic operation, to ensure # that HTTP/2 requests issued in close concurrency will end up # on the same connection. logger.trace("get_connection_from_pool=%r", origin) connection = await self._get_connection_from_pool(origin) if connection is None: connection = self._create_connection(origin=origin) logger.trace("created connection=%r", connection) await self._add_to_pool(connection, timeout=timeout) else: logger.trace("reuse connection=%r", connection) try: > response = await connection.handle_async_request( method, url, headers=headers, stream=stream, extensions=extensions ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection_pool.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: assert url_to_origin(url) == self.origin timeout = cast(TimeoutDict, extensions.get("timeout", {})) async with self.request_lock: if self.connection is None: if self._connect_failed: raise NewConnectionRequired() if not self.socket: logger.trace( "open_socket origin=%r timeout=%r", self.origin, timeout ) > self.socket = await self._open_socket(timeout) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:136: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def _open_socket(self, timeout: TimeoutDict = None) -> AsyncSocketStream: scheme, hostname, port = self.origin timeout = {} if timeout is None else timeout ssl_context = self._ssl_context if scheme == b"https" else None retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) while True: try: if self._uds is None: > return await self._backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=self._local_address, ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:163: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: > return await self.backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=local_address ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/auto.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: connect_timeout = timeout.get("connect") unicode_host = hostname.decode("utf-8") exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(connect_timeout): stream: anyio.abc.ByteStream stream = await anyio.connect_tcp( unicode_host, port, local_host=local_address ) if ssl_context: > stream = await TLSStream.wrap( stream, hostname=unicode_host, ssl_context=ssl_context, standard_compatible=False, ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/anyio.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = , value = OSError('All connection attempts failed') traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ map = {: , : , : } @contextlib.contextmanager def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): > raise to_exc(exc) from None E httpcore.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpcore/_exceptions.py:12: ConnectError The above exception was the direct cause of the following exception: config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ use_colors = False caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c2151370> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False), (None)]) async def test_access_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:105: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = url = 'http://127.0.0.1:8000' async def get( self, url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1704: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = 'GET' url = 'http://127.0.0.1:8000' async def request( self, method: str, url: URLTypes, *, content: RequestContent = None, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Build and send a request. Equivalent to: ```python request = client.build_request(...) response = await client.send(request, ...) ``` See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration. [0]: /advanced/#merging-of-configuration """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, ) > response = await self.send( request, auth=auth, follow_redirects=follow_redirects ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1483: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request. The request is sent as-is, unmodified. Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well. See also: [Request instances][0] [0]: /advanced/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.") self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects ) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1571: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , follow_redirects = False history = [] async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__() while True: > response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1599: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = , follow_redirects = False history = [] async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) for hook in self._event_hooks["request"]: await hook(request) > response = await self._send_single_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1636: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." ) with request_context(request=request): > response = await transport.handle_async_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1673: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): > ( status_code, headers, byte_stream, extensions, ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:271: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = value = ConnectError(OSError('All connection attempts failed')) traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: yield except Exception as exc: mapped_exc = None for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc if mapped_exc is None: # pragma: nocover raise message = str(exc) > raise mapped_exc(message) from exc E httpx.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:79: ConnectError During handling of the above exception, another exception occurred: use_colors = False caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c2151370> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False), (None)]) async def test_access_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:105: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:on.py:45 Waiting for application startup. INFO uvicorn.error:on.py:92 ASGI 'lifespan' protocol appears unsupported. INFO uvicorn.error:on.py:59 Application startup complete. INFO uvicorn.error:server.py:263 Shutting down __________________________ test_access_logging[None] ___________________________ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: > yield /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:62: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): ( status_code, headers, byte_stream, extensions, > ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:276: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: if not url[0]: raise UnsupportedProtocol( "Request URL missing either an 'http://' or 'https://' protocol." ) if url[0] not in (b"http", b"https"): protocol = url[0].decode("ascii") raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{protocol}://'." ) if not url[1]: raise LocalProtocolError("Missing hostname in URL.") origin = url_to_origin(url) timeout = cast(TimeoutDict, extensions.get("timeout", {})) await self._keepalive_sweep() connection: Optional[AsyncHTTPConnection] = None while connection is None: async with self._connection_acquiry_lock: # We get-or-create a connection as an atomic operation, to ensure # that HTTP/2 requests issued in close concurrency will end up # on the same connection. logger.trace("get_connection_from_pool=%r", origin) connection = await self._get_connection_from_pool(origin) if connection is None: connection = self._create_connection(origin=origin) logger.trace("created connection=%r", connection) await self._add_to_pool(connection, timeout=timeout) else: logger.trace("reuse connection=%r", connection) try: > response = await connection.handle_async_request( method, url, headers=headers, stream=stream, extensions=extensions ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection_pool.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: assert url_to_origin(url) == self.origin timeout = cast(TimeoutDict, extensions.get("timeout", {})) async with self.request_lock: if self.connection is None: if self._connect_failed: raise NewConnectionRequired() if not self.socket: logger.trace( "open_socket origin=%r timeout=%r", self.origin, timeout ) > self.socket = await self._open_socket(timeout) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:136: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def _open_socket(self, timeout: TimeoutDict = None) -> AsyncSocketStream: scheme, hostname, port = self.origin timeout = {} if timeout is None else timeout ssl_context = self._ssl_context if scheme == b"https" else None retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) while True: try: if self._uds is None: > return await self._backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=self._local_address, ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:163: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: > return await self.backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=local_address ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/auto.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: connect_timeout = timeout.get("connect") unicode_host = hostname.decode("utf-8") exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(connect_timeout): stream: anyio.abc.ByteStream stream = await anyio.connect_tcp( unicode_host, port, local_host=local_address ) if ssl_context: > stream = await TLSStream.wrap( stream, hostname=unicode_host, ssl_context=ssl_context, standard_compatible=False, ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/anyio.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = , value = OSError('All connection attempts failed') traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ map = {: , : , : } @contextlib.contextmanager def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): > raise to_exc(exc) from None E httpcore.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpcore/_exceptions.py:12: ConnectError The above exception was the direct cause of the following exception: config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ use_colors = None caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c2334820> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False), (None)]) async def test_access_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:105: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = url = 'http://127.0.0.1:8000' async def get( self, url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1704: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = 'GET' url = 'http://127.0.0.1:8000' async def request( self, method: str, url: URLTypes, *, content: RequestContent = None, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Build and send a request. Equivalent to: ```python request = client.build_request(...) response = await client.send(request, ...) ``` See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration. [0]: /advanced/#merging-of-configuration """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, ) > response = await self.send( request, auth=auth, follow_redirects=follow_redirects ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1483: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request. The request is sent as-is, unmodified. Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well. See also: [Request instances][0] [0]: /advanced/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.") self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects ) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1571: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , follow_redirects = False history = [] async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__() while True: > response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1599: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = , follow_redirects = False history = [] async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) for hook in self._event_hooks["request"]: await hook(request) > response = await self._send_single_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1636: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." ) with request_context(request=request): > response = await transport.handle_async_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1673: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): > ( status_code, headers, byte_stream, extensions, ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:271: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = value = ConnectError(OSError('All connection attempts failed')) traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: yield except Exception as exc: mapped_exc = None for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc if mapped_exc is None: # pragma: nocover raise message = str(exc) > raise mapped_exc(message) from exc E httpx.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:79: ConnectError During handling of the above exception, another exception occurred: use_colors = None caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c2334820> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False), (None)]) async def test_access_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:105: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:on.py:45 Waiting for application startup. INFO uvicorn.error:on.py:92 ASGI 'lifespan' protocol appears unsupported. INFO uvicorn.error:on.py:59 Application startup complete. INFO uvicorn.error:server.py:263 Shutting down __________________________ test_default_logging[True] __________________________ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: > yield /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:62: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): ( status_code, headers, byte_stream, extensions, > ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:276: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: if not url[0]: raise UnsupportedProtocol( "Request URL missing either an 'http://' or 'https://' protocol." ) if url[0] not in (b"http", b"https"): protocol = url[0].decode("ascii") raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{protocol}://'." ) if not url[1]: raise LocalProtocolError("Missing hostname in URL.") origin = url_to_origin(url) timeout = cast(TimeoutDict, extensions.get("timeout", {})) await self._keepalive_sweep() connection: Optional[AsyncHTTPConnection] = None while connection is None: async with self._connection_acquiry_lock: # We get-or-create a connection as an atomic operation, to ensure # that HTTP/2 requests issued in close concurrency will end up # on the same connection. logger.trace("get_connection_from_pool=%r", origin) connection = await self._get_connection_from_pool(origin) if connection is None: connection = self._create_connection(origin=origin) logger.trace("created connection=%r", connection) await self._add_to_pool(connection, timeout=timeout) else: logger.trace("reuse connection=%r", connection) try: > response = await connection.handle_async_request( method, url, headers=headers, stream=stream, extensions=extensions ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection_pool.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: assert url_to_origin(url) == self.origin timeout = cast(TimeoutDict, extensions.get("timeout", {})) async with self.request_lock: if self.connection is None: if self._connect_failed: raise NewConnectionRequired() if not self.socket: logger.trace( "open_socket origin=%r timeout=%r", self.origin, timeout ) > self.socket = await self._open_socket(timeout) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:136: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def _open_socket(self, timeout: TimeoutDict = None) -> AsyncSocketStream: scheme, hostname, port = self.origin timeout = {} if timeout is None else timeout ssl_context = self._ssl_context if scheme == b"https" else None retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) while True: try: if self._uds is None: > return await self._backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=self._local_address, ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:163: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: > return await self.backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=local_address ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/auto.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: connect_timeout = timeout.get("connect") unicode_host = hostname.decode("utf-8") exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(connect_timeout): stream: anyio.abc.ByteStream stream = await anyio.connect_tcp( unicode_host, port, local_host=local_address ) if ssl_context: > stream = await TLSStream.wrap( stream, hostname=unicode_host, ssl_context=ssl_context, standard_compatible=False, ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/anyio.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = , value = OSError('All connection attempts failed') traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ map = {: , : , : } @contextlib.contextmanager def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): > raise to_exc(exc) from None E httpcore.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpcore/_exceptions.py:12: ConnectError The above exception was the direct cause of the following exception: config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ use_colors = True caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c260c1c0> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False)]) async def test_default_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:123: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = url = 'http://127.0.0.1:8000' async def get( self, url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1704: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = 'GET' url = 'http://127.0.0.1:8000' async def request( self, method: str, url: URLTypes, *, content: RequestContent = None, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Build and send a request. Equivalent to: ```python request = client.build_request(...) response = await client.send(request, ...) ``` See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration. [0]: /advanced/#merging-of-configuration """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, ) > response = await self.send( request, auth=auth, follow_redirects=follow_redirects ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1483: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request. The request is sent as-is, unmodified. Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well. See also: [Request instances][0] [0]: /advanced/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.") self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects ) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1571: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , follow_redirects = False history = [] async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__() while True: > response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1599: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = , follow_redirects = False history = [] async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) for hook in self._event_hooks["request"]: await hook(request) > response = await self._send_single_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1636: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." ) with request_context(request=request): > response = await transport.handle_async_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1673: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): > ( status_code, headers, byte_stream, extensions, ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:271: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = value = ConnectError(OSError('All connection attempts failed')) traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: yield except Exception as exc: mapped_exc = None for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc if mapped_exc is None: # pragma: nocover raise message = str(exc) > raise mapped_exc(message) from exc E httpx.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:79: ConnectError During handling of the above exception, another exception occurred: use_colors = True caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c260c1c0> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False)]) async def test_default_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:123: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:on.py:45 Waiting for application startup. INFO uvicorn.error:on.py:92 ASGI 'lifespan' protocol appears unsupported. INFO uvicorn.error:on.py:59 Application startup complete. INFO uvicorn.error:server.py:263 Shutting down _________________________ test_default_logging[False] __________________________ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: > yield /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:62: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): ( status_code, headers, byte_stream, extensions, > ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:276: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: if not url[0]: raise UnsupportedProtocol( "Request URL missing either an 'http://' or 'https://' protocol." ) if url[0] not in (b"http", b"https"): protocol = url[0].decode("ascii") raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{protocol}://'." ) if not url[1]: raise LocalProtocolError("Missing hostname in URL.") origin = url_to_origin(url) timeout = cast(TimeoutDict, extensions.get("timeout", {})) await self._keepalive_sweep() connection: Optional[AsyncHTTPConnection] = None while connection is None: async with self._connection_acquiry_lock: # We get-or-create a connection as an atomic operation, to ensure # that HTTP/2 requests issued in close concurrency will end up # on the same connection. logger.trace("get_connection_from_pool=%r", origin) connection = await self._get_connection_from_pool(origin) if connection is None: connection = self._create_connection(origin=origin) logger.trace("created connection=%r", connection) await self._add_to_pool(connection, timeout=timeout) else: logger.trace("reuse connection=%r", connection) try: > response = await connection.handle_async_request( method, url, headers=headers, stream=stream, extensions=extensions ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection_pool.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: assert url_to_origin(url) == self.origin timeout = cast(TimeoutDict, extensions.get("timeout", {})) async with self.request_lock: if self.connection is None: if self._connect_failed: raise NewConnectionRequired() if not self.socket: logger.trace( "open_socket origin=%r timeout=%r", self.origin, timeout ) > self.socket = await self._open_socket(timeout) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:136: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def _open_socket(self, timeout: TimeoutDict = None) -> AsyncSocketStream: scheme, hostname, port = self.origin timeout = {} if timeout is None else timeout ssl_context = self._ssl_context if scheme == b"https" else None retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) while True: try: if self._uds is None: > return await self._backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=self._local_address, ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:163: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: > return await self.backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=local_address ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/auto.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: connect_timeout = timeout.get("connect") unicode_host = hostname.decode("utf-8") exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(connect_timeout): stream: anyio.abc.ByteStream stream = await anyio.connect_tcp( unicode_host, port, local_host=local_address ) if ssl_context: > stream = await TLSStream.wrap( stream, hostname=unicode_host, ssl_context=ssl_context, standard_compatible=False, ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/anyio.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = , value = OSError('All connection attempts failed') traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ map = {: , : , : } @contextlib.contextmanager def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): > raise to_exc(exc) from None E httpcore.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpcore/_exceptions.py:12: ConnectError The above exception was the direct cause of the following exception: config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ use_colors = False caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c2348400> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False)]) async def test_default_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:123: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = url = 'http://127.0.0.1:8000' async def get( self, url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1704: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = 'GET' url = 'http://127.0.0.1:8000' async def request( self, method: str, url: URLTypes, *, content: RequestContent = None, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Build and send a request. Equivalent to: ```python request = client.build_request(...) response = await client.send(request, ...) ``` See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration. [0]: /advanced/#merging-of-configuration """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, ) > response = await self.send( request, auth=auth, follow_redirects=follow_redirects ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1483: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request. The request is sent as-is, unmodified. Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well. See also: [Request instances][0] [0]: /advanced/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.") self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects ) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1571: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , follow_redirects = False history = [] async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__() while True: > response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1599: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = , follow_redirects = False history = [] async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) for hook in self._event_hooks["request"]: await hook(request) > response = await self._send_single_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1636: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." ) with request_context(request=request): > response = await transport.handle_async_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1673: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): > ( status_code, headers, byte_stream, extensions, ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:271: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = value = ConnectError(OSError('All connection attempts failed')) traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: yield except Exception as exc: mapped_exc = None for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc if mapped_exc is None: # pragma: nocover raise message = str(exc) > raise mapped_exc(message) from exc E httpx.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:79: ConnectError During handling of the above exception, another exception occurred: use_colors = False caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c2348400> @pytest.mark.asyncio @pytest.mark.parametrize("use_colors", [(True), (False)]) async def test_default_logging(use_colors, caplog): config = Config(app=app, use_colors=use_colors) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:123: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:on.py:45 Waiting for application startup. INFO uvicorn.error:on.py:92 ASGI 'lifespan' protocol appears unsupported. INFO uvicorn.error:on.py:59 Application startup complete. INFO uvicorn.error:server.py:263 Shutting down ___________________________ test_unknown_status_code ___________________________ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: > yield /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:62: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): ( status_code, headers, byte_stream, extensions, > ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:276: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: if not url[0]: raise UnsupportedProtocol( "Request URL missing either an 'http://' or 'https://' protocol." ) if url[0] not in (b"http", b"https"): protocol = url[0].decode("ascii") raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{protocol}://'." ) if not url[1]: raise LocalProtocolError("Missing hostname in URL.") origin = url_to_origin(url) timeout = cast(TimeoutDict, extensions.get("timeout", {})) await self._keepalive_sweep() connection: Optional[AsyncHTTPConnection] = None while connection is None: async with self._connection_acquiry_lock: # We get-or-create a connection as an atomic operation, to ensure # that HTTP/2 requests issued in close concurrency will end up # on the same connection. logger.trace("get_connection_from_pool=%r", origin) connection = await self._get_connection_from_pool(origin) if connection is None: connection = self._create_connection(origin=origin) logger.trace("created connection=%r", connection) await self._add_to_pool(connection, timeout=timeout) else: logger.trace("reuse connection=%r", connection) try: > response = await connection.handle_async_request( method, url, headers=headers, stream=stream, extensions=extensions ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection_pool.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'127.0.0.1', 8000, b'/') headers = [(b'Host', b'127.0.0.1:8000'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.20.0')] stream = extensions = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def handle_async_request( self, method: bytes, url: URL, headers: Headers, stream: AsyncByteStream, extensions: dict, ) -> Tuple[int, Headers, AsyncByteStream, dict]: assert url_to_origin(url) == self.origin timeout = cast(TimeoutDict, extensions.get("timeout", {})) async with self.request_lock: if self.connection is None: if self._connect_failed: raise NewConnectionRequired() if not self.socket: logger.trace( "open_socket origin=%r timeout=%r", self.origin, timeout ) > self.socket = await self._open_socket(timeout) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:136: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def _open_socket(self, timeout: TimeoutDict = None) -> AsyncSocketStream: scheme, hostname, port = self.origin timeout = {} if timeout is None else timeout ssl_context = self._ssl_context if scheme == b"https" else None retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) while True: try: if self._uds is None: > return await self._backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=self._local_address, ) /usr/local/lib/python3.9/dist-packages/httpcore/_async/connection.py:163: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: > return await self.backend.open_tcp_stream( hostname, port, ssl_context, timeout, local_address=local_address ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/auto.py:44: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = hostname = b'127.0.0.1', port = 8000, ssl_context = None timeout = {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0} async def open_tcp_stream( self, hostname: bytes, port: int, ssl_context: Optional[SSLContext], timeout: TimeoutDict, *, local_address: Optional[str], ) -> AsyncSocketStream: connect_timeout = timeout.get("connect") unicode_host = hostname.decode("utf-8") exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(connect_timeout): stream: anyio.abc.ByteStream stream = await anyio.connect_tcp( unicode_host, port, local_host=local_address ) if ssl_context: > stream = await TLSStream.wrap( stream, hostname=unicode_host, ssl_context=ssl_context, standard_compatible=False, ) /usr/local/lib/python3.9/dist-packages/httpcore/_backends/anyio.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = , value = OSError('All connection attempts failed') traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ map = {: , : , : } @contextlib.contextmanager def map_exceptions(map: Dict[Type[Exception], Type[Exception]]) -> Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): > raise to_exc(exc) from None E httpcore.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpcore/_exceptions.py:12: ConnectError The above exception was the direct cause of the following exception: config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c21ce8b0> @pytest.mark.asyncio async def test_unknown_status_code(caplog): async def app(scope, receive, send): assert scope["type"] == "http" await send({"type": "http.response.start", "status": 599, "headers": []}) await send({"type": "http.response.body", "body": b"", "more_body": False}) config = Config(app=app) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:148: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = url = 'http://127.0.0.1:8000' async def get( self, url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, follow_redirects=follow_redirects, timeout=timeout, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1704: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = 'GET' url = 'http://127.0.0.1:8000' async def request( self, method: str, url: URLTypes, *, content: RequestContent = None, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Build and send a request. Equivalent to: ```python request = client.build_request(...) response = await client.send(request, ...) ``` See `AsyncClient.build_request()`, `AsyncClient.send()` and [Merging of configuration][0] for how the various parameters are merged with client-level configuration. [0]: /advanced/#merging-of-configuration """ request = self.build_request( method=method, url=url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, timeout=timeout, ) > response = await self.send( request, auth=auth, follow_redirects=follow_redirects ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1483: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, ) -> Response: """ Send a request. The request is sent as-is, unmodified. Typically you'll want to build one with `AsyncClient.build_request()` so that any client-level configuration is merged into the request, but passing an explicit `httpx.Request()` is supported as well. See also: [Request instances][0] [0]: /advanced/#request-instances """ if self._state == ClientState.CLOSED: raise RuntimeError("Cannot send a request, as the client has been closed.") self._state = ClientState.OPENED follow_redirects = ( self.follow_redirects if isinstance(follow_redirects, UseClientDefault) else follow_redirects ) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, follow_redirects=follow_redirects, history=[], ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1571: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , follow_redirects = False history = [] async def _send_handling_auth( self, request: Request, auth: Auth, follow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) try: request = await auth_flow.__anext__() while True: > response = await self._send_handling_redirects( request, follow_redirects=follow_redirects, history=history, ) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1599: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = , follow_redirects = False history = [] async def _send_handling_redirects( self, request: Request, follow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) for hook in self._event_hooks["request"]: await hook(request) > response = await self._send_single_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1636: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def _send_single_request(self, request: Request) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() if not isinstance(request.stream, AsyncByteStream): raise RuntimeError( "Attempted to send an sync request with an AsyncClient instance." ) with request_context(request=request): > response = await transport.handle_async_request(request) /usr/local/lib/python3.9/dist-packages/httpx/_client.py:1673: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) with map_httpcore_exceptions(): > ( status_code, headers, byte_stream, extensions, ) = await self._pool.handle_async_request( method=request.method.encode("ascii"), url=request.url.raw, headers=request.headers.raw, stream=httpcore.AsyncIteratorByteStream(request.stream.__aiter__()), extensions=request.extensions, ) /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:271: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typ = value = ConnectError(OSError('All connection attempts failed')) traceback = def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: > self.gen.throw(typ, value, traceback) /usr/lib/python3.9/contextlib.py:137: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @contextlib.contextmanager def map_httpcore_exceptions() -> typing.Iterator[None]: try: yield except Exception as exc: mapped_exc = None for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): if not isinstance(exc, from_exc): continue # We want to map to the most specific exception we can find. # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. if mapped_exc is None or issubclass(to_exc, mapped_exc): mapped_exc = to_exc if mapped_exc is None: # pragma: nocover raise message = str(exc) > raise mapped_exc(message) from exc E httpx.ConnectError: All connection attempts failed /usr/local/lib/python3.9/dist-packages/httpx/_transports/default.py:79: ConnectError During handling of the above exception, another exception occurred: caplog = <_pytest.logging.LogCaptureFixture object at 0x7f07c21ce8b0> @pytest.mark.asyncio async def test_unknown_status_code(caplog): async def app(scope, receive, send): assert scope["type"] == "http" await send({"type": "http.response.start", "status": 599, "headers": []}) await send({"type": "http.response.body", "body": b"", "more_body": False}) config = Config(app=app) with caplog_for_logger(caplog, "uvicorn.access"): async with run_server(config): async with httpx.AsyncClient() as client: > response = await client.get("http://127.0.0.1:8000") tests/middleware/test_logging.py:148: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:on.py:45 Waiting for application startup. INFO uvicorn.error:on.py:92 ASGI 'lifespan' protocol appears unsupported. INFO uvicorn.error:on.py:59 Application startup complete. INFO uvicorn.error:server.py:263 Shutting down _____ test_100_continue_not_sent_when_body_not_consumed[HttpToolsProtocol] _____ cls = func = . at 0x7f07c225dd30> when = 'call' reraise = (, ) @classmethod def from_call( cls, func: "Callable[[], TResult]", when: "Literal['collect', 'setup', 'call', 'teardown']", reraise: Optional[ Union[Type[BaseException], Tuple[Type[BaseException], ...]] ] = None, ) -> "CallInfo[TResult]": excinfo = None start = timing.time() precise_start = timing.perf_counter() try: > result: Optional[TResult] = func() /usr/lib/python3/dist-packages/_pytest/runner.py:311: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/_pytest/runner.py:255: in lambda: ihook(item=item, **kwds), when=when, reraise=reraise /usr/lib/python3/dist-packages/pluggy/hooks.py:286: in __call__ return self._hookexec(self, self.get_hookimpls(), kwargs) /usr/lib/python3/dist-packages/pluggy/manager.py:92: in _hookexec return self._inner_hookexec(hook, methods, kwargs) /usr/lib/python3/dist-packages/pluggy/manager.py:83: in self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall( /usr/lib/python3/dist-packages/_pytest/unraisableexception.py:88: in pytest_runtest_call yield from unraisable_exception_runtest_hook() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def unraisable_exception_runtest_hook() -> Generator[None, None, None]: with catch_unraisable_exception() as cm: yield if cm.unraisable: if cm.unraisable.err_msg is not None: err_msg = cm.unraisable.err_msg else: err_msg = "Exception ignored in" msg = f"{err_msg}: {cm.unraisable.object!r}\n\n" msg += "".join( traceback.format_exception( cm.unraisable.exc_type, cm.unraisable.exc_value, cm.unraisable.exc_traceback, ) ) > warnings.warn(pytest.PytestUnraisableExceptionWarning(msg)) E pytest.PytestUnraisableExceptionWarning: Exception ignored in: E E Traceback (most recent call last): E File "/usr/lib/python3.9/warnings.py", line 506, in _warn_unawaited_coroutine E warn(msg, category=RuntimeWarning, stacklevel=2, source=coro) E RuntimeWarning: coroutine 'BaseEventLoop._create_server_getaddrinfo' was never awaited /usr/lib/python3/dist-packages/_pytest/unraisableexception.py:78: PytestUnraisableExceptionWarning ----------------------------- Captured stdout call ----------------------------- INFO: 127.0.0.1:8001 - "POST / HTTP/1.1" 204 No Content ------------------------------ Captured log call ------------------------------- ERROR asyncio:base_events.py:1738 Task exception was never retrieved future: exception=DeprecationWarning('The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.')> Traceback (most recent call last): File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 86, in serve await self.startup(sockets=sockets) File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 159, in startup server = await asyncio.start_server( File "/usr/lib/python3.9/asyncio/streams.py", line 94, in start_server return await loop.create_server(factory, host, port, **kwds) File "/usr/lib/python3.9/asyncio/base_events.py", line 1460, in create_server infos = await tasks.gather(*fs, loop=self) File "/usr/lib/python3.9/asyncio/tasks.py", line 755, in gather warnings.warn("The loop argument is deprecated since Python 3.8, " DeprecationWarning: The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10. ERROR asyncio:base_events.py:1738 Task exception was never retrieved future: exception=DeprecationWarning('The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.')> Traceback (most recent call last): File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 86, in serve await self.startup(sockets=sockets) File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 159, in startup server = await asyncio.start_server( File "/usr/lib/python3.9/asyncio/streams.py", line 94, in start_server return await loop.create_server(factory, host, port, **kwds) File "/usr/lib/python3.9/asyncio/base_events.py", line 1460, in create_server infos = await tasks.gather(*fs, loop=self) File "/usr/lib/python3.9/asyncio/tasks.py", line 755, in gather warnings.warn("The loop argument is deprecated since Python 3.8, " DeprecationWarning: The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10. ERROR asyncio:base_events.py:1738 Task exception was never retrieved future: exception=DeprecationWarning('The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.')> Traceback (most recent call last): File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 86, in serve await self.startup(sockets=sockets) File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 159, in startup server = await asyncio.start_server( File "/usr/lib/python3.9/asyncio/streams.py", line 94, in start_server return await loop.create_server(factory, host, port, **kwds) File "/usr/lib/python3.9/asyncio/base_events.py", line 1460, in create_server infos = await tasks.gather(*fs, loop=self) File "/usr/lib/python3.9/asyncio/tasks.py", line 755, in gather warnings.warn("The loop argument is deprecated since Python 3.8, " DeprecationWarning: The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10. ERROR asyncio:base_events.py:1738 Task exception was never retrieved future: exception=DeprecationWarning('The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.')> Traceback (most recent call last): File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 86, in serve await self.startup(sockets=sockets) File "/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/server.py", line 159, in startup server = await asyncio.start_server( File "/usr/lib/python3.9/asyncio/streams.py", line 94, in start_server return await loop.create_server(factory, host, port, **kwds) File "/usr/lib/python3.9/asyncio/base_events.py", line 1460, in create_server infos = await tasks.gather(*fs, loop=self) File "/usr/lib/python3.9/asyncio/tasks.py", line 755, in gather warnings.warn("The loop argument is deprecated since Python 3.8, " DeprecationWarning: The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10. ________________ test_accept_connection[H11Protocol-WSProtocol] ________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:96: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:91: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21b37f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21b37f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:97: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_accept_connection[H11Protocol-WebSocketProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:96: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:91: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2334a60>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2334a60>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:97: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____________ test_accept_connection[HttpToolsProtocol-WSProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:96: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:91: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26e78b0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26e78b0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:97: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_accept_connection[HttpToolsProtocol-WebSocketProtocol] __________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:96: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:91: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2714790>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2714790>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_accept_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:97: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ______ test_supports_permessage_deflate_extension[H11Protocol-WSProtocol] ______ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > extension_names = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:117: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] > async with websockets.connect(url, extensions=extension_factories) as websocket: tests/protocols/test_websocket.py:112: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20d94f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20d94f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): extension_names = await open_connection("ws://127.0.0.1:8000") > assert "permessage-deflate" in extension_names tests/protocols/test_websocket.py:118: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down __ test_supports_permessage_deflate_extension[H11Protocol-WebSocketProtocol] ___ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > extension_names = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:117: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] > async with websockets.connect(url, extensions=extension_factories) as websocket: tests/protocols/test_websocket.py:112: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c233a9d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c233a9d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): extension_names = await open_connection("ws://127.0.0.1:8000") > assert "permessage-deflate" in extension_names tests/protocols/test_websocket.py:118: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___ test_supports_permessage_deflate_extension[HttpToolsProtocol-WSProtocol] ___ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > extension_names = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:117: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] > async with websockets.connect(url, extensions=extension_factories) as websocket: tests/protocols/test_websocket.py:112: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2211ca0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2211ca0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): extension_names = await open_connection("ws://127.0.0.1:8000") > assert "permessage-deflate" in extension_names tests/protocols/test_websocket.py:118: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_supports_permessage_deflate_extension[HttpToolsProtocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > extension_names = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:117: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] > async with websockets.connect(url, extensions=extension_factories) as websocket: tests/protocols/test_websocket.py:112: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2642a90>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2642a90>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_supports_permessage_deflate_extension( ws_protocol_cls, http_protocol_cls ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def open_connection(url): extension_factories = [ClientPerMessageDeflateFactory()] async with websockets.connect(url, extensions=extension_factories) as websocket: return [extension.name for extension in websocket.extensions] config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): extension_names = await open_connection("ws://127.0.0.1:8000") > assert "permessage-deflate" in extension_names tests/protocols/test_websocket.py:118: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________________ test_close_connection[H11Protocol-WSProtocol] _________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:138: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): try: > await websockets.connect(url) tests/protocols/test_websocket.py:131: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c215a1f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c215a1f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert not is_open tests/protocols/test_websocket.py:139: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____________ test_close_connection[H11Protocol-WebSocketProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:138: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): try: > await websockets.connect(url) tests/protocols/test_websocket.py:131: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c264ffa0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c264ffa0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert not is_open tests/protocols/test_websocket.py:139: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____________ test_close_connection[HttpToolsProtocol-WSProtocol] ______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:138: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): try: > await websockets.connect(url) tests/protocols/test_websocket.py:131: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c6af0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c6af0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert not is_open tests/protocols/test_websocket.py:139: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down __________ test_close_connection[HttpToolsProtocol-WebSocketProtocol] __________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:138: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): try: > await websockets.connect(url) tests/protocols/test_websocket.py:131: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c22091c0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c22091c0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.close"}) async def open_connection(url): try: await websockets.connect(url) except websockets.exceptions.InvalidHandshake: return False return True # pragma: no cover config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert not is_open tests/protocols/test_websocket.py:139: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____________________ test_headers[H11Protocol-WSProtocol] _____________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:159: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c220cca0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c220cca0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:160: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________________ test_headers[H11Protocol-WebSocketProtocol] __________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:159: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2225310>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2225310>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:160: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down __________________ test_headers[HttpToolsProtocol-WSProtocol] __________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:159: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20a1f70>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20a1f70>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:160: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ______________ test_headers[HttpToolsProtocol-WebSocketProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:159: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:154: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c17f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c17f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_headers(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): headers = self.scope.get("headers") headers = dict(headers) assert headers[b"host"].startswith(b"127.0.0.1") await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000") > assert is_open tests/protocols/test_websocket.py:160: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________________ test_path_and_raw_path[H11Protocol-WSProtocol] ________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") tests/protocols/test_websocket.py:181: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000/one%2Ftwo' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:176: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c264db50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c264db50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") > assert is_open tests/protocols/test_websocket.py:182: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_path_and_raw_path[H11Protocol-WebSocketProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") tests/protocols/test_websocket.py:181: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000/one%2Ftwo' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:176: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2656ac0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2656ac0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") > assert is_open tests/protocols/test_websocket.py:182: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____________ test_path_and_raw_path[HttpToolsProtocol-WSProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") tests/protocols/test_websocket.py:181: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000/one%2Ftwo' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:176: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c235f6d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c235f6d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") > assert is_open tests/protocols/test_websocket.py:182: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_path_and_raw_path[HttpToolsProtocol-WebSocketProtocol] __________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") tests/protocols/test_websocket.py:181: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000/one%2Ftwo' async def open_connection(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:176: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21ce490>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21ce490>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_path_and_raw_path(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): path = self.scope.get("path") raw_path = self.scope.get("raw_path") assert path == "/one/two" assert raw_path == "/one%2Ftwo" await self.send({"type": "websocket.accept"}) async def open_connection(url): async with websockets.connect(url) as websocket: return websocket.open config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): is_open = await open_connection("ws://127.0.0.1:8000/one%2Ftwo") > assert is_open tests/protocols/test_websocket.py:182: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_send_text_data_to_client[H11Protocol-WSProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:200: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:195: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2251c40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2251c40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == "123" tests/protocols/test_websocket.py:201: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_send_text_data_to_client[H11Protocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:200: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:195: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0823dc0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0823dc0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == "123" tests/protocols/test_websocket.py:201: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_send_text_data_to_client[HttpToolsProtocol-WSProtocol] __________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:200: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:195: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2209b20>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2209b20>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == "123" tests/protocols/test_websocket.py:201: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ______ test_send_text_data_to_client[HttpToolsProtocol-WebSocketProtocol] ______ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:200: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:195: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c24fdf10>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c24fdf10>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == "123" tests/protocols/test_websocket.py:201: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_send_binary_data_to_client[H11Protocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:219: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:214: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c05f7910>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c05f7910>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == b"123" tests/protocols/test_websocket.py:220: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_send_binary_data_to_client[H11Protocol-WebSocketProtocol] ________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:219: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:214: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c061e730>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c061e730>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == b"123" tests/protocols/test_websocket.py:220: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_send_binary_data_to_client[HttpToolsProtocol-WSProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:219: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:214: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2315f40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2315f40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == b"123" tests/protocols/test_websocket.py:220: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____ test_send_binary_data_to_client[HttpToolsProtocol-WebSocketProtocol] _____ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:219: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:214: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c6820>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c6820>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_client(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "bytes": b"123"}) async def get_data(url): async with websockets.connect(url) as websocket: return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await get_data("ws://127.0.0.1:8000") > assert data == b"123" tests/protocols/test_websocket.py:220: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_send_and_close_connection[H11Protocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:245: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c25ab1c0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c25ab1c0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:247: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_send_and_close_connection[H11Protocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:245: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26d9130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26d9130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:247: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_send_and_close_connection[HttpToolsProtocol-WSProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:245: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c228d910>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c228d910>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:247: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____ test_send_and_close_connection[HttpToolsProtocol-WebSocketProtocol] ______ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:245: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:234: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21800a0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21800a0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_and_close_connection(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:247: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_send_text_data_to_server[H11Protocol-WSProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:269: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:263: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0805c10>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0805c10>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == "abc" tests/protocols/test_websocket.py:270: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_send_text_data_to_server[H11Protocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:269: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:263: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2170ca0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2170ca0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == "abc" tests/protocols/test_websocket.py:270: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_send_text_data_to_server[HttpToolsProtocol-WSProtocol] __________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:269: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:263: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c256c670>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c256c670>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == "abc" tests/protocols/test_websocket.py:270: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ______ test_send_text_data_to_server[HttpToolsProtocol-WebSocketProtocol] ______ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:269: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:263: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2389670>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2389670>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_text_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _text = message.get("text") await self.send({"type": "websocket.send", "text": _text}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send("abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == "abc" tests/protocols/test_websocket.py:270: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_send_binary_data_to_server[H11Protocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:292: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:286: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c060cf10>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c060cf10>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == b"abc" tests/protocols/test_websocket.py:293: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_send_binary_data_to_server[H11Protocol-WebSocketProtocol] ________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:292: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:286: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06edf40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06edf40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == b"abc" tests/protocols/test_websocket.py:293: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_send_binary_data_to_server[HttpToolsProtocol-WSProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:292: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:286: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c061ee50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c061ee50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == b"abc" tests/protocols/test_websocket.py:293: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____ test_send_binary_data_to_server[HttpToolsProtocol-WebSocketProtocol] _____ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:292: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:286: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c268ec40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c268ec40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_binary_data_to_server(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url) as websocket: await websocket.send(b"abc") return await websocket.recv() config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): data = await send_text("ws://127.0.0.1:8000") > assert data == b"abc" tests/protocols/test_websocket.py:293: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_send_after_protocol_close[H11Protocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:320: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:309: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c209ca00>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c209ca00>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:322: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_send_after_protocol_close[H11Protocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:320: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:309: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2544490>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2544490>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:322: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_send_after_protocol_close[HttpToolsProtocol-WSProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:320: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:309: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c235f4f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c235f4f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:322: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____ test_send_after_protocol_close[HttpToolsProtocol-WebSocketProtocol] ______ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > (data, is_open) = await get_data("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:320: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_data(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:309: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c22111f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c22111f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_after_protocol_close(ws_protocol_cls, http_protocol_cls): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) await self.send({"type": "websocket.send", "text": "123"}) await self.send({"type": "websocket.close"}) with pytest.raises(Exception): await self.send({"type": "websocket.send", "text": "123"}) async def get_data(url): async with websockets.connect(url) as websocket: data = await websocket.recv() is_open = True try: await websocket.recv() except Exception: is_open = False return (data, is_open) config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): (data, is_open) = await get_data("ws://127.0.0.1:8000") assert data == "123" > assert not is_open tests/protocols/test_websocket.py:322: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________________ test_missing_handshake[H11Protocol-WSProtocol] ________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:338: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:333: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c230de80>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c230de80>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:339: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_missing_handshake[H11Protocol-WebSocketProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:338: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:333: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c25976d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c25976d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:339: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____________ test_missing_handshake[HttpToolsProtocol-WSProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:338: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:333: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2722a90>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2722a90>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:339: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_missing_handshake[HttpToolsProtocol-WebSocketProtocol] __________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:338: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:333: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23cfdf0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23cfdf0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_missing_handshake(ws_protocol_cls, http_protocol_cls): async def app(app, receive, send): pass async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:339: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ______________ test_send_before_handshake[H11Protocol-WSProtocol] ______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:355: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:350: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c221d130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c221d130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:356: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down __________ test_send_before_handshake[H11Protocol-WebSocketProtocol] ___________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:355: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:350: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c24fd190>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c24fd190>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:356: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_send_before_handshake[HttpToolsProtocol-WSProtocol] ___________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:355: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:350: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c04ce400>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c04ce400>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:356: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______ test_send_before_handshake[HttpToolsProtocol-WebSocketProtocol] ________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:355: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > await websockets.connect(url) tests/protocols/test_websocket.py:350: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c07c4700>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c07c4700>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_send_before_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.send", "text": "123"}) async def connect(url): await websockets.connect(url) config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.status_code == 500 tests/protocols/test_websocket.py:356: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_duplicate_handshake[H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:374: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2597e50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2597e50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:375: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_duplicate_handshake[H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:374: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c04b4ac0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c04b4ac0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:375: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_duplicate_handshake[HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:374: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23475e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23475e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:375: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_duplicate_handshake[HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:374: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:368: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c22d6f40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c22d6f40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_duplicate_handshake(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): await send({"type": "websocket.accept"}) await send({"type": "websocket.accept"}) async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:375: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________________ test_asgi_return_value[H11Protocol-WSProtocol] ________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:398: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:392: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06d79a0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06d79a0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:399: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_asgi_return_value[H11Protocol-WebSocketProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:398: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:392: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23bb550>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23bb550>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:399: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _____________ test_asgi_return_value[HttpToolsProtocol-WSProtocol] _____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:398: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:392: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26b3970>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26b3970>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:399: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _________ test_asgi_return_value[HttpToolsProtocol-WebSocketProtocol] __________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await connect("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:398: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def connect(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:392: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21519d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c21519d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_asgi_return_value(ws_protocol_cls, http_protocol_cls): """ The ASGI callable should return 'None'. If it doesn't make sure that the connection is closed with an error condition. """ async def app(scope, receive, send): await send({"type": "websocket.accept"}) return 123 async def connect(url): async with websockets.connect(url) as websocket: _ = await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await connect("ws://127.0.0.1:8000") > assert exc_info.value.code == 1006 tests/protocols/test_websocket.py:399: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_app_close[None-None-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26afe80>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26afe80>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_app_close[None-None-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2334b50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2334b50>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_app_close[None-None-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23cf940>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23cf940>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_app_close[None-None-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20d3220>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20d3220>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_app_close[None-1000-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06b8af0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06b8af0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_app_close[None-1000-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c256c7f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c256c7f0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_app_close[None-1000-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0435190>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0435190>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_app_close[None-1000-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26360d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c26360d0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_app_close[None-1001-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23b95e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c23b95e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_app_close[None-1001-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2315f40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2315f40>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_app_close[None-1001-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c03d6bb0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c03d6bb0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_app_close[None-1001-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c03dc5e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c03dc5e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = None @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_app_close[test-None-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2151d00>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2151d00>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_app_close[test-None-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2346160>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2346160>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_app_close[test-None-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c242ddf0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c242ddf0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_app_close[test-None-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c220e910>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c220e910>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = None, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_app_close[test-1000-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0379d30>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0379d30>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_app_close[test-1000-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c6ee0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20c6ee0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_app_close[test-1000-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c045d3a0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c045d3a0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_app_close[test-1000-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0395f70>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0395f70>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1000, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_app_close[test-1001-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06e9be0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c06e9be0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_app_close[test-1001-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2c80130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2c80130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_app_close[test-1001-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0734bb0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0734bb0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_app_close[test-1001-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:435: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:427: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c075ed30>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c075ed30>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = code = 1001, reason = 'test' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("code", [None, 1000, 1001]) @pytest.mark.parametrize("reason", [None, "test"]) async def test_app_close(ws_protocol_cls, http_protocol_cls, code, reason): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": reply = {"type": "websocket.close"} if code is not None: reply["code"] = code if reason is not None: reply["reason"] = reason await send(reply) elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") await websocket.recv() config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info: await websocket_session("ws://127.0.0.1:8000") assert exc_info.value.code == (code or 1000) > assert exc_info.value.reason == (reason or "") tests/protocols/test_websocket.py:437: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down __________________ test_client_close[H11Protocol-WSProtocol] ___________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:455: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0770100>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0770100>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_client_close[H11Protocol-WebSocketProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:455: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2180130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2180130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_client_close[HttpToolsProtocol-WSProtocol] ________________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:455: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0366b80>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0366b80>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_client_close[HttpToolsProtocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def websocket_session(url): > async with websockets.connect(url) as websocket: tests/protocols/test_websocket.py:455: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2291130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2291130>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) async def test_client_close(ws_protocol_cls, http_protocol_cls): async def app(scope, receive, send): while True: message = await receive() if message["type"] == "websocket.connect": await send({"type": "websocket.accept"}) elif message["type"] == "websocket.receive": pass elif message["type"] == "websocket.disconnect": break async def websocket_session(url): async with websockets.connect(url) as websocket: await websocket.ping() await websocket.send("abc") config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > await websocket_session("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:461: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_subprotocols[proto1-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c20a1f70>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c20a1f70>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_subprotocols[proto1-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c22530a0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c22530a0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_subprotocols[proto1-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c07e42b0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c07e42b0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_subprotocols[proto1-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c07f7220>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c07f7220>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto1' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _______________ test_subprotocols[proto2-H11Protocol-WSProtocol] _______________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c044b820>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c044b820>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ___________ test_subprotocols[proto2-H11Protocol-WebSocketProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c07c4f70>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c07c4f70>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ____________ test_subprotocols[proto2-HttpToolsProtocol-WSProtocol] ____________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c06465b0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c06465b0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down ________ test_subprotocols[proto2-HttpToolsProtocol-WebSocketProtocol] _________ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): > accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:481: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def get_subprotocol(url): > async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: tests/protocols/test_websocket.py:474: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c20a19d0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...flate.ClientPerMessageDeflateFactory object at 0x7f07c20a19d0>], subprotocols=['proto1', 'proto2'], extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = subprotocol = 'proto2' @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize("subprotocol", ["proto1", "proto2"]) async def test_subprotocols(ws_protocol_cls, http_protocol_cls, subprotocol): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept", "subprotocol": subprotocol}) async def get_subprotocol(url): async with websockets.connect( url, subprotocols=["proto1", "proto2"] ) as websocket: return websocket.subprotocol config = Config(app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") async with run_server(config): accepted_subprotocol = await get_subprotocol("ws://127.0.0.1:8000") > assert accepted_subprotocol == subprotocol tests/protocols/test_websocket.py:482: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=defaults sent=defaults-H11Protocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 16777216, server_size_max = 16777216, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:536: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c04eb8e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c04eb8e0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 16777216, server_size_max = 16777216, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=defaults sent=defaults-HttpToolsProtocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 16777216, server_size_max = 16777216, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:536: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c238d760>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c238d760>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 16777216, server_size_max = 16777216, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=defaults sent=defaults+1-H11Protocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 16777217, server_size_max = 16777216, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:540: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c233a5b0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c233a5b0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 16777217, server_size_max = 16777216, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=defaults sent=defaults+1-HttpToolsProtocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 16777217, server_size_max = 16777216, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:540: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0552f70>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c0552f70>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 16777217, server_size_max = 16777216, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=10 sent=10-H11Protocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 10, server_size_max = 10, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:536: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2334790>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2334790>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 10, server_size_max = 10, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=10 sent=10-HttpToolsProtocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 10, server_size_max = 10, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:536: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2291fa0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c2291fa0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 10, server_size_max = 10, expected_result = 0 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=10 sent=11-H11Protocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 11, server_size_max = 10, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:540: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c064a820>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c064a820>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 11, server_size_max = 10, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down _ test_send_binary_data_to_server_bigger_than_default[max=10 sent=11-HttpToolsProtocol-WebSocketProtocol] _ config = , sockets = None @asynccontextmanager async def run_server(config: Config, sockets=None): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve(sockets=sockets)) await asyncio.sleep(0.1) try: > yield server tests/utils.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ws_protocol_cls = http_protocol_cls = client_size_sent = 11, server_size_max = 10, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: > data = await send_text("ws://127.0.0.1:8000") tests/protocols/test_websocket.py:540: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ url = 'ws://127.0.0.1:8000' async def send_text(url): > async with websockets.connect(url, max_size=client_size_sent) as websocket: tests/protocols/test_websocket.py:523: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __aenter__(self) -> WebSocketClientProtocol: > return await self /usr/lib/python3/dist-packages/websockets/legacy/client.py:604: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = async def __await_impl__(self) -> WebSocketClientProtocol: for redirects in range(self.MAX_REDIRECTS_ALLOWED): > transport, protocol = await self._create_connection() /usr/lib/python3/dist-packages/websockets/legacy/client.py:622: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20b8be0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) break except OSError: continue else: # using happy eyeballs sock, _, _ = await staggered.staggered_race( (functools.partial(self._connect_sock, exceptions, addrinfo, laddr_infos) for addrinfo in infos), happy_eyeballs_delay, loop=self) if sock is None: exceptions = [exc for sub in exceptions for exc in sub] if len(exceptions) == 1: > raise exceptions[0] /usr/lib/python3.9/asyncio/base_events.py:1056: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> protocol_factory = functools.partial(, ping_interval=20, ping_timeout=20, close...ns.permessage_deflate.ClientPerMessageDeflateFactory object at 0x7f07c20b8be0>], subprotocols=None, extra_headers=None) host = '127.0.0.1', port = 8000 async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if happy_eyeballs_delay is not None and interleave is None: # If using happy eyeballs, default to interleave addresses by family interleave = 1 if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') else: laddr_infos = None if interleave: infos = _interleave_addrinfos(infos, interleave) exceptions = [] if happy_eyeballs_delay is None: # not using happy eyeballs for addrinfo in infos: try: > sock = await self._connect_sock( exceptions, addrinfo, laddr_infos) /usr/lib/python3.9/asyncio/base_events.py:1041: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> exceptions = [[ConnectionRefusedError(111, "Connect call failed ('127.0.0.1', 8000)")]] addr_info = (, , 6, '', ('127.0.0.1', 8000)) local_addr_infos = None async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): """Create, bind and connect one socket.""" my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info sock = None try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) if local_addr_infos is not None: for _, _, _, _, laddr in local_addr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) my_exceptions.append(exc) else: # all bind attempts failed raise my_exceptions.pop() > await self.sock_connect(sock, address) /usr/lib/python3.9/asyncio/base_events.py:955: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> sock = address = ('127.0.0.1', 8000) async def sock_connect(self, sock, address): """Connect to a remote socket at address. This method is a coroutine. """ _check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: resolved = await self._ensure_resolved( address, family=sock.family, proto=sock.proto, loop=self) _, _, _, _, address = resolved[0] fut = self.create_future() self._sock_connect(fut, sock, address) > return await fut /usr/lib/python3.9/asyncio/selector_events.py:502: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <_UnixSelectorEventLoop running=False closed=False debug=False> fut = sock = address = ('127.0.0.1', 8000) def _sock_connect_cb(self, fut, sock, address): if fut.done(): return try: err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # Jump to any except clause below. > raise OSError(err, f'Connect call failed {address}') E ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 8000) /usr/lib/python3.9/asyncio/selector_events.py:537: ConnectionRefusedError During handling of the above exception, another exception occurred: ws_protocol_cls = http_protocol_cls = client_size_sent = 11, server_size_max = 10, expected_result = 1009 @pytest.mark.asyncio @pytest.mark.parametrize("ws_protocol_cls", ONLY_WEBSOCKETPROTOCOL) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) @pytest.mark.parametrize( "client_size_sent, server_size_max, expected_result", [ (MAX_WS_BYTES, MAX_WS_BYTES, 0), (MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009), (10, 10, 0), (11, 10, 1009), ], ids=[ "max=defaults sent=defaults", "max=defaults sent=defaults+1", "max=10 sent=10", "max=10 sent=11", ], ) async def test_send_binary_data_to_server_bigger_than_default( ws_protocol_cls, http_protocol_cls, client_size_sent, server_size_max, expected_result, ): class App(WebSocketResponse): async def websocket_connect(self, message): await self.send({"type": "websocket.accept"}) async def websocket_receive(self, message): _bytes = message.get("bytes") await self.send({"type": "websocket.send", "bytes": _bytes}) async def send_text(url): async with websockets.connect(url, max_size=client_size_sent) as websocket: await websocket.send(b"\x01" * client_size_sent) return await websocket.recv() config = Config( app=App, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off", ws_max_size=server_size_max, ) async with run_server(config): if expected_result == 0: data = await send_text("ws://127.0.0.1:8000") assert data == b"\x01" * client_size_sent else: with pytest.raises(websockets.ConnectionClosedError) as e: data = await send_text("ws://127.0.0.1:8000") > assert e.value.code == expected_result tests/protocols/test_websocket.py:541: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3.9/contextlib.py:199: in __aexit__ await self.gen.athrow(typ, value, traceback) tests/utils.py:22: in run_server await server.shutdown() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , sockets = None async def shutdown(self, sockets: Optional[List[socket.socket]] = None) -> None: logger.info("Shutting down") # Stop accepting new connections. > for server in self.servers: E AttributeError: 'Server' object has no attribute 'servers' uvicorn/server.py:266: AttributeError ----------------------------- Captured stderr call ----------------------------- INFO: Started server process [1451933] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1451933] INFO uvicorn.error:server.py:263 Shutting down =============== 112 failed, 212 passed, 24 deselected in 30.52s ================ make[1]: Leaving directory '/build/python-uvicorn-0.15.0'