OSError:aiohttp测试中的[Errno 10048]

时间:2016-10-31 20:29:09

标签: python-3.x pytest python-asyncio aiohttp

我想为我的aiohttp web应用程序编写一些py.tests。我从一个简单的测试开始:

from aiohttp import web

async def hello(request):
    return web.Response(body=b'Hello, world')

def create_app(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', hello)
    return app

async def test_hello(test_client):
    client = await test_client(create_app)
    resp = await client.get('/')
    assert resp.status == 200
    text = await resp.text()
    assert 'Hello, world' in text

但是当我运行它时,它会失败并显示以下消息:

...
# Disable IPv4/IPv6 dual stack support (enabled by
# default on Linux) which makes a single socket
# listen on both address families.
if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
    sock.setsockopt(socket.IPPROTO_IPV6,
                    socket.IPV6_V6ONLY,
                    True)
try:
    sock.bind(sa)
except OSError as err:
    raise OSError(err.errno, 'error while attempting '
                  'to bind on address %r: %s'
>   % (sa, err.strerror.lower()))
E   OSError: [Errno 10048] error while attempting to bind on address ('127.0.0.1', 65214): обычно разрешается только одно использование адреса сокета (протокол/сетевой адрес/порт)

C:\Python35\lib\asyncio\base_events.py:962: OSError
========================== 1 failed in 0.66 seconds ===========================

以下是aiohttp \ test_utils.py的内容:

def unused_port():
    """Return a port that is unused on the current host."""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('127.0.0.1', 0))
        return s.getsockname()[1]


class TestServer:
    def __init__(self, app, *, scheme="http", host='127.0.0.1'):
        self.app = app
        self._loop = app.loop
        self.port = None
        self.server = None
        self.handler = None
        self._root = None
        self.host = host
        self.scheme = scheme
        self._closed = False

    @asyncio.coroutine
    def start_server(self, **kwargs):
        if self.server:
            return
        self.port = unused_port()
        self._root = '{}://{}:{}'.format(self.scheme, self.host, self.port)
        self.handler = self.app.make_handler(**kwargs)

我发现如果我手动指定self.port,例如65214,然后运行测试,它就会成功结束。也许有人可以解释为什么会发生此错误?我使用的是Windows 7 x64,Python 3.5.2和virtualenv,aiohttp 1.0.5,pytest 3.0.3,pytest-aiohttp 0.1.3。

0 个答案:

没有答案