|
| 1 | +import time |
| 2 | +from time import sleep |
| 3 | + |
| 4 | +import grpc |
| 5 | +from grpc_health.v1 import health_pb2, health_pb2_grpc |
| 6 | +from testcontainers.core.container import DockerContainer |
| 7 | +from testcontainers.core.waiting_utils import wait_container_is_ready, wait_for_logs |
| 8 | + |
| 9 | +HEALTH_CHECK = 8014 |
| 10 | + |
| 11 | + |
| 12 | +class FlagDContainer(DockerContainer): |
| 13 | + def __init__( |
| 14 | + self, |
| 15 | + image: str = "ghcr.io/open-feature/flagd-testbed:v0.5.10", |
| 16 | + port: int = 8013, |
| 17 | + **kwargs, |
| 18 | + ) -> None: |
| 19 | + super().__init__(image, **kwargs) |
| 20 | + self.port = port |
| 21 | + self.with_exposed_ports(self.port, HEALTH_CHECK) |
| 22 | + |
| 23 | + def start(self) -> "FlagDContainer": |
| 24 | + super().start() |
| 25 | + self._checker(self.get_container_host_ip(), self.get_exposed_port(HEALTH_CHECK)) |
| 26 | + return self |
| 27 | + |
| 28 | + @wait_container_is_ready(ConnectionError) |
| 29 | + def _checker(self, host: str, port: int) -> None: |
| 30 | + # First we wait for Flagd to say it's listening |
| 31 | + wait_for_logs( |
| 32 | + self, |
| 33 | + "Flag IResolver listening at", |
| 34 | + 5, |
| 35 | + ) |
| 36 | + |
| 37 | + time.sleep(1) |
| 38 | + # Second we use the GRPC health check endpoint |
| 39 | + with grpc.insecure_channel(host + ":" + port) as channel: |
| 40 | + health_stub = health_pb2_grpc.HealthStub(channel) |
| 41 | + |
| 42 | + def health_check_call(stub: health_pb2_grpc.HealthStub): |
| 43 | + request = health_pb2.HealthCheckRequest() |
| 44 | + resp = stub.Check(request) |
| 45 | + if resp.status == health_pb2.HealthCheckResponse.SERVING: |
| 46 | + return True |
| 47 | + elif resp.status == health_pb2.HealthCheckResponse.NOT_SERVING: |
| 48 | + return False |
| 49 | + |
| 50 | + # Should succeed |
| 51 | + # Check health status every 1 second for 30 seconds |
| 52 | + ok = False |
| 53 | + for _ in range(30): |
| 54 | + ok = health_check_call(health_stub) |
| 55 | + if ok: |
| 56 | + break |
| 57 | + sleep(1) |
| 58 | + |
| 59 | + if not ok: |
| 60 | + raise ConnectionError("flagD not ready in time") |
0 commit comments