python network_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-06-27First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active

Root Cause

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

中文

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

Workarounds

  1. 97% success
    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% success
    @pytest.fixture(scope='session')
    def server():
        srv = HTTPServer()
        srv.start()
        yield srv
        srv.stop()  # critical

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 90% fail

    The port stays bound between retries; retries fail immediately.