|
| 1 | +import os |
| 2 | +import secrets |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +from testcontainers.core.container import DockerContainer |
| 6 | +from testcontainers.core.wait_strategies import HttpWaitStrategy |
| 7 | + |
| 8 | + |
| 9 | +class MeilisearchContainer(DockerContainer): |
| 10 | + """ |
| 11 | + Meilisearch container. |
| 12 | +
|
| 13 | + Example: |
| 14 | +
|
| 15 | + .. doctest:: |
| 16 | +
|
| 17 | + >>> from meilisearch import Client |
| 18 | + >>> from testcontainers.community.meilisearch import MeilisearchContainer |
| 19 | +
|
| 20 | + >>> with MeilisearchContainer() as meili: |
| 21 | + ... client = Client(meili.get_connection_url(), meili.get_master_key()) |
| 22 | + ... client.health()["status"] |
| 23 | + 'available' |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + image: str = "getmeili/meilisearch:v1.53", |
| 29 | + port: int = 7700, |
| 30 | + meili_env: Optional[str] = None, |
| 31 | + master_key: Optional[str] = None, |
| 32 | + **kwargs, |
| 33 | + ) -> None: |
| 34 | + super().__init__(image=image, **kwargs) |
| 35 | + |
| 36 | + self.port = port |
| 37 | + self.meili_env = meili_env or os.environ.get("MEILI_ENV", "production") |
| 38 | + self.master_key = master_key or os.environ.get("MEILI_MASTER_KEY", secrets.token_urlsafe(32)) |
| 39 | + |
| 40 | + if self.meili_env == "production" and len(self.master_key.encode()) < 16: |
| 41 | + raise ValueError("master key must be at least 16 bytes when MEILI_ENV=production") |
| 42 | + |
| 43 | + self.with_exposed_ports(self.port) |
| 44 | + self.with_env("MEILI_ENV", self.meili_env) |
| 45 | + self.with_env("MEILI_MASTER_KEY", self.master_key) |
| 46 | + self.with_env("MEILI_NO_ANALYTICS", "true") |
| 47 | + |
| 48 | + self.waiting_for(HttpWaitStrategy(self.port, "/health")) |
| 49 | + |
| 50 | + def get_master_key(self) -> str: |
| 51 | + return self.master_key |
| 52 | + |
| 53 | + def get_connection_url(self) -> str: |
| 54 | + host = self.get_container_host_ip() |
| 55 | + port = self.get_exposed_port(self.port) |
| 56 | + return f"http://{host}:{port}" |
0 commit comments