|
1 | 1 | import os |
| 2 | +import time |
2 | 3 | import uuid |
3 | 4 | from collections.abc import Generator |
4 | 5 |
|
5 | 6 | import pytest |
6 | 7 | from docker.errors import DockerException |
7 | 8 | from elasticsearch import Elasticsearch |
| 9 | +from elasticsearch.exceptions import ConnectionError as ESConnectionError |
8 | 10 | from testcontainers.core.container import DockerContainer |
9 | 11 | from testcontainers.core.waiting_utils import wait_for_logs |
10 | 12 |
|
11 | 13 | ES_IMAGE = os.environ.get("ES_TEST_IMAGE", "docker.elastic.co/elasticsearch/elasticsearch:9.1.3") |
12 | 14 | ES_PORT = 9200 |
13 | 15 |
|
14 | 16 |
|
| 17 | +def _wait_for_elasticsearch(url: str, timeout: float = 60.0) -> None: |
| 18 | + deadline = time.monotonic() + timeout |
| 19 | + last_error: Exception | None = None |
| 20 | + |
| 21 | + while time.monotonic() < deadline: |
| 22 | + client = Elasticsearch(hosts=[url], verify_certs=False) |
| 23 | + try: |
| 24 | + client.info() |
| 25 | + return |
| 26 | + except ESConnectionError as exc: |
| 27 | + last_error = exc |
| 28 | + time.sleep(1) |
| 29 | + finally: |
| 30 | + client.close() |
| 31 | + |
| 32 | + raise TimeoutError(f"Elasticsearch did not become ready at {url}") from last_error |
| 33 | + |
| 34 | + |
15 | 35 | @pytest.fixture(scope="session") |
16 | 36 | def es_url() -> Generator[str, None, None]: |
17 | 37 | """Yield a base URL for an Elasticsearch cluster. |
@@ -45,7 +65,9 @@ def es_url() -> Generator[str, None, None]: |
45 | 65 | wait_for_logs(container, "started") |
46 | 66 | host = container.get_container_host_ip() |
47 | 67 | port = container.get_exposed_port(ES_PORT) |
48 | | - yield f"http://{host}:{port}" |
| 68 | + url = f"http://{host}:{port}" |
| 69 | + _wait_for_elasticsearch(url) |
| 70 | + yield url |
49 | 71 | finally: |
50 | 72 | container.stop() |
51 | 73 |
|
|
0 commit comments