|
| 1 | +# |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 3 | +# not use this file except in compliance with the License. You may obtain |
| 4 | +# a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 10 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 11 | +# License for the specific language governing permissions and limitations |
| 12 | +# under the License. |
| 13 | +import os |
| 14 | +from typing import ClassVar, Optional |
| 15 | + |
| 16 | +from testcontainers.community.generic.sql import SqlContainer |
| 17 | +from testcontainers.core.utils import raise_for_deprecated_parameter |
| 18 | +from testcontainers.core.wait_strategies import HttpWaitStrategy |
| 19 | + |
| 20 | +# CrateDB's HTTP interface. The SQLAlchemy `crate://` dialect talks to CrateDB |
| 21 | +# over HTTP, so this is the port used for connection URLs and readiness checks. |
| 22 | +HTTP_PORT = 4200 |
| 23 | +# CrateDB's PostgreSQL wire-protocol interface, exposed for convenience. |
| 24 | +PSQL_PORT = 5432 |
| 25 | + |
| 26 | + |
| 27 | +class CrateDBContainer(SqlContainer): |
| 28 | + """ |
| 29 | + CrateDB database container. |
| 30 | +
|
| 31 | + Example: |
| 32 | +
|
| 33 | + The example spins up a CrateDB database and connects to it using |
| 34 | + SQLAlchemy and the ``sqlalchemy-cratedb`` dialect, which talks to |
| 35 | + CrateDB over its HTTP interface (port 4200). |
| 36 | +
|
| 37 | + .. doctest:: |
| 38 | +
|
| 39 | + >>> from testcontainers.community.cratedb import CrateDBContainer |
| 40 | + >>> import sqlalchemy |
| 41 | +
|
| 42 | + >>> with CrateDBContainer("crate:5.10") as cratedb: |
| 43 | + ... engine = sqlalchemy.create_engine(cratedb.get_connection_url()) |
| 44 | + ... with engine.begin() as connection: |
| 45 | + ... result = connection.execute(sqlalchemy.text("select name from sys.cluster")) |
| 46 | + ... cluster_name, = result.fetchone() |
| 47 | + """ |
| 48 | + |
| 49 | + # Default command-line options. CrateDB needs single-node discovery to run |
| 50 | + # as a one-node cluster suitable for testing. |
| 51 | + CMD_OPTS: ClassVar[list[tuple[str, str]]] = [("discovery.type", "single-node")] |
| 52 | + |
| 53 | + def __init__( |
| 54 | + self, |
| 55 | + image: str = "crate/crate:latest", |
| 56 | + port: int = HTTP_PORT, |
| 57 | + username: Optional[str] = None, |
| 58 | + password: Optional[str] = None, |
| 59 | + dialect: str = "crate", |
| 60 | + cmd_opts: Optional[list[tuple[str, str]]] = None, |
| 61 | + **kwargs, |
| 62 | + ) -> None: |
| 63 | + """ |
| 64 | + :param image: Docker image name (with optional tag). |
| 65 | + :param port: container port used to build the connection URL; defaults |
| 66 | + to the HTTP port (4200) used by the ``crate://`` dialect. |
| 67 | + :param username: username for the DB; falls back to the ``CRATEDB_USER`` |
| 68 | + environment variable, then ``crate``. |
| 69 | + :param password: password for the DB; falls back to the |
| 70 | + ``CRATEDB_PASSWORD`` environment variable, then ``crate``. |
| 71 | + :param dialect: SQLAlchemy dialect used in the connection URL. |
| 72 | + :param cmd_opts: extra ``-C<key>=<value>`` options passed to CrateDB, |
| 73 | + merged over (and able to override) the defaults. |
| 74 | + """ |
| 75 | + raise_for_deprecated_parameter(kwargs, "user", "username") |
| 76 | + # Readiness is signaled by CrateDB's HTTP interface returning 200; this |
| 77 | + # keeps startup free of any database client library. |
| 78 | + super().__init__(image, wait_strategy=HttpWaitStrategy(HTTP_PORT).for_status_code(200), **kwargs) |
| 79 | + |
| 80 | + cmd_opts = cmd_opts or [] |
| 81 | + default_cmd_opts = [s for s in self.CMD_OPTS if s[0] not in {k[0] for k in cmd_opts}] |
| 82 | + self._command = self._build_cmd([*default_cmd_opts, *cmd_opts]) |
| 83 | + |
| 84 | + self.username = username or os.environ.get("CRATEDB_USER", "crate") |
| 85 | + self.password = password or os.environ.get("CRATEDB_PASSWORD", "crate") |
| 86 | + self.port = port |
| 87 | + self.dialect = dialect |
| 88 | + |
| 89 | + self.with_exposed_ports(HTTP_PORT, PSQL_PORT) |
| 90 | + |
| 91 | + @staticmethod |
| 92 | + def _build_cmd(opts: list[tuple[str, str]]) -> str: |
| 93 | + """Render a CrateDB ``-C<key>=<value> ...`` command-line string.""" |
| 94 | + cmd = [] |
| 95 | + for key, val in opts: |
| 96 | + if isinstance(val, bool): |
| 97 | + val = str(val).lower() |
| 98 | + cmd.append(f"-C{key}={val}") |
| 99 | + return " ".join(cmd) |
| 100 | + |
| 101 | + def _configure(self) -> None: |
| 102 | + self.with_env("CRATEDB_USER", self.username) |
| 103 | + self.with_env("CRATEDB_PASSWORD", self.password) |
| 104 | + |
| 105 | + def get_connection_url(self, host: Optional[str] = None) -> str: |
| 106 | + return self._create_connection_url( |
| 107 | + dialect=self.dialect, |
| 108 | + username=self.username, |
| 109 | + password=self.password, |
| 110 | + host=host, |
| 111 | + port=self.port, |
| 112 | + ) |
0 commit comments