# ConnectionRefusedError: [Errno 111] 连接被拒绝

- **ID:** `python/pytest-docker-compose-not-ready`
- **领域:** python
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

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()
   ```

## 无效尝试

- **** — This is unreliable; services may take longer or shorter to start, leading to flaky tests. (80% 失败率)
- **** — If the service never starts, the test hangs forever. (90% 失败率)
- **** — This hides the issue and reduces test coverage. (95% 失败率)
