python network_error ai_generated true

ConnectionRefusedError: [Errno 111] 连接被拒绝

ConnectionRefusedError: [Errno 111] Connection refused

ID: python/pytest-docker-compose-not-ready

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2026-01-15首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

测试尝试连接尚未准备好的服务(例如数据库、Redis)。这通常发生在 CI 中使用 docker-compose 而没有等待服务健康时。

English

A test tries to connect to a service (e.g., database, Redis) that is not yet ready. This often happens in CI when using docker-compose without waiting for services to be healthy.

generic

解决方案

  1. 98% 成功率
    In docker-compose.yml, add healthcheck to the service and use depends_on with condition: service_healthy.
  2. 95% 成功率
    pip install pytest-docker
    Then use the docker_services fixture to wait for ports.
  3. 90% 成功率
    @pytest.fixture
    def db_connection():
        for _ in range(30):
            try:
                conn = connect()
                break
            except ConnectionRefusedError:
                time.sleep(1)
        else:
            raise
        yield conn
        conn.close()

无效尝试

常见但无效的做法:

  1. 80% 失败

    This is unreliable; services may take longer or shorter to start, leading to flaky tests.

  2. 90% 失败

    If the service never starts, the test hangs forever.

  3. 95% 失败

    This hides the issue and reduces test coverage.