python network_error ai_generated true

OSError: [Errno 98] 地址已被占用 在 tests/test_http.py::test_fetch 的设置期间 端口 8080 已被占用

OSError: [Errno 98] Address already in use during setup of tests/test_http.py::test_fetch port 8080 is already bound

ID: python/pytest-httpserver-port-in-use

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-06-27首次发现

版本兼容性

版本状态引入弃用备注
1.0 active

根因分析

之前的测试运行或其他进程仍占用该端口。在使用 pytest-httpserver、responses 或在 session 作用域 fixture 中启动但未拆除的本地开发服务器时很常见。

English

A previous test run or another process is still holding the port. Common with pytest-httpserver, responses, or a local dev server started in a session-scoped fixture that was not torn down.

generic

解决方案

  1. 97% 成功率
    from pytest_httpserver import HTTPServer
    
    def test_fetch(httpserver: HTTPServer):
        httpserver.expect_request('/api').respond_with_json({'ok': True})
        url = httpserver.url_for('/api')  # uses assigned port
        assert fetch(url) == {'ok': True}
  2. 95% 成功率
    @pytest.fixture(scope='session')
    def server():
        srv = HTTPServer()
        srv.start()
        yield srv
        srv.stop()  # critical

无效尝试

常见但无效的做法:

  1. 80% 失败

    Next run someone else uses 8081; whack-a-mole with no root fix and CI containers may have different free ports.

  2. 90% 失败

    The port stays bound between retries; retries fail immediately.