I: Using pkgname logfile I: Current time: Mon Nov 1 23:48:37 EDT 2021 I: pbuilder-time-stamp: 1635824917 I: Copying source file I: copying [../python-uvicorn_0.15.0-1.dsc] I: copying [../python-uvicorn_0.15.0.orig.tar.xz] I: copying [../python-uvicorn_0.15.0-1.debian.tar.xz] I: Extracting source dpkg-source: warning: extracting unsigned source package (python-uvicorn_0.15.0-1.dsc) dpkg-source: info: extracting python-uvicorn in python-uvicorn-0.15.0 dpkg-source: info: unpacking python-uvicorn_0.15.0.orig.tar.xz dpkg-source: info: unpacking python-uvicorn_0.15.0-1.debian.tar.xz dpkg-source: info: using patch list from debian/patches/series dpkg-source: info: applying 0001-Disable-material-theme-for-mkdocs-use-default-one.patch dpkg-source: info: applying 0002-Use-local-copy-of-uvicorn-logo.patch dpkg-source: info: applying 0003-Remove-image-badges-to-prevent-privacy-breaches.patch I: Not using root during the build. I: Installing the build-deps I: user script /var/cache/pbuilder/build/1055192/tmp/hooks/D70local-repo starting + REPO=/home/morph/deb/pbuilder/pkgs + ls -A /home/morph/deb/pbuilder/pkgs + [ Packages platformdirs_2.0.2-1.debian.tar.xz platformdirs_2.0.2-1.dsc platformdirs_2.0.2-1_amd64.build platformdirs_2.0.2-1_amd64.buildinfo platformdirs_2.0.2-1_amd64.changes platformdirs_2.0.2-1_source.changes platformdirs_2.0.2.orig.tar.gz pydata-sphinx-theme_0.6.3-1.debian.tar.xz pydata-sphinx-theme_0.6.3-1.dsc pydata-sphinx-theme_0.6.3-1_amd64.build pydata-sphinx-theme_0.6.3-1_amd64.buildinfo pydata-sphinx-theme_0.6.3-1_amd64.changes pydata-sphinx-theme_0.6.3-1_source.changes pydata-sphinx-theme_0.6.3.orig.tar.xz pydata-sphinx-theme_0.7.1-1.debian.tar.xz pydata-sphinx-theme_0.7.1-1.dsc pydata-sphinx-theme_0.7.1-1_amd64.build pydata-sphinx-theme_0.7.1-1_amd64.buildinfo pydata-sphinx-theme_0.7.1-1_amd64.changes pydata-sphinx-theme_0.7.1-1_source.changes pydata-sphinx-theme_0.7.1.orig.tar.xz python-charset-normalizer_2.0.6-1.debian.tar.xz python-charset-normalizer_2.0.6-1.dsc python-charset-normalizer_2.0.6-1_amd64.build python-charset-normalizer_2.0.6-1_amd64.buildinfo python-charset-normalizer_2.0.6-1_amd64.changes python-charset-normalizer_2.0.6-1_source.changes python-charset-normalizer_2.0.6.orig.tar.gz python-pallets-sphinx-themes_2.0.1-1.debian.tar.xz python-pallets-sphinx-themes_2.0.1-1.dsc python-pallets-sphinx-themes_2.0.1-1_amd64.build python-pallets-sphinx-themes_2.0.1-1_amd64.buildinfo python-pallets-sphinx-themes_2.0.1-1_amd64.changes python-pallets-sphinx-themes_2.0.1-1_source.changes python-pallets-sphinx-themes_2.0.1.orig.tar.xz python-pydata-sphinx-theme-doc_0.6.3-1_all.deb python-pydata-sphinx-theme-doc_0.7.1-1_all.deb python3-charset-normalizer_2.0.6-1_all.deb python3-pallets-sphinx-themes_2.0.1-1_all.deb python3-platformdirs_2.0.2-1_all.deb python3-pydata-sphinx-theme_0.6.3-1_all.deb python3-pydata-sphinx-theme_0.7.1-1_all.deb ] + cd /home/morph/deb/pbuilder/pkgs + /usr/bin/dpkg-scanpackages . /dev/null dpkg-scanpackages: warning: package python3-pydata-sphinx-theme (filename ./python3-pydata-sphinx-theme_0.7.1-1_all.deb) is repeat but newer version; used that one and ignored data from ./python3-pydata-sphinx-theme_0.6.3-1_all.deb! dpkg-scanpackages: warning: package python-pydata-sphinx-theme-doc (filename ./python-pydata-sphinx-theme-doc_0.7.1-1_all.deb) is repeat but newer version; used that one and ignored data from ./python-pydata-sphinx-theme-doc_0.6.3-1_all.deb! dpkg-scanpackages: warning: Packages with multiple instances but no --multiversion specified: dpkg-scanpackages: warning: ./python-pydata-sphinx-theme-doc_0.7.1-1_all.deb dpkg-scanpackages: warning: ./python3-pydata-sphinx-theme_0.6.3-1_all.deb dpkg-scanpackages: warning: ./python3-pydata-sphinx-theme_0.7.1-1_all.deb dpkg-scanpackages: warning: Packages in archive but missing from override file: dpkg-scanpackages: warning: python-pydata-sphinx-theme-doc python3-charset-normalizer python3-pallets-sphinx-themes python3-platformdirs python3-pydata-sphinx-theme dpkg-scanpackages: info: Wrote 5 entries to output Packages file. + /usr/bin/apt-get update Get:1 file:/home/morph/deb/pbuilder/pkgs ./ InRelease Ign:1 file:/home/morph/deb/pbuilder/pkgs ./ InRelease Get:2 file:/home/morph/deb/pbuilder/pkgs ./ Release Ign:2 file:/home/morph/deb/pbuilder/pkgs ./ Release Get:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Ign:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Get:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Ign:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Get:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Ign:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Get:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Ign:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Get:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Ign:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Get:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Ign:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Get:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Ign:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Get:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Ign:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Get:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Ign:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Get:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Ign:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Get:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Ign:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages Get:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Ign:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Get:3 file:/home/morph/deb/pbuilder/pkgs ./ Packages [5598 B] Get:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Ign:4 file:/home/morph/deb/pbuilder/pkgs ./ Translation-en Get:5 http://ftp.debian.org/debian unstable InRelease [165 kB] Get:6 http://ftp.debian.org/debian experimental InRelease [75.4 kB] Get:7 http://ftp.debian.org/debian unstable/main amd64 Packages [8797 kB] Get:8 http://ftp.debian.org/debian unstable/main Translation-en [6588 kB] Get:9 http://ftp.debian.org/debian experimental/main amd64 Packages [385 kB] Get:10 http://ftp.debian.org/debian experimental/main Translation-en [237 kB] Fetched 16.2 MB in 3s (5811 kB/s) Reading package lists... I: user script /var/cache/pbuilder/build/1055192/tmp/hooks/D70local-repo finished I: user script /var/cache/pbuilder/build/1055192/tmp/hooks/D80no-man-db-rebuild starting I: Preseed man-db/auto-update to false I: user script /var/cache/pbuilder/build/1055192/tmp/hooks/D80no-man-db-rebuild finished -> Attempting to satisfy build-dependencies -> Creating pbuilder-satisfydepends-dummy package Package: pbuilder-satisfydepends-dummy Version: 0.invalid.0 Architecture: amd64 Maintainer: Debian Pbuilder Team Description: Dummy package to satisfy dependencies with aptitude - created by pbuilder This package was created automatically by pbuilder to satisfy the build-dependencies of the package being currently built. Depends: debhelper-compat (= 13), dh-python, docbook-to-man, mkdocs (>= 1.0.4), python3-all, python3-asgiref, python3-dotenv, python3-click, python3-h11, python3-httptools, python3-httpx, python3-pytest, python3-pytest-asyncio, python3-pytest-mock, python3-requests, python3-setuptools, python3-trustme, python3-uvloop, python3-watchgod, python3-websockets, python3-wsproto dpkg-deb: building package 'pbuilder-satisfydepends-dummy' in '/tmp/satisfydepends-aptitude/pbuilder-satisfydepends-dummy.deb'. Selecting previously unselected package pbuilder-satisfydepends-dummy. (Reading database ... 14908 files and directories currently installed.) Preparing to unpack .../pbuilder-satisfydepends-dummy.deb ... Unpacking pbuilder-satisfydepends-dummy (0.invalid.0) ... dpkg: pbuilder-satisfydepends-dummy: dependency problems, but configuring anyway as you requested: pbuilder-satisfydepends-dummy depends on debhelper-compat (= 13); however: Package debhelper-compat is not installed. pbuilder-satisfydepends-dummy depends on dh-python; however: Package dh-python is not installed. pbuilder-satisfydepends-dummy depends on docbook-to-man; however: Package docbook-to-man is not installed. pbuilder-satisfydepends-dummy depends on mkdocs (>= 1.0.4); however: Package mkdocs is not installed. pbuilder-satisfydepends-dummy depends on python3-all; however: Package python3-all is not installed. pbuilder-satisfydepends-dummy depends on python3-asgiref; however: Package python3-asgiref is not installed. pbuilder-satisfydepends-dummy depends on python3-dotenv; however: Package python3-dotenv is not installed. pbuilder-satisfydepends-dummy depends on python3-click; however: Package python3-click is not installed. pbuilder-satisfydepends-dummy depends on python3-h11; however: Package python3-h11 is not installed. pbuilder-satisfydepends-dummy depends on python3-httptools; however: Package python3-httptools is not installed. pbuilder-satisfydepends-dummy depends on python3-httpx; however: Package python3-httpx is not installed. pbuilder-satisfydepends-dummy depends on python3-pytest; however: Package python3-pytest is not installed. pbuilder-satisfydepends-dummy depends on python3-pytest-asyncio; however: Package python3-pytest-asyncio is not installed. pbuilder-satisfydepends-dummy depends on python3-pytest-mock; however: Package python3-pytest-mock is not installed. pbuilder-satisfydepends-dummy depends on python3-requests; however: Package python3-requests is not installed. pbuilder-satisfydepends-dummy depends on python3-setuptools; however: Package python3-setuptools is not installed. pbuilder-satisfydepends-dummy depends on python3-trustme; however: Package python3-trustme is not installed. pbuilder-satisfydepends-dummy depends on python3-uvloop; however: Package python3-uvloop is not installed. pbuilder-satisfydepends-dummy depends on python3-watchgod; however: Package python3-watchgod is not installed. pbuilder-satisfydepends-dummy depends on python3-websockets; however: Package python3-websockets is not installed. pbuilder-satisfydepends-dummy depends on python3-wsproto; however: Package python3-wsproto is not installed. Setting up pbuilder-satisfydepends-dummy (0.invalid.0) ... Reading package lists... Building dependency tree... Reading state information... Reading extended state information... Initializing package states... Writing extended state information... Building tag database... pbuilder-satisfydepends-dummy is already installed at the requested version (0.invalid.0) pbuilder-satisfydepends-dummy is already installed at the requested version (0.invalid.0) The following NEW packages will be installed: autoconf{a} automake{a} autopoint{a} autotools-dev{a} bsdextrautils{a} ca-certificates{a} debhelper{a} dh-autoreconf{a} dh-python{a} dh-strip-nondeterminism{a} docbook{a} docbook-to-man{a} dwz{a} file{a} fonts-font-awesome{a} fonts-lato{a} gettext{a} gettext-base{a} groff-base{a} intltool-debian{a} javascript-common{a} libarchive-zip-perl{a} libdebhelper-perl{a} libelf1{a} libexpat1{a} libfile-stripnondeterminism-perl{a} libhttp-parser2.9{a} libicu67{a} libjs-bootstrap4{a} libjs-jquery{a} libjs-lunr{a} libjs-modernizr{a} libjs-popper.js{a} libmagic-mgc{a} libmagic1{a} libmpdec3{a} libosp5{a} libpipeline1{a} libpython3-stdlib{a} libpython3.9-minimal{a} libpython3.9-stdlib{a} libreadline8{a} libsigsegv2{a} libsub-override-perl{a} libtool{a} libuchardet0{a} libuv1{a} libxml2{a} libyaml-0-2{a} m4{a} man-db{a} media-types{a} mkdocs{a} opensp{a} openssl{a} po-debconf{a} python-babel-localedata{a} python3{a} python3-all{a} python3-asgiref{a} python3-async-generator{a} python3-attr{a} python3-babel{a} python3-certifi{a} python3-cffi-backend{a} python3-chardet{a} python3-click{a} python3-colorama{a} python3-cryptography{a} python3-distutils{a} python3-dotenv{a} python3-h11{a} python3-httpcore{a} python3-httptools{a} python3-httpx{a} python3-idna{a} python3-importlib-metadata{a} python3-iniconfig{a} python3-jinja2{a} python3-lib2to3{a} python3-livereload{a} python3-markdown{a} python3-markupsafe{a} python3-minimal{a} python3-more-itertools{a} python3-packaging{a} python3-pkg-resources{a} python3-pluggy{a} python3-py{a} python3-pyparsing{a} python3-pytest{a} python3-pytest-asyncio{a} python3-pytest-mock{a} python3-requests{a} python3-rfc3986{a} python3-setuptools{a} python3-six{a} python3-sniffio{a} python3-toml{a} python3-tornado{a} python3-trustme{a} python3-tz{a} python3-urllib3{a} python3-uvloop{a} python3-watchgod{a} python3-websockets{a} python3-wsproto{a} python3-yaml{a} python3-zipp{a} python3.9{a} python3.9-minimal{a} sgml-base{a} sgml-data{a} sphinx-rtd-theme-common{a} xml-core{a} The following packages are RECOMMENDED but will NOT be installed: curl libarchive-cpio-perl libltdl-dev libmail-sendmail-perl lynx node-jquery python3-pygments python3-pyinotify wget 0 packages upgraded, 115 newly installed, 0 to remove and 0 not upgraded. Need to get 0 B/43.1 MB of archives. After unpacking 168 MB will be used. Writing extended state information... debconf: delaying package configuration, since apt-utils is not installed Selecting previously unselected package bsdextrautils. (Reading database ... (Reading database ... 5% (Reading database ... 10% (Reading database ... 15% (Reading database ... 20% (Reading database ... 25% (Reading database ... 30% (Reading database ... 35% (Reading database ... 40% (Reading database ... 45% (Reading database ... 50% (Reading database ... 55% (Reading database ... 60% (Reading database ... 65% (Reading database ... 70% (Reading database ... 75% (Reading database ... 80% (Reading database ... 85% (Reading database ... 90% (Reading database ... 95% (Reading database ... 100% (Reading database ... 14908 files and directories currently installed.) Preparing to unpack .../0-bsdextrautils_2.37.2-4_amd64.deb ... Unpacking bsdextrautils (2.37.2-4) ... Selecting previously unselected package libuchardet0:amd64. Preparing to unpack .../1-libuchardet0_0.0.7-1_amd64.deb ... Unpacking libuchardet0:amd64 (0.0.7-1) ... Selecting previously unselected package groff-base. Preparing to unpack .../2-groff-base_1.22.4-7_amd64.deb ... Unpacking groff-base (1.22.4-7) ... Selecting previously unselected package libpipeline1:amd64. Preparing to unpack .../3-libpipeline1_1.5.3-1_amd64.deb ... Unpacking libpipeline1:amd64 (1.5.3-1) ... Selecting previously unselected package man-db. Preparing to unpack .../4-man-db_2.9.4-2_amd64.deb ... Unpacking man-db (2.9.4-2) ... Selecting previously unselected package fonts-lato. Preparing to unpack .../5-fonts-lato_2.0-2.1_all.deb ... Unpacking fonts-lato (2.0-2.1) ... Selecting previously unselected package libpython3.9-minimal:amd64. Preparing to unpack .../6-libpython3.9-minimal_3.9.7-4_amd64.deb ... Unpacking libpython3.9-minimal:amd64 (3.9.7-4) ... Preparing to unpack .../7-libexpat1_2.4.1-3_amd64.deb ... Unpacking libexpat1:amd64 (2.4.1-3) ... Selecting previously unselected package python3.9-minimal. Preparing to unpack .../8-python3.9-minimal_3.9.7-4_amd64.deb ... Unpacking python3.9-minimal (3.9.7-4) ... Setting up libpython3.9-minimal:amd64 (3.9.7-4) ... Setting up libexpat1:amd64 (2.4.1-3) ... Setting up python3.9-minimal (3.9.7-4) ... Selecting previously unselected package python3-minimal. (Reading database ... (Reading database ... 5% (Reading database ... 10% (Reading database ... 15% (Reading database ... 20% (Reading database ... 25% (Reading database ... 30% (Reading database ... 35% (Reading database ... 40% (Reading database ... 45% (Reading database ... 50% (Reading database ... 55% (Reading database ... 60% (Reading database ... 65% (Reading database ... 70% (Reading database ... 75% (Reading database ... 80% (Reading database ... 85% (Reading database ... 90% (Reading database ... 95% (Reading database ... 100% (Reading database ... 15801 files and directories currently installed.) Preparing to unpack .../0-python3-minimal_3.9.2-3_amd64.deb ... Unpacking python3-minimal (3.9.2-3) ... Selecting previously unselected package media-types. Preparing to unpack .../1-media-types_4.0.0_all.deb ... Unpacking media-types (4.0.0) ... Selecting previously unselected package libmpdec3:amd64. Preparing to unpack .../2-libmpdec3_2.5.1-2_amd64.deb ... Unpacking libmpdec3:amd64 (2.5.1-2) ... Selecting previously unselected package libreadline8:amd64. Preparing to unpack .../3-libreadline8_8.1-2_amd64.deb ... Unpacking libreadline8:amd64 (8.1-2) ... Selecting previously unselected package libpython3.9-stdlib:amd64. Preparing to unpack .../4-libpython3.9-stdlib_3.9.7-4_amd64.deb ... Unpacking libpython3.9-stdlib:amd64 (3.9.7-4) ... Selecting previously unselected package python3.9. Preparing to unpack .../5-python3.9_3.9.7-4_amd64.deb ... Unpacking python3.9 (3.9.7-4) ... Selecting previously unselected package libpython3-stdlib:amd64. Preparing to unpack .../6-libpython3-stdlib_3.9.2-3_amd64.deb ... Unpacking libpython3-stdlib:amd64 (3.9.2-3) ... Setting up python3-minimal (3.9.2-3) ... Selecting previously unselected package python3. (Reading database ... (Reading database ... 5% (Reading database ... 10% (Reading database ... 15% (Reading database ... 20% (Reading database ... 25% (Reading database ... 30% (Reading database ... 35% (Reading database ... 40% (Reading database ... 45% (Reading database ... 50% (Reading database ... 55% (Reading database ... 60% (Reading database ... 65% (Reading database ... 70% (Reading database ... 75% (Reading database ... 80% (Reading database ... 85% (Reading database ... 90% (Reading database ... 95% (Reading database ... 100% (Reading database ... 16212 files and directories currently installed.) Preparing to unpack .../00-python3_3.9.2-3_amd64.deb ... Unpacking python3 (3.9.2-3) ... Selecting previously unselected package sgml-base. Preparing to unpack .../01-sgml-base_1.30_all.deb ... Unpacking sgml-base (1.30) ... Preparing to unpack .../02-openssl_1.1.1l-1_amd64.deb ... Unpacking openssl (1.1.1l-1) ... Preparing to unpack .../03-ca-certificates_20211016_all.deb ... Unpacking ca-certificates (20211016) ... Selecting previously unselected package libmagic-mgc. Preparing to unpack .../04-libmagic-mgc_1%3a5.39-3_amd64.deb ... Unpacking libmagic-mgc (1:5.39-3) ... Selecting previously unselected package libmagic1:amd64. Preparing to unpack .../05-libmagic1_1%3a5.39-3_amd64.deb ... Unpacking libmagic1:amd64 (1:5.39-3) ... Selecting previously unselected package file. Preparing to unpack .../06-file_1%3a5.39-3_amd64.deb ... Unpacking file (1:5.39-3) ... Selecting previously unselected package gettext-base. Preparing to unpack .../07-gettext-base_0.21-4_amd64.deb ... Unpacking gettext-base (0.21-4) ... Selecting previously unselected package libsigsegv2:amd64. Preparing to unpack .../08-libsigsegv2_2.13-1_amd64.deb ... Unpacking libsigsegv2:amd64 (2.13-1) ... Selecting previously unselected package m4. Preparing to unpack .../09-m4_1.4.18-5_amd64.deb ... Unpacking m4 (1.4.18-5) ... Selecting previously unselected package autoconf. Preparing to unpack .../10-autoconf_2.71-2_all.deb ... Unpacking autoconf (2.71-2) ... Selecting previously unselected package autotools-dev. Preparing to unpack .../11-autotools-dev_20180224.1+nmu1_all.deb ... Unpacking autotools-dev (20180224.1+nmu1) ... Selecting previously unselected package automake. Preparing to unpack .../12-automake_1%3a1.16.5-1_all.deb ... Unpacking automake (1:1.16.5-1) ... Selecting previously unselected package autopoint. Preparing to unpack .../13-autopoint_0.21-4_all.deb ... Unpacking autopoint (0.21-4) ... Selecting previously unselected package libdebhelper-perl. Preparing to unpack .../14-libdebhelper-perl_13.5.2_all.deb ... Unpacking libdebhelper-perl (13.5.2) ... Selecting previously unselected package libtool. Preparing to unpack .../15-libtool_2.4.6-15_all.deb ... Unpacking libtool (2.4.6-15) ... Selecting previously unselected package dh-autoreconf. Preparing to unpack .../16-dh-autoreconf_20_all.deb ... Unpacking dh-autoreconf (20) ... Selecting previously unselected package libarchive-zip-perl. Preparing to unpack .../17-libarchive-zip-perl_1.68-1_all.deb ... Unpacking libarchive-zip-perl (1.68-1) ... Selecting previously unselected package libsub-override-perl. Preparing to unpack .../18-libsub-override-perl_0.09-2_all.deb ... Unpacking libsub-override-perl (0.09-2) ... Selecting previously unselected package libfile-stripnondeterminism-perl. Preparing to unpack .../19-libfile-stripnondeterminism-perl_1.12.0-2_all.deb ... Unpacking libfile-stripnondeterminism-perl (1.12.0-2) ... Selecting previously unselected package dh-strip-nondeterminism. Preparing to unpack .../20-dh-strip-nondeterminism_1.12.0-2_all.deb ... Unpacking dh-strip-nondeterminism (1.12.0-2) ... Selecting previously unselected package libelf1:amd64. Preparing to unpack .../21-libelf1_0.185-2_amd64.deb ... Unpacking libelf1:amd64 (0.185-2) ... Selecting previously unselected package dwz. Preparing to unpack .../22-dwz_0.14-1_amd64.deb ... Unpacking dwz (0.14-1) ... Selecting previously unselected package libicu67:amd64. Preparing to unpack .../23-libicu67_67.1-7_amd64.deb ... Unpacking libicu67:amd64 (67.1-7) ... Selecting previously unselected package libxml2:amd64. Preparing to unpack .../24-libxml2_2.9.12+dfsg-5_amd64.deb ... Unpacking libxml2:amd64 (2.9.12+dfsg-5) ... Selecting previously unselected package gettext. Preparing to unpack .../25-gettext_0.21-4_amd64.deb ... Unpacking gettext (0.21-4) ... Selecting previously unselected package intltool-debian. Preparing to unpack .../26-intltool-debian_0.35.0+20060710.5_all.deb ... Unpacking intltool-debian (0.35.0+20060710.5) ... Selecting previously unselected package po-debconf. Preparing to unpack .../27-po-debconf_1.0.21+nmu1_all.deb ... Unpacking po-debconf (1.0.21+nmu1) ... Selecting previously unselected package debhelper. Preparing to unpack .../28-debhelper_13.5.2_all.deb ... Unpacking debhelper (13.5.2) ... Selecting previously unselected package python3-lib2to3. Preparing to unpack .../29-python3-lib2to3_3.9.7-1_all.deb ... Unpacking python3-lib2to3 (3.9.7-1) ... Selecting previously unselected package python3-distutils. Preparing to unpack .../30-python3-distutils_3.9.7-1_all.deb ... Unpacking python3-distutils (3.9.7-1) ... Selecting previously unselected package dh-python. Preparing to unpack .../31-dh-python_5.20211022.1_all.deb ... Unpacking dh-python (5.20211022.1) ... Selecting previously unselected package xml-core. Preparing to unpack .../32-xml-core_0.18+nmu1_all.deb ... Unpacking xml-core (0.18+nmu1) ... Selecting previously unselected package sgml-data. Preparing to unpack .../33-sgml-data_2.0.11+nmu1_all.deb ... Unpacking sgml-data (2.0.11+nmu1) ... Selecting previously unselected package docbook. Preparing to unpack .../34-docbook_4.5-8_all.deb ... Unpacking docbook (4.5-8) ... Selecting previously unselected package libosp5. Preparing to unpack .../35-libosp5_1.5.2-13+b2_amd64.deb ... Unpacking libosp5 (1.5.2-13+b2) ... Selecting previously unselected package opensp. Preparing to unpack .../36-opensp_1.5.2-13+b2_amd64.deb ... Unpacking opensp (1.5.2-13+b2) ... Selecting previously unselected package docbook-to-man. Preparing to unpack .../37-docbook-to-man_1%3a2.0.0-45_amd64.deb ... Unpacking docbook-to-man (1:2.0.0-45) ... Selecting previously unselected package fonts-font-awesome. Preparing to unpack .../38-fonts-font-awesome_5.0.10+really4.7.0~dfsg-4.1_all.deb ... Unpacking fonts-font-awesome (5.0.10+really4.7.0~dfsg-4.1) ... Selecting previously unselected package javascript-common. Preparing to unpack .../39-javascript-common_11+nmu1_all.deb ... Unpacking javascript-common (11+nmu1) ... Selecting previously unselected package libhttp-parser2.9:amd64. Preparing to unpack .../40-libhttp-parser2.9_2.9.4-4_amd64.deb ... Unpacking libhttp-parser2.9:amd64 (2.9.4-4) ... Selecting previously unselected package libjs-popper.js. Preparing to unpack .../41-libjs-popper.js_1.16.1+ds-4_all.deb ... Unpacking libjs-popper.js (1.16.1+ds-4) ... Selecting previously unselected package libjs-bootstrap4. Preparing to unpack .../42-libjs-bootstrap4_4.5.2+dfsg1-8_all.deb ... Unpacking libjs-bootstrap4 (4.5.2+dfsg1-8) ... Selecting previously unselected package libjs-jquery. Preparing to unpack .../43-libjs-jquery_3.5.1+dfsg+~3.5.5-8_all.deb ... Unpacking libjs-jquery (3.5.1+dfsg+~3.5.5-8) ... Selecting previously unselected package libjs-lunr. Preparing to unpack .../44-libjs-lunr_2.3.8~dfsg-4_all.deb ... Unpacking libjs-lunr (2.3.8~dfsg-4) ... Selecting previously unselected package libjs-modernizr. Preparing to unpack .../45-libjs-modernizr_2.6.2+ds1-4_all.deb ... Unpacking libjs-modernizr (2.6.2+ds1-4) ... Selecting previously unselected package libuv1:amd64. Preparing to unpack .../46-libuv1_1.42.0-1_amd64.deb ... Unpacking libuv1:amd64 (1.42.0-1) ... Selecting previously unselected package libyaml-0-2:amd64. Preparing to unpack .../47-libyaml-0-2_0.2.2-1_amd64.deb ... Unpacking libyaml-0-2:amd64 (0.2.2-1) ... Selecting previously unselected package python3-pkg-resources. Preparing to unpack .../48-python3-pkg-resources_58.2.0-1_all.deb ... Unpacking python3-pkg-resources (58.2.0-1) ... Selecting previously unselected package sphinx-rtd-theme-common. Preparing to unpack .../49-sphinx-rtd-theme-common_1.0.0+dfsg-1_all.deb ... Unpacking sphinx-rtd-theme-common (1.0.0+dfsg-1) ... Selecting previously unselected package python3-colorama. Preparing to unpack .../50-python3-colorama_0.4.4-1_all.deb ... Unpacking python3-colorama (0.4.4-1) ... Selecting previously unselected package python3-click. Preparing to unpack .../51-python3-click_8.0.2-1_all.deb ... Unpacking python3-click (8.0.2-1) ... Selecting previously unselected package python-babel-localedata. Preparing to unpack .../52-python-babel-localedata_2.8.0+dfsg.1-7_all.deb ... Unpacking python-babel-localedata (2.8.0+dfsg.1-7) ... Selecting previously unselected package python3-tz. Preparing to unpack .../53-python3-tz_2021.3-1_all.deb ... Unpacking python3-tz (2021.3-1) ... Selecting previously unselected package python3-babel. Preparing to unpack .../54-python3-babel_2.8.0+dfsg.1-7_all.deb ... Unpacking python3-babel (2.8.0+dfsg.1-7) ... Selecting previously unselected package python3-markupsafe. Preparing to unpack .../55-python3-markupsafe_2.0.1-2_amd64.deb ... Unpacking python3-markupsafe (2.0.1-2) ... Selecting previously unselected package python3-jinja2. Preparing to unpack .../56-python3-jinja2_3.0.1-2_all.deb ... Unpacking python3-jinja2 (3.0.1-2) ... Selecting previously unselected package python3-tornado. Preparing to unpack .../57-python3-tornado_6.1.0-1+b1_amd64.deb ... Unpacking python3-tornado (6.1.0-1+b1) ... Selecting previously unselected package python3-six. Preparing to unpack .../58-python3-six_1.16.0-2_all.deb ... Unpacking python3-six (1.16.0-2) ... Selecting previously unselected package python3-livereload. Preparing to unpack .../59-python3-livereload_2.6.3-2_all.deb ... Unpacking python3-livereload (2.6.3-2) ... Selecting previously unselected package python3-markdown. Preparing to unpack .../60-python3-markdown_3.3.4-1_all.deb ... Unpacking python3-markdown (3.3.4-1) ... Selecting previously unselected package python3-yaml. Preparing to unpack .../61-python3-yaml_5.4.1-1_amd64.deb ... Unpacking python3-yaml (5.4.1-1) ... Selecting previously unselected package mkdocs. Preparing to unpack .../62-mkdocs_1.1.2+dfsg-2_all.deb ... Unpacking mkdocs (1.1.2+dfsg-2) ... Selecting previously unselected package python3-all. Preparing to unpack .../63-python3-all_3.9.2-3_amd64.deb ... Unpacking python3-all (3.9.2-3) ... Selecting previously unselected package python3-asgiref. Preparing to unpack .../64-python3-asgiref_3.4.1-1_all.deb ... Unpacking python3-asgiref (3.4.1-1) ... Selecting previously unselected package python3-async-generator. Preparing to unpack .../65-python3-async-generator_1.10-3_all.deb ... Unpacking python3-async-generator (1.10-3) ... Selecting previously unselected package python3-attr. Preparing to unpack .../66-python3-attr_20.3.0-1_all.deb ... Unpacking python3-attr (20.3.0-1) ... Selecting previously unselected package python3-certifi. Preparing to unpack .../67-python3-certifi_2020.6.20-1_all.deb ... Unpacking python3-certifi (2020.6.20-1) ... Selecting previously unselected package python3-cffi-backend:amd64. Preparing to unpack .../68-python3-cffi-backend_1.15.0-1_amd64.deb ... Unpacking python3-cffi-backend:amd64 (1.15.0-1) ... Selecting previously unselected package python3-chardet. Preparing to unpack .../69-python3-chardet_4.0.0-1_all.deb ... Unpacking python3-chardet (4.0.0-1) ... Selecting previously unselected package python3-cryptography. Preparing to unpack .../70-python3-cryptography_3.3.2-1_amd64.deb ... Unpacking python3-cryptography (3.3.2-1) ... Selecting previously unselected package python3-dotenv. Preparing to unpack .../71-python3-dotenv_0.19.0-1_all.deb ... Unpacking python3-dotenv (0.19.0-1) ... Selecting previously unselected package python3-h11. Preparing to unpack .../72-python3-h11_0.12.0-1_all.deb ... Unpacking python3-h11 (0.12.0-1) ... Selecting previously unselected package python3-sniffio. Preparing to unpack .../73-python3-sniffio_1.1.0-1_all.deb ... Unpacking python3-sniffio (1.1.0-1) ... Selecting previously unselected package python3-httpcore. Preparing to unpack .../74-python3-httpcore_0.13.7-1_all.deb ... Unpacking python3-httpcore (0.13.7-1) ... Selecting previously unselected package python3-httptools. Preparing to unpack .../75-python3-httptools_0.1.1-1+b3_amd64.deb ... Unpacking python3-httptools (0.1.1-1+b3) ... Selecting previously unselected package python3-idna. Preparing to unpack .../76-python3-idna_2.10-1_all.deb ... Unpacking python3-idna (2.10-1) ... Selecting previously unselected package python3-rfc3986. Preparing to unpack .../77-python3-rfc3986_1.5.0-2_all.deb ... Unpacking python3-rfc3986 (1.5.0-2) ... Selecting previously unselected package python3-httpx. Preparing to unpack .../78-python3-httpx_0.16.1-1_all.deb ... Unpacking python3-httpx (0.16.1-1) ... Selecting previously unselected package python3-more-itertools. Preparing to unpack .../79-python3-more-itertools_4.2.0-3_all.deb ... Unpacking python3-more-itertools (4.2.0-3) ... Selecting previously unselected package python3-zipp. Preparing to unpack .../80-python3-zipp_1.0.0-3_all.deb ... Unpacking python3-zipp (1.0.0-3) ... Selecting previously unselected package python3-importlib-metadata. Preparing to unpack .../81-python3-importlib-metadata_4.6.4-1_all.deb ... Unpacking python3-importlib-metadata (4.6.4-1) ... Selecting previously unselected package python3-iniconfig. Preparing to unpack .../82-python3-iniconfig_1.1.1-1_all.deb ... Unpacking python3-iniconfig (1.1.1-1) ... Selecting previously unselected package python3-pyparsing. Preparing to unpack .../83-python3-pyparsing_2.4.7-1_all.deb ... Unpacking python3-pyparsing (2.4.7-1) ... Selecting previously unselected package python3-packaging. Preparing to unpack .../84-python3-packaging_21.0-1_all.deb ... Unpacking python3-packaging (21.0-1) ... Selecting previously unselected package python3-pluggy. Preparing to unpack .../85-python3-pluggy_0.13.0-7.1_all.deb ... Unpacking python3-pluggy (0.13.0-7.1) ... Selecting previously unselected package python3-py. Preparing to unpack .../86-python3-py_1.10.0-1_all.deb ... Unpacking python3-py (1.10.0-1) ... Selecting previously unselected package python3-toml. Preparing to unpack .../87-python3-toml_0.10.2-1_all.deb ... Unpacking python3-toml (0.10.2-1) ... Selecting previously unselected package python3-pytest. Preparing to unpack .../88-python3-pytest_6.2.5-1_all.deb ... Unpacking python3-pytest (6.2.5-1) ... Selecting previously unselected package python3-pytest-asyncio. Preparing to unpack .../89-python3-pytest-asyncio_0.15.1-1_all.deb ... Unpacking python3-pytest-asyncio (0.15.1-1) ... Selecting previously unselected package python3-pytest-mock. Preparing to unpack .../90-python3-pytest-mock_3.6.1-1_all.deb ... Unpacking python3-pytest-mock (3.6.1-1) ... Selecting previously unselected package python3-urllib3. Preparing to unpack .../91-python3-urllib3_1.26.5-1~exp1_all.deb ... Unpacking python3-urllib3 (1.26.5-1~exp1) ... Selecting previously unselected package python3-requests. Preparing to unpack .../92-python3-requests_2.25.1+dfsg-2_all.deb ... Unpacking python3-requests (2.25.1+dfsg-2) ... Selecting previously unselected package python3-setuptools. Preparing to unpack .../93-python3-setuptools_58.2.0-1_all.deb ... Unpacking python3-setuptools (58.2.0-1) ... Selecting previously unselected package python3-trustme. Preparing to unpack .../94-python3-trustme_0.6.0-1_all.deb ... Unpacking python3-trustme (0.6.0-1) ... Selecting previously unselected package python3-uvloop. Preparing to unpack .../95-python3-uvloop_0.16.0+ds1-1_amd64.deb ... Unpacking python3-uvloop (0.16.0+ds1-1) ... Selecting previously unselected package python3-watchgod. Preparing to unpack .../96-python3-watchgod_0.7-1_all.deb ... Unpacking python3-watchgod (0.7-1) ... Selecting previously unselected package python3-websockets. Preparing to unpack .../97-python3-websockets_9.1-1_all.deb ... Unpacking python3-websockets (9.1-1) ... Selecting previously unselected package python3-wsproto. Preparing to unpack .../98-python3-wsproto_1.0.0-1_all.deb ... Unpacking python3-wsproto (1.0.0-1) ... Setting up media-types (4.0.0) ... Setting up libpipeline1:amd64 (1.5.3-1) ... Setting up javascript-common (11+nmu1) ... /usr/bin/which: this version of `which' is deprecated; use `command -v' in scripts instead. Setting up fonts-lato (2.0-2.1) ... Setting up bsdextrautils (2.37.2-4) ... update-alternatives: using /usr/bin/write.ul to provide /usr/bin/write (write) in auto mode Setting up libicu67:amd64 (67.1-7) ... Setting up libjs-popper.js (1.16.1+ds-4) ... Setting up libmagic-mgc (1:5.39-3) ... Setting up libarchive-zip-perl (1.68-1) ... Setting up libyaml-0-2:amd64 (0.2.2-1) ... Setting up libjs-lunr (2.3.8~dfsg-4) ... Setting up libdebhelper-perl (13.5.2) ... Setting up libreadline8:amd64 (8.1-2) ... Setting up libmagic1:amd64 (1:5.39-3) ... Setting up gettext-base (0.21-4) ... Setting up file (1:5.39-3) ... Setting up libjs-modernizr (2.6.2+ds1-4) ... Setting up python-babel-localedata (2.8.0+dfsg.1-7) ... Setting up libosp5 (1.5.2-13+b2) ... Setting up autotools-dev (20180224.1+nmu1) ... Setting up libuv1:amd64 (1.42.0-1) ... Setting up libsigsegv2:amd64 (2.13-1) ... Setting up autopoint (0.21-4) ... Setting up libuchardet0:amd64 (0.0.7-1) ... Setting up libmpdec3:amd64 (2.5.1-2) ... Setting up libsub-override-perl (0.09-2) ... Setting up sgml-base (1.30) ... Setting up libjs-bootstrap4 (4.5.2+dfsg1-8) ... Setting up libjs-jquery (3.5.1+dfsg+~3.5.5-8) ... Setting up openssl (1.1.1l-1) ... Installing new version of config file /etc/ssl/openssl.cnf ... Setting up libelf1:amd64 (0.185-2) ... Setting up libxml2:amd64 (2.9.12+dfsg-5) ... Setting up fonts-font-awesome (5.0.10+really4.7.0~dfsg-4.1) ... Setting up sphinx-rtd-theme-common (1.0.0+dfsg-1) ... Setting up libhttp-parser2.9:amd64 (2.9.4-4) ... Setting up libpython3.9-stdlib:amd64 (3.9.7-4) ... Setting up libpython3-stdlib:amd64 (3.9.2-3) ... Setting up libfile-stripnondeterminism-perl (1.12.0-2) ... Setting up gettext (0.21-4) ... Setting up libtool (2.4.6-15) ... Setting up m4 (1.4.18-5) ... Setting up opensp (1.5.2-13+b2) ... Setting up intltool-debian (0.35.0+20060710.5) ... Setting up ca-certificates (20211016) ... Clearing symlinks in /etc/ssl/certs... done. Updating certificates in /etc/ssl/certs... rehash: warning: skipping ca-certificates.crt,it does not contain exactly one certificate or CRL 127 added, 0 removed; done. Setting up autoconf (2.71-2) ... Setting up dh-strip-nondeterminism (1.12.0-2) ... Setting up dwz (0.14-1) ... Setting up groff-base (1.22.4-7) ... Setting up xml-core (0.18+nmu1) ... Setting up python3.9 (3.9.7-4) ... Setting up automake (1:1.16.5-1) ... update-alternatives: using /usr/bin/automake-1.16 to provide /usr/bin/automake (automake) in auto mode Setting up po-debconf (1.0.21+nmu1) ... Setting up python3 (3.9.2-3) ... Setting up python3-watchgod (0.7-1) ... Setting up man-db (2.9.4-2) ... Not building database; man-db/auto-update is not 'true'. Setting up python3-markupsafe (2.0.1-2) ... Setting up python3-tz (2021.3-1) ... Setting up python3-six (1.16.0-2) ... Setting up dh-autoreconf (20) ... Setting up python3-pyparsing (2.4.7-1) ... Setting up python3-certifi (2020.6.20-1) ... Setting up python3-idna (2.10-1) ... Setting up python3-h11 (0.12.0-1) ... Setting up python3-toml (0.10.2-1) ... Setting up python3-uvloop (0.16.0+ds1-1) ... Setting up python3-urllib3 (1.26.5-1~exp1) ... Setting up python3-httptools (0.1.1-1+b3) ... Setting up python3-lib2to3 (3.9.7-1) ... Setting up python3-asgiref (3.4.1-1) ... Setting up python3-cffi-backend:amd64 (1.15.0-1) ... Setting up python3-websockets (9.1-1) ... Setting up python3-dotenv (0.19.0-1) ... Setting up python3-pkg-resources (58.2.0-1) ... Setting up python3-distutils (3.9.7-1) ... Setting up dh-python (5.20211022.1) ... Setting up python3-more-itertools (4.2.0-3) ... Setting up python3-iniconfig (1.1.1-1) ... Setting up python3-sniffio (1.1.0-1) ... Setting up python3-attr (20.3.0-1) ... Setting up python3-tornado (6.1.0-1+b1) ... Setting up python3-wsproto (1.0.0-1) ... Setting up python3-setuptools (58.2.0-1) ... Setting up python3-async-generator (1.10-3) ... Setting up python3-py (1.10.0-1) ... Setting up python3-babel (2.8.0+dfsg.1-7) ... update-alternatives: using /usr/bin/pybabel-python3 to provide /usr/bin/pybabel (pybabel) in auto mode Setting up python3-colorama (0.4.4-1) ... Setting up python3-all (3.9.2-3) ... Setting up python3-yaml (5.4.1-1) ... Setting up debhelper (13.5.2) ... Setting up python3-zipp (1.0.0-3) ... Setting up python3-click (8.0.2-1) ... Setting up python3-jinja2 (3.0.1-2) ... Setting up python3-packaging (21.0-1) ... Setting up python3-chardet (4.0.0-1) ... Setting up python3-rfc3986 (1.5.0-2) ... Setting up python3-cryptography (3.3.2-1) ... Setting up python3-requests (2.25.1+dfsg-2) ... Setting up python3-markdown (3.3.4-1) ... Setting up python3-livereload (2.6.3-2) ... Setting up mkdocs (1.1.2+dfsg-2) ... Setting up python3-httpcore (0.13.7-1) ... Setting up python3-importlib-metadata (4.6.4-1) ... Setting up python3-trustme (0.6.0-1) ... Setting up python3-httpx (0.16.1-1) ... Setting up python3-pluggy (0.13.0-7.1) ... Setting up python3-pytest (6.2.5-1) ... Setting up python3-pytest-asyncio (0.15.1-1) ... Setting up python3-pytest-mock (3.6.1-1) ... Processing triggers for install-info (6.8-3) ... Processing triggers for libc-bin (2.32-4) ... Processing triggers for sgml-base (1.30) ... Setting up sgml-data (2.0.11+nmu1) ... Processing triggers for sgml-base (1.30) ... Setting up docbook (4.5-8) ... Processing triggers for sgml-base (1.30) ... Setting up docbook-to-man (1:2.0.0-45) ... Processing triggers for ca-certificates (20211016) ... Updating certificates in /etc/ssl/certs... 0 added, 0 removed; done. Running hooks in /etc/ca-certificates/update.d... done. Reading package lists... Building dependency tree... Reading state information... Reading extended state information... Initializing package states... Writing extended state information... Building tag database... -> Finished parsing the build-deps I: Building the package I: Running cd /build/python-uvicorn-0.15.0/ && env PATH="/usr/sbin:/usr/bin:/sbin:/bin" HOME="/nonexistent" dpkg-buildpackage -us -uc -j6 && env PATH="/usr/sbin:/usr/bin:/sbin:/bin" HOME="/nonexistent" dpkg-genchanges -S > ../python-uvicorn_0.15.0-1_source.changes dpkg-buildpackage: info: source package python-uvicorn dpkg-buildpackage: info: source version 0.15.0-1 dpkg-buildpackage: info: source distribution UNRELEASED dpkg-buildpackage: info: source changed by Sandro Tosi dpkg-source --before-build . dpkg-buildpackage: info: host architecture amd64 debian/rules clean dh clean --with mkdocs,python3 --buildsystem=pybuild dh_auto_clean -O--buildsystem=pybuild I: pybuild base:232: python3.9 setup.py clean running clean removing '/build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build' (and everything under it) 'build/bdist.linux-x86_64' does not exist -- can't clean it 'build/scripts-3.9' does not exist -- can't clean it dh_autoreconf_clean -O--buildsystem=pybuild debian/rules override_dh_clean make[1]: Entering directory '/build/python-uvicorn-0.15.0' rm -rf html dh_clean make[1]: Leaving directory '/build/python-uvicorn-0.15.0' dpkg-source -b . dpkg-source: info: using source format '3.0 (quilt)' dpkg-source: info: building python-uvicorn using existing ./python-uvicorn_0.15.0.orig.tar.xz dpkg-source: info: using patch list from debian/patches/series dpkg-source: info: building python-uvicorn in python-uvicorn_0.15.0-1.debian.tar.xz dpkg-source: info: building python-uvicorn in python-uvicorn_0.15.0-1.dsc debian/rules binary 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 I: pybuild base:232: python3.9 setup.py config running config debian/rules override_dh_auto_build make[1]: Entering directory '/build/python-uvicorn-0.15.0' dh_auto_build I: pybuild base:232: /usr/bin/python3 setup.py build running build running build_py creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/workers.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/subprocess.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/server.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/main.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/logging.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/importer.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/config.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/_types.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/__main__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn copying uvicorn/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/supervisors copying uvicorn/supervisors/watchgodreload.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/supervisors copying uvicorn/supervisors/statreload.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/supervisors copying uvicorn/supervisors/multiprocess.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/supervisors copying uvicorn/supervisors/basereload.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/supervisors copying uvicorn/supervisors/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/supervisors creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols copying uvicorn/protocols/utils.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols copying uvicorn/protocols/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/websockets copying uvicorn/protocols/websockets/wsproto_impl.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/websockets copying uvicorn/protocols/websockets/websockets_impl.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/websockets copying uvicorn/protocols/websockets/auto.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/websockets copying uvicorn/protocols/websockets/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/websockets creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/http copying uvicorn/protocols/http/httptools_impl.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/http copying uvicorn/protocols/http/h11_impl.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/http copying uvicorn/protocols/http/flow_control.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/http copying uvicorn/protocols/http/auto.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/http copying uvicorn/protocols/http/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/protocols/http creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/middleware copying uvicorn/middleware/wsgi.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/middleware copying uvicorn/middleware/proxy_headers.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/middleware copying uvicorn/middleware/message_logger.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/middleware copying uvicorn/middleware/debug.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/middleware copying uvicorn/middleware/asgi2.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/middleware copying uvicorn/middleware/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/middleware creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/loops copying uvicorn/loops/uvloop.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/loops copying uvicorn/loops/auto.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/loops copying uvicorn/loops/asyncio.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/loops copying uvicorn/loops/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/loops creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/lifespan copying uvicorn/lifespan/on.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/lifespan copying uvicorn/lifespan/off.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/lifespan copying uvicorn/lifespan/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/lifespan creating /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/_handlers copying uvicorn/_handlers/http.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/_handlers copying uvicorn/_handlers/__init__.py -> /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build/uvicorn/_handlers running egg_info creating uvicorn.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 writing manifest file 'uvicorn.egg-info/SOURCES.txt' reading manifest file 'uvicorn.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no previously-included files matching '__pycache__' found anywhere in distribution warning: no previously-included files matching '*.py[co]' found anywhere in distribution 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 INFO - Cleaning site directory INFO - Building documentation to directory: /build/python-uvicorn-0.15.0/site INFO - Documentation built in 0.15 seconds make[1]: Leaving directory '/build/python-uvicorn-0.15.0' dh_auto_test -O--buildsystem=pybuild I: pybuild pybuild:285: cp -r /build/python-uvicorn-0.15.0/tests /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build I: pybuild base:232: cd /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build; python3.9 -m pytest -k 'not test_run and not test_invalid_upgrade and not test_default_headers and not test_trace_logging' ============================= 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: 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 FFF. [ 23%] tests/middleware/test_logging.py FFFFFF [ 25%] tests/middleware/test_message_logger.py F. [ 26%] tests/middleware/test_proxy_headers.py FFFFFFFFFFF [ 29%] tests/middleware/test_wsgi.py FF.F. [ 31%] tests/protocols/test_http.py ........................................... [ 44%] ............................................. [ 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 ___________________________ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, timeout=timeout, ) /usr/lib/python3/dist-packages/httpx/_client.py:1548: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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, ) > response = await self.send( request, auth=auth, allow_redirects=allow_redirects, timeout=timeout ) /usr/lib/python3/dist-packages/httpx/_client.py:1371: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, timeout=timeout, allow_redirects=allow_redirects, history=[], ) /usr/lib/python3/dist-packages/httpx/_client.py:1406: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , timeout = Timeout(timeout=5.0) allow_redirects = True, history = [] async def _send_handling_auth( self, request: Request, auth: Auth, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) request = await auth_flow.__anext__() for hook in self._event_hooks["request"]: await hook(request) while True: > response = await self._send_handling_redirects( request, timeout=timeout, allow_redirects=allow_redirects, history=history, ) /usr/lib/python3/dist-packages/httpx/_client.py:1444: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0), allow_redirects = True, history = [] async def _send_handling_redirects( self, request: Request, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) > response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1476: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0) async def _send_single_request( self, request: Request, timeout: Timeout ) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() with map_exceptions(HTTPCORE_EXC_MAP, request=request): > (status_code, headers, stream, ext,) = await transport.arequest( request.method.encode(), request.url.raw, headers=request.headers.raw, stream=request.stream, # type: ignore ext={"timeout": timeout.as_dict()}, ) E AttributeError: 'AsyncHTTPProxy' object has no attribute 'arequest' /usr/lib/python3/dist-packages/httpx/_client.py:1502: AttributeError 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 [1063183] 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 [1063183] 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_debug_text ________________________________ @pytest.mark.asyncio async def test_debug_text(): async def app(scope, receive, send): raise RuntimeError("Something went wrong") app = DebugMiddleware(app) transport = httpx.ASGITransport( app=app, raise_app_exceptions=False, ) async with httpx.AsyncClient( transport=transport, base_url="http://testserver" ) as client: > response = await client.get("/") tests/middleware/test_debug.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1')] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError _______________________________ test_debug_html ________________________________ @pytest.mark.asyncio async def test_debug_html(): async def app(scope, receive, send): raise RuntimeError("Something went wrong") app = DebugMiddleware(app) transport = httpx.ASGITransport( app=app, raise_app_exceptions=False, ) async with httpx.AsyncClient( transport=transport, base_url="http://testserver" ) as client: > response = await client.get("/", headers={"Accept": "text/html, */*"}) tests/middleware/test_debug.py:40: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'text/html, */*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1')] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError ________________________ test_debug_after_response_sent ________________________ @pytest.mark.asyncio async def test_debug_after_response_sent(): async def app(scope, receive, send): await send({"type": "http.response.start", "status": 204, "headers": []}) await send({"type": "http.response.body", "body": b"", "more_body": False}) raise RuntimeError("Something went wrong") app = DebugMiddleware(app) transport = httpx.ASGITransport( app=app, raise_app_exceptions=False, ) async with httpx.AsyncClient( transport=transport, base_url="http://testserver" ) as client: > response = await client.get("/") tests/middleware/test_debug.py:61: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1')] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError __________________________ test_access_logging[True] ___________________________ 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 0x7f3ba27b25e0> @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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, timeout=timeout, ) /usr/lib/python3/dist-packages/httpx/_client.py:1548: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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, ) > response = await self.send( request, auth=auth, allow_redirects=allow_redirects, timeout=timeout ) /usr/lib/python3/dist-packages/httpx/_client.py:1371: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, timeout=timeout, allow_redirects=allow_redirects, history=[], ) /usr/lib/python3/dist-packages/httpx/_client.py:1406: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , timeout = Timeout(timeout=5.0) allow_redirects = True, history = [] async def _send_handling_auth( self, request: Request, auth: Auth, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) request = await auth_flow.__anext__() for hook in self._event_hooks["request"]: await hook(request) while True: > response = await self._send_handling_redirects( request, timeout=timeout, allow_redirects=allow_redirects, history=history, ) /usr/lib/python3/dist-packages/httpx/_client.py:1444: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0), allow_redirects = True, history = [] async def _send_handling_redirects( self, request: Request, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) > response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1476: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0) async def _send_single_request( self, request: Request, timeout: Timeout ) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() with map_exceptions(HTTPCORE_EXC_MAP, request=request): > (status_code, headers, stream, ext,) = await transport.arequest( request.method.encode(), request.url.raw, headers=request.headers.raw, stream=request.stream, # type: ignore ext={"timeout": timeout.as_dict()}, ) E AttributeError: 'AsyncHTTPProxy' object has no attribute 'arequest' /usr/lib/python3/dist-packages/httpx/_client.py:1502: AttributeError During handling of the above exception, another exception occurred: use_colors = True caplog = <_pytest.logging.LogCaptureFixture object at 0x7f3ba27b25e0> @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 [1063183] 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 [1063183] 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] __________________________ 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 0x7f3ba364b850> @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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, timeout=timeout, ) /usr/lib/python3/dist-packages/httpx/_client.py:1548: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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, ) > response = await self.send( request, auth=auth, allow_redirects=allow_redirects, timeout=timeout ) /usr/lib/python3/dist-packages/httpx/_client.py:1371: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, timeout=timeout, allow_redirects=allow_redirects, history=[], ) /usr/lib/python3/dist-packages/httpx/_client.py:1406: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , timeout = Timeout(timeout=5.0) allow_redirects = True, history = [] async def _send_handling_auth( self, request: Request, auth: Auth, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) request = await auth_flow.__anext__() for hook in self._event_hooks["request"]: await hook(request) while True: > response = await self._send_handling_redirects( request, timeout=timeout, allow_redirects=allow_redirects, history=history, ) /usr/lib/python3/dist-packages/httpx/_client.py:1444: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0), allow_redirects = True, history = [] async def _send_handling_redirects( self, request: Request, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) > response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1476: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0) async def _send_single_request( self, request: Request, timeout: Timeout ) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() with map_exceptions(HTTPCORE_EXC_MAP, request=request): > (status_code, headers, stream, ext,) = await transport.arequest( request.method.encode(), request.url.raw, headers=request.headers.raw, stream=request.stream, # type: ignore ext={"timeout": timeout.as_dict()}, ) E AttributeError: 'AsyncHTTPProxy' object has no attribute 'arequest' /usr/lib/python3/dist-packages/httpx/_client.py:1502: AttributeError During handling of the above exception, another exception occurred: use_colors = False caplog = <_pytest.logging.LogCaptureFixture object at 0x7f3ba364b850> @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 [1063183] 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 [1063183] 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] ___________________________ 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 0x7f3ba270b9a0> @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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, timeout=timeout, ) /usr/lib/python3/dist-packages/httpx/_client.py:1548: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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, ) > response = await self.send( request, auth=auth, allow_redirects=allow_redirects, timeout=timeout ) /usr/lib/python3/dist-packages/httpx/_client.py:1371: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, timeout=timeout, allow_redirects=allow_redirects, history=[], ) /usr/lib/python3/dist-packages/httpx/_client.py:1406: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , timeout = Timeout(timeout=5.0) allow_redirects = True, history = [] async def _send_handling_auth( self, request: Request, auth: Auth, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) request = await auth_flow.__anext__() for hook in self._event_hooks["request"]: await hook(request) while True: > response = await self._send_handling_redirects( request, timeout=timeout, allow_redirects=allow_redirects, history=history, ) /usr/lib/python3/dist-packages/httpx/_client.py:1444: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0), allow_redirects = True, history = [] async def _send_handling_redirects( self, request: Request, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) > response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1476: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0) async def _send_single_request( self, request: Request, timeout: Timeout ) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() with map_exceptions(HTTPCORE_EXC_MAP, request=request): > (status_code, headers, stream, ext,) = await transport.arequest( request.method.encode(), request.url.raw, headers=request.headers.raw, stream=request.stream, # type: ignore ext={"timeout": timeout.as_dict()}, ) E AttributeError: 'AsyncHTTPProxy' object has no attribute 'arequest' /usr/lib/python3/dist-packages/httpx/_client.py:1502: AttributeError During handling of the above exception, another exception occurred: use_colors = None caplog = <_pytest.logging.LogCaptureFixture object at 0x7f3ba270b9a0> @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 [1063183] 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 [1063183] 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] __________________________ 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 0x7f3ba270d7c0> @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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, timeout=timeout, ) /usr/lib/python3/dist-packages/httpx/_client.py:1548: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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, ) > response = await self.send( request, auth=auth, allow_redirects=allow_redirects, timeout=timeout ) /usr/lib/python3/dist-packages/httpx/_client.py:1371: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, timeout=timeout, allow_redirects=allow_redirects, history=[], ) /usr/lib/python3/dist-packages/httpx/_client.py:1406: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , timeout = Timeout(timeout=5.0) allow_redirects = True, history = [] async def _send_handling_auth( self, request: Request, auth: Auth, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) request = await auth_flow.__anext__() for hook in self._event_hooks["request"]: await hook(request) while True: > response = await self._send_handling_redirects( request, timeout=timeout, allow_redirects=allow_redirects, history=history, ) /usr/lib/python3/dist-packages/httpx/_client.py:1444: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0), allow_redirects = True, history = [] async def _send_handling_redirects( self, request: Request, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) > response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1476: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0) async def _send_single_request( self, request: Request, timeout: Timeout ) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() with map_exceptions(HTTPCORE_EXC_MAP, request=request): > (status_code, headers, stream, ext,) = await transport.arequest( request.method.encode(), request.url.raw, headers=request.headers.raw, stream=request.stream, # type: ignore ext={"timeout": timeout.as_dict()}, ) E AttributeError: 'AsyncHTTPProxy' object has no attribute 'arequest' /usr/lib/python3/dist-packages/httpx/_client.py:1502: AttributeError During handling of the above exception, another exception occurred: use_colors = True caplog = <_pytest.logging.LogCaptureFixture object at 0x7f3ba270d7c0> @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 [1063183] 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 [1063183] 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] __________________________ 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 0x7f3ba2752b20> @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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, timeout=timeout, ) /usr/lib/python3/dist-packages/httpx/_client.py:1548: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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, ) > response = await self.send( request, auth=auth, allow_redirects=allow_redirects, timeout=timeout ) /usr/lib/python3/dist-packages/httpx/_client.py:1371: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, timeout=timeout, allow_redirects=allow_redirects, history=[], ) /usr/lib/python3/dist-packages/httpx/_client.py:1406: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , timeout = Timeout(timeout=5.0) allow_redirects = True, history = [] async def _send_handling_auth( self, request: Request, auth: Auth, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) request = await auth_flow.__anext__() for hook in self._event_hooks["request"]: await hook(request) while True: > response = await self._send_handling_redirects( request, timeout=timeout, allow_redirects=allow_redirects, history=history, ) /usr/lib/python3/dist-packages/httpx/_client.py:1444: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0), allow_redirects = True, history = [] async def _send_handling_redirects( self, request: Request, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) > response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1476: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0) async def _send_single_request( self, request: Request, timeout: Timeout ) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() with map_exceptions(HTTPCORE_EXC_MAP, request=request): > (status_code, headers, stream, ext,) = await transport.arequest( request.method.encode(), request.url.raw, headers=request.headers.raw, stream=request.stream, # type: ignore ext={"timeout": timeout.as_dict()}, ) E AttributeError: 'AsyncHTTPProxy' object has no attribute 'arequest' /usr/lib/python3/dist-packages/httpx/_client.py:1502: AttributeError During handling of the above exception, another exception occurred: use_colors = False caplog = <_pytest.logging.LogCaptureFixture object at 0x7f3ba2752b20> @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 [1063183] 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 [1063183] 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 ___________________________ 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 0x7f3ba2505ac0> @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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: """ Send a `GET` request. **Parameters**: See `httpx.request`. """ > return await self.request( "GET", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, timeout=timeout, ) /usr/lib/python3/dist-packages/httpx/_client.py:1548: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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, ) > response = await self.send( request, auth=auth, allow_redirects=allow_redirects, timeout=timeout ) /usr/lib/python3/dist-packages/httpx/_client.py:1371: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = async def send( self, request: Request, *, stream: bool = False, auth: typing.Union[AuthTypes, UnsetType] = UNSET, allow_redirects: bool = True, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> 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 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout) auth = self._build_request_auth(request, auth) > response = await self._send_handling_auth( request, auth=auth, timeout=timeout, allow_redirects=allow_redirects, history=[], ) /usr/lib/python3/dist-packages/httpx/_client.py:1406: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = auth = , timeout = Timeout(timeout=5.0) allow_redirects = True, history = [] async def _send_handling_auth( self, request: Request, auth: Auth, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: auth_flow = auth.async_auth_flow(request) request = await auth_flow.__anext__() for hook in self._event_hooks["request"]: await hook(request) while True: > response = await self._send_handling_redirects( request, timeout=timeout, allow_redirects=allow_redirects, history=history, ) /usr/lib/python3/dist-packages/httpx/_client.py:1444: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0), allow_redirects = True, history = [] async def _send_handling_redirects( self, request: Request, timeout: Timeout, allow_redirects: bool, history: typing.List[Response], ) -> Response: while True: if len(history) > self.max_redirects: raise TooManyRedirects( "Exceeded maximum allowed redirects.", request=request ) > response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1476: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = request = timeout = Timeout(timeout=5.0) async def _send_single_request( self, request: Request, timeout: Timeout ) -> Response: """ Sends a single request, without handling any redirections. """ transport = self._transport_for_url(request.url) timer = Timer() await timer.async_start() with map_exceptions(HTTPCORE_EXC_MAP, request=request): > (status_code, headers, stream, ext,) = await transport.arequest( request.method.encode(), request.url.raw, headers=request.headers.raw, stream=request.stream, # type: ignore ext={"timeout": timeout.as_dict()}, ) E AttributeError: 'AsyncHTTPProxy' object has no attribute 'arequest' /usr/lib/python3/dist-packages/httpx/_client.py:1502: AttributeError During handling of the above exception, another exception occurred: caplog = <_pytest.logging.LogCaptureFixture object at 0x7f3ba2505ac0> @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 [1063183] 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 [1063183] 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_message_logger ______________________________ caplog = <_pytest.logging.LogCaptureFixture object at 0x7f3ba2608ca0> @pytest.mark.asyncio async def test_message_logger(caplog): async def app(scope, receive, send): await receive() await send({"type": "http.response.start", "status": 200, "headers": []}) await send({"type": "http.response.body", "body": b"", "more_body": False}) caplog.set_level(TRACE_LOG_LEVEL, logger="uvicorn.asgi") caplog.set_level(TRACE_LOG_LEVEL) app = MessageLoggerMiddleware(app) async with httpx.AsyncClient(app=app, base_url="http://testserver") as client: > response = await client.get("/") tests/middleware/test_message_logger.py:20: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1')] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError ----------------------------- Captured stderr call ----------------------------- TRACE: 127.0.0.1:123 - ASGI [1] Started scope={'type': 'http', 'asgi': {'version': '3.0'}, 'http_version': '1.1', 'method': 'GET', 'headers': '<...>', 'scheme': 'http', 'path': '/', 'query_string': b'', 'server': ('testserver', None), 'client': ('127.0.0.1', 123), 'root_path': ''} TRACE: 127.0.0.1:123 - ASGI [1] Receive {'type': 'http.request', 'body': '<0 bytes>', 'more_body': True} TRACE: 127.0.0.1:123 - ASGI [1] Send {'type': 'http.response.start', 'status': 200, 'headers': '<...>'} TRACE: 127.0.0.1:123 - ASGI [1] Send {'type': 'http.response.body', 'body': '<0 bytes>', 'more_body': False} TRACE: 127.0.0.1:123 - ASGI [1] Completed ------------------------------ Captured log call ------------------------------- TRACE uvicorn.asgi:message_logger.py:44 127.0.0.1:123 - ASGI [1] Started scope={'type': 'http', 'asgi': {'version': '3.0'}, 'http_version': '1.1', 'method': 'GET', 'headers': '<...>', 'scheme': 'http', 'path': '/', 'query_string': b'', 'server': ('testserver', None), 'client': ('127.0.0.1', 123), 'root_path': ''} TRACE uvicorn.asgi:message_logger.py:44 127.0.0.1:123 - ASGI [1] Receive {'type': 'http.request', 'body': '<0 bytes>', 'more_body': True} TRACE uvicorn.asgi:message_logger.py:44 127.0.0.1:123 - ASGI [1] Send {'type': 'http.response.start', 'status': 200, 'headers': '<...>'} TRACE uvicorn.asgi:message_logger.py:44 127.0.0.1:123 - ASGI [1] Send {'type': 'http.response.body', 'body': '<0 bytes>', 'more_body': False} TRACE uvicorn.asgi:message_logger.py:44 127.0.0.1:123 - ASGI [1] Completed ________ test_proxy_headers_trusted_hosts[*-Remote: https://1.2.3.4:0] _________ trusted_hosts = '*', response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # trusted proxy ("127.0.0.1", "Remote: https://1.2.3.4:0"), (["127.0.0.1"], "Remote: https://1.2.3.4:0"), # trusted proxy list (["127.0.0.1", "10.0.0.1"], "Remote: https://1.2.3.4:0"), ("127.0.0.1, 10.0.0.1", "Remote: https://1.2.3.4:0"), # request from untrusted proxy ("192.168.0.1", "Remote: http://127.0.0.1:123"), ], ) async def test_proxy_headers_trusted_hosts( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"} > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:47: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError ____ test_proxy_headers_trusted_hosts[127.0.0.1-Remote: https://1.2.3.4:0] _____ trusted_hosts = '127.0.0.1', response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # trusted proxy ("127.0.0.1", "Remote: https://1.2.3.4:0"), (["127.0.0.1"], "Remote: https://1.2.3.4:0"), # trusted proxy list (["127.0.0.1", "10.0.0.1"], "Remote: https://1.2.3.4:0"), ("127.0.0.1, 10.0.0.1", "Remote: https://1.2.3.4:0"), # request from untrusted proxy ("192.168.0.1", "Remote: http://127.0.0.1:123"), ], ) async def test_proxy_headers_trusted_hosts( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"} > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:47: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError __ test_proxy_headers_trusted_hosts[trusted_hosts2-Remote: https://1.2.3.4:0] __ trusted_hosts = ['127.0.0.1'], response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # trusted proxy ("127.0.0.1", "Remote: https://1.2.3.4:0"), (["127.0.0.1"], "Remote: https://1.2.3.4:0"), # trusted proxy list (["127.0.0.1", "10.0.0.1"], "Remote: https://1.2.3.4:0"), ("127.0.0.1, 10.0.0.1", "Remote: https://1.2.3.4:0"), # request from untrusted proxy ("192.168.0.1", "Remote: http://127.0.0.1:123"), ], ) async def test_proxy_headers_trusted_hosts( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"} > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:47: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError __ test_proxy_headers_trusted_hosts[trusted_hosts3-Remote: https://1.2.3.4:0] __ trusted_hosts = ['127.0.0.1', '10.0.0.1'] response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # trusted proxy ("127.0.0.1", "Remote: https://1.2.3.4:0"), (["127.0.0.1"], "Remote: https://1.2.3.4:0"), # trusted proxy list (["127.0.0.1", "10.0.0.1"], "Remote: https://1.2.3.4:0"), ("127.0.0.1, 10.0.0.1", "Remote: https://1.2.3.4:0"), # request from untrusted proxy ("192.168.0.1", "Remote: http://127.0.0.1:123"), ], ) async def test_proxy_headers_trusted_hosts( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"} > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:47: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError _ test_proxy_headers_trusted_hosts[127.0.0.1, 10.0.0.1-Remote: https://1.2.3.4:0] _ trusted_hosts = '127.0.0.1, 10.0.0.1' response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # trusted proxy ("127.0.0.1", "Remote: https://1.2.3.4:0"), (["127.0.0.1"], "Remote: https://1.2.3.4:0"), # trusted proxy list (["127.0.0.1", "10.0.0.1"], "Remote: https://1.2.3.4:0"), ("127.0.0.1, 10.0.0.1", "Remote: https://1.2.3.4:0"), # request from untrusted proxy ("192.168.0.1", "Remote: http://127.0.0.1:123"), ], ) async def test_proxy_headers_trusted_hosts( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"} > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:47: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError __ test_proxy_headers_trusted_hosts[192.168.0.1-Remote: http://127.0.0.1:123] __ trusted_hosts = '192.168.0.1', response_text = 'Remote: http://127.0.0.1:123' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # trusted proxy ("127.0.0.1", "Remote: https://1.2.3.4:0"), (["127.0.0.1"], "Remote: https://1.2.3.4:0"), # trusted proxy list (["127.0.0.1", "10.0.0.1"], "Remote: https://1.2.3.4:0"), ("127.0.0.1, 10.0.0.1", "Remote: https://1.2.3.4:0"), # request from untrusted proxy ("192.168.0.1", "Remote: http://127.0.0.1:123"), ], ) async def test_proxy_headers_trusted_hosts( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = {"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"} > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:47: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError _______ test_proxy_headers_multiple_proxies[*-Remote: https://1.2.3.4:0] _______ trusted_hosts = '*', response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # all proxies are trusted ( ["127.0.0.1", "10.0.2.1", "192.168.0.2"], "Remote: https://1.2.3.4:0", ), # order doesn't matter ( ["10.0.2.1", "192.168.0.2", "127.0.0.1"], "Remote: https://1.2.3.4:0", ), # should set first untrusted as remote address (["192.168.0.2", "127.0.0.1"], "Remote: https://10.0.2.1:0"), ], ) async def test_proxy_headers_multiple_proxies( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = { "X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4, 10.0.2.1, 192.168.0.2", } > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:84: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError _ test_proxy_headers_multiple_proxies[trusted_hosts1-Remote: https://1.2.3.4:0] _ trusted_hosts = ['127.0.0.1', '10.0.2.1', '192.168.0.2'] response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # all proxies are trusted ( ["127.0.0.1", "10.0.2.1", "192.168.0.2"], "Remote: https://1.2.3.4:0", ), # order doesn't matter ( ["10.0.2.1", "192.168.0.2", "127.0.0.1"], "Remote: https://1.2.3.4:0", ), # should set first untrusted as remote address (["192.168.0.2", "127.0.0.1"], "Remote: https://10.0.2.1:0"), ], ) async def test_proxy_headers_multiple_proxies( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = { "X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4, 10.0.2.1, 192.168.0.2", } > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:84: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError _ test_proxy_headers_multiple_proxies[trusted_hosts2-Remote: https://1.2.3.4:0] _ trusted_hosts = ['10.0.2.1', '192.168.0.2', '127.0.0.1'] response_text = 'Remote: https://1.2.3.4:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # all proxies are trusted ( ["127.0.0.1", "10.0.2.1", "192.168.0.2"], "Remote: https://1.2.3.4:0", ), # order doesn't matter ( ["10.0.2.1", "192.168.0.2", "127.0.0.1"], "Remote: https://1.2.3.4:0", ), # should set first untrusted as remote address (["192.168.0.2", "127.0.0.1"], "Remote: https://10.0.2.1:0"), ], ) async def test_proxy_headers_multiple_proxies( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = { "X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4, 10.0.2.1, 192.168.0.2", } > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:84: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError _ test_proxy_headers_multiple_proxies[trusted_hosts3-Remote: https://10.0.2.1:0] _ trusted_hosts = ['192.168.0.2', '127.0.0.1'] response_text = 'Remote: https://10.0.2.1:0' @pytest.mark.asyncio @pytest.mark.parametrize( ("trusted_hosts", "response_text"), [ # always trust ("*", "Remote: https://1.2.3.4:0"), # all proxies are trusted ( ["127.0.0.1", "10.0.2.1", "192.168.0.2"], "Remote: https://1.2.3.4:0", ), # order doesn't matter ( ["10.0.2.1", "192.168.0.2", "127.0.0.1"], "Remote: https://1.2.3.4:0", ), # should set first untrusted as remote address (["192.168.0.2", "127.0.0.1"], "Remote: https://10.0.2.1:0"), ], ) async def test_proxy_headers_multiple_proxies( trusted_hosts: Union[List[str], str], response_text: str ) -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts) async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = { "X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4, 10.0.2.1, 192.168.0.2", } > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:84: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError __________________ test_proxy_headers_invalid_x_forwarded_for __________________ @pytest.mark.asyncio async def test_proxy_headers_invalid_x_forwarded_for() -> None: app_with_middleware = ProxyHeadersMiddleware(app, trusted_hosts="*") async with httpx.AsyncClient( app=app_with_middleware, base_url="http://testserver" ) as client: headers = httpx.Headers( { "X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4, \xf0\xfd\xfd\xfd", }, encoding="latin-1", ) > response = await client.get("/", headers=headers) tests/middleware/test_proxy_headers.py:103: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'X-Forwarded-Proto', b'https'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError ________________________________ test_wsgi_get _________________________________ @pytest.mark.asyncio async def test_wsgi_get() -> None: app = WSGIMiddleware(hello_world) async with httpx.AsyncClient(app=app, base_url="http://testserver") as client: > response = await client.get("/") tests/middleware/test_wsgi.py:56: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1')] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError ________________________________ test_wsgi_post ________________________________ @pytest.mark.asyncio async def test_wsgi_post() -> None: app = WSGIMiddleware(echo_body) async with httpx.AsyncClient(app=app, base_url="http://testserver") as client: > response = await client.post("/", json={"example": 123}) tests/middleware/test_wsgi.py:65: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1633: in post return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'POST' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1'), (b'Content-Length', b'16'), ...] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError ______________________________ test_wsgi_exc_info ______________________________ @pytest.mark.asyncio async def test_wsgi_exc_info() -> None: # Note that we're testing the WSGI app directly here. # The HTTP protocol implementations would catch this error and return 500. app = WSGIMiddleware(return_exc_info) async with httpx.AsyncClient(app=app, base_url="http://testserver") as client: with pytest.raises(RuntimeError): response = await client.get("/") app = WSGIMiddleware(return_exc_info) transport = httpx.ASGITransport( app=app, raise_app_exceptions=False, ) async with httpx.AsyncClient( transport=transport, base_url="http://testserver" ) as client: > response = await client.get("/") tests/middleware/test_wsgi.py:97: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/lib/python3/dist-packages/httpx/_client.py:1548: in get return await self.request( /usr/lib/python3/dist-packages/httpx/_client.py:1371: in request response = await self.send( /usr/lib/python3/dist-packages/httpx/_client.py:1406: in send response = await self._send_handling_auth( /usr/lib/python3/dist-packages/httpx/_client.py:1444: in _send_handling_auth response = await self._send_handling_redirects( /usr/lib/python3/dist-packages/httpx/_client.py:1476: in _send_handling_redirects response = await self._send_single_request(request, timeout) /usr/lib/python3/dist-packages/httpx/_client.py:1502: in _send_single_request (status_code, headers, stream, ext,) = await transport.arequest( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = , method = b'GET' url = (b'http', b'testserver', None, b'/') headers = [(b'Host', b'testserver'), (b'Accept', b'*/*'), (b'Accept-Encoding', b'gzip, deflate'), (b'Connection', b'keep-alive'), (b'User-Agent', b'python-httpx/0.16.1')] stream = ext = {'timeout': {'connect': 5.0, 'pool': 5.0, 'read': 5.0, 'write': 5.0}} async def arequest( self, method: bytes, url: Tuple[bytes, bytes, Optional[int], bytes], headers: List[Tuple[bytes, bytes]] = None, stream: httpcore.AsyncByteStream = None, ext: dict = None, ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]: headers = [] if headers is None else headers stream = httpcore.PlainByteStream(content=b"") if stream is None else stream # ASGI scope. scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method.decode(), "headers": [(k.lower(), v) for (k, v) in headers], "scheme": scheme.decode("ascii"), "path": unquote(path.decode("ascii")), "query_string": query, "server": (host.decode("ascii"), port), "client": self.client, "root_path": self.root_path, } # Request. request_body_chunks = stream.__aiter__() request_complete = False # Response. status_code = None response_headers = None body_parts = [] response_started = False response_complete = create_event() # ASGI callables. async def receive() -> dict: nonlocal request_complete if request_complete: await response_complete.wait() return {"type": "http.disconnect"} try: body = await request_body_chunks.__anext__() except StopAsyncIteration: request_complete = True return {"type": "http.request", "body": b"", "more_body": False} return {"type": "http.request", "body": body, "more_body": True} async def send(message: dict) -> None: nonlocal status_code, response_headers, response_started if message["type"] == "http.response.start": assert not response_started status_code = message["status"] response_headers = message.get("headers", []) response_started = True elif message["type"] == "http.response.body": assert not response_complete.is_set() body = message.get("body", b"") more_body = message.get("more_body", False) if body and method != b"HEAD": body_parts.append(body) if not more_body: response_complete.set() try: await self.app(scope, receive, send) except Exception: if self.raise_app_exceptions or not response_complete.is_set(): raise assert response_complete.is_set() assert status_code is not None assert response_headers is not None > stream = httpcore.PlainByteStream(content=b"".join(body_parts)) E AttributeError: module 'httpcore' has no attribute 'PlainByteStream' /usr/lib/python3/dist-packages/httpx/_transports/asgi.py:157: AttributeError ________________ 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 0x7f3ba2505d90>], 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 0x7f3ba2505d90>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba274ef10>], 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 0x7f3ba274ef10>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba24569d0>], 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 0x7f3ba24569d0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba24651c0>], 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 0x7f3ba24651c0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0a08280>], 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 0x7f3ba0a08280>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba248b640>], 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 0x7f3ba248b640>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2798820>], 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 0x7f3ba2798820>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba274e7c0>], 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 0x7f3ba274e7c0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba27f6ca0>], 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 0x7f3ba27f6ca0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2545b20>], 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 0x7f3ba2545b20>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba24a7a60>], 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 0x7f3ba24a7a60>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2638370>], 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 0x7f3ba2638370>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba081df40>], 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 0x7f3ba081df40>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2649520>], 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 0x7f3ba2649520>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba256fd90>], 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 0x7f3ba256fd90>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba271d4c0>], 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 0x7f3ba271d4c0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2785700>], 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 0x7f3ba2785700>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2469eb0>], 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 0x7f3ba2469eb0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba27b2b50>], 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 0x7f3ba27b2b50>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba254f880>], 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 0x7f3ba254f880>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba26ad6d0>], 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 0x7f3ba26ad6d0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba24c6a60>], 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 0x7f3ba24c6a60>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3b937c69a0>], 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 0x7f3b937c69a0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba078d820>], 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 0x7f3ba078d820>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba23276d0>], 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 0x7f3ba23276d0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba250aee0>], 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 0x7f3ba250aee0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba27f8970>], 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 0x7f3ba27f8970>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2545bb0>], 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 0x7f3ba2545bb0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba27930d0>], 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 0x7f3ba27930d0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0205160>], 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 0x7f3ba0205160>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba01f7f40>], 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 0x7f3ba01f7f40>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba23c4c40>], 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 0x7f3ba23c4c40>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0a99b50>], 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 0x7f3ba0a99b50>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0aa8040>], 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 0x7f3ba0aa8040>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba270d8b0>], 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 0x7f3ba270d8b0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0ab6040>], 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 0x7f3ba0ab6040>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2543eb0>], 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 0x7f3ba2543eb0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba09fba00>], 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 0x7f3ba09fba00>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba07705e0>], 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 0x7f3ba07705e0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba073ed00>], 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 0x7f3ba073ed00>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0ace4c0>], 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 0x7f3ba0ace4c0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba27f8b20>], 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 0x7f3ba27f8b20>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2724c70>], 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 0x7f3ba2724c70>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3b937c65e0>], 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 0x7f3b937c65e0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba231f280>], 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 0x7f3ba231f280>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0aa86a0>], 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 0x7f3ba0aa86a0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2484dc0>], 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 0x7f3ba2484dc0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2454d60>], 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 0x7f3ba2454d60>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba081d250>], 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 0x7f3ba081d250>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba08e7100>], 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 0x7f3ba08e7100>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba088ea90>], 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 0x7f3ba088ea90>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba01f7460>], 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 0x7f3ba01f7460>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2351130>], 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 0x7f3ba2351130>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba254f730>], 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 0x7f3ba254f730>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0ad3520>], 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 0x7f3ba0ad3520>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba23350a0>], 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 0x7f3ba23350a0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba25a9be0>], 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 0x7f3ba25a9be0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba23ec070>], 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 0x7f3ba23ec070>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2696c40>], 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 0x7f3ba2696c40>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0826e50>], 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 0x7f3ba0826e50>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3b937c6e20>], 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 0x7f3b937c6e20>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0205a00>], 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 0x7f3ba0205a00>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0acea60>], 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 0x7f3ba0acea60>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba26ad5e0>], 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 0x7f3ba26ad5e0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba25d3430>], 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 0x7f3ba25d3430>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0875730>], 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 0x7f3ba0875730>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba256ef70>], 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 0x7f3ba256ef70>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0956ee0>], 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 0x7f3ba0956ee0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba082bfa0>], 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 0x7f3ba082bfa0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2327940>], 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 0x7f3ba2327940>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba07f9040>], 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 0x7f3ba07f9040>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba086db50>], 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 0x7f3ba086db50>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0987c70>], 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 0x7f3ba0987c70>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0a47550>], 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 0x7f3ba0a47550>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba247be80>], 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 0x7f3ba247be80>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3b937c6070>], 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 0x7f3b937c6070>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba23cf640>], 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 0x7f3ba23cf640>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2491040>], 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 0x7f3ba2491040>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba064e970>], 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 0x7f3ba064e970>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0a0e400>], 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 0x7f3ba0a0e400>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0a24550>], 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 0x7f3ba0a24550>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba248b040>], 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 0x7f3ba248b040>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba24960d0>], 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 0x7f3ba24960d0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2adbfa0>], 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 0x7f3ba2adbfa0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba23090a0>], 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 0x7f3ba23090a0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba096aa90>], 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 0x7f3ba096aa90>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba07177c0>], 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 0x7f3ba07177c0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0604d00>], 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 0x7f3ba0604d00>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba07911f0>], 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 0x7f3ba07911f0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2548790>], 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 0x7f3ba2548790>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0a6eb80>], 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 0x7f3ba0a6eb80>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba02b03d0>], 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 0x7f3ba02b03d0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2368670>], 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 0x7f3ba2368670>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2351eb0>], 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 0x7f3ba2351eb0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3b937c6e20>], 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 0x7f3b937c6e20>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba06181f0>], 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 0x7f3ba06181f0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2545dc0>], 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 0x7f3ba2545dc0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba2571d60>], 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 0x7f3ba2571d60>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba0999070>], 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 0x7f3ba0999070>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba24913a0>], 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 0x7f3ba24913a0>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3b937c5c10>], 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 0x7f3b937c5c10>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3b937c6760>], 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 0x7f3b937c6760>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba06f3610>], 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 0x7f3ba06f3610>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] 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 0x7f3ba23d0640>], 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 0x7f3ba23d0640>], 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 [1063183] INFO: Shutting down ------------------------------ Captured log call ------------------------------- INFO uvicorn.error:server.py:84 Started server process [1063183] INFO uvicorn.error:server.py:263 Shutting down =============== 129 failed, 195 passed, 24 deselected in 30.08s ================ 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. sys:1: RuntimeWarning: coroutine 'BaseEventLoop._create_server_getaddrinfo' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback 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. 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. E: pybuild pybuild:354: test: plugin distutils failed with: exit code=1: cd /build/python-uvicorn-0.15.0/.pybuild/cpython3_3.9/build; python3.9 -m pytest -k 'not test_run and not test_invalid_upgrade and not test_default_headers and not test_trace_logging' dh_auto_test: error: pybuild --test --test-pytest -i python{version} -p 3.9 returned exit code 13 make: *** [debian/rules:10: binary] Error 25 dpkg-buildpackage: error: debian/rules binary subprocess returned exit status 2 I: copying local configuration E: Failed autobuilding of package I: user script /var/cache/pbuilder/build/1055192/tmp/hooks/C00notify-send starting debconf: delaying package configuration, since apt-utils is not installed I: user script /var/cache/pbuilder/build/1055192/tmp/hooks/C00notify-send finished W: execute priv not set on file C01basemap, not executing. W: execute priv not set on file C01mpl-sphinx, not executing. W: execute priv not set on file C10python-sphinx-errors, not executing. I: user script /var/cache/pbuilder/build/1055192/tmp/hooks/C10shell starting debconf: delaying package configuration, since apt-utils is not installed