|
| 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 Optional |
| 15 | + |
| 16 | +from cassandra.cluster import Cluster, NoHostAvailable |
| 17 | + |
| 18 | +from testcontainers.core.container import DockerContainer |
| 19 | +from testcontainers.core.waiting_utils import wait_container_is_ready |
| 20 | + |
| 21 | + |
| 22 | +class CassandraContainer(DockerContainer): |
| 23 | + """ |
| 24 | + Cassandra database container. |
| 25 | +
|
| 26 | + Example: |
| 27 | +
|
| 28 | + .. doctest:: |
| 29 | +
|
| 30 | + >>> from testcontainers.cassandra import CassandraContainer |
| 31 | +
|
| 32 | + >>> with CassandraContainer("cassandra:latest") as cassandra: |
| 33 | + ... db = cassandra.get_connection_client().test |
| 34 | + ... # Insert a database entry |
| 35 | + ... result = db.restaurants.insert_one( |
| 36 | + ... { |
| 37 | + ... "address": { |
| 38 | + ... "street": "2 Avenue", |
| 39 | + ... "zipcode": "10075", |
| 40 | + ... "building": "1480", |
| 41 | + ... "coord": [-73.9557413, 40.7720266] |
| 42 | + ... }, |
| 43 | + ... "borough": "Manhattan", |
| 44 | + ... "cuisine": "Italian", |
| 45 | + ... "name": "Vella", |
| 46 | + ... "restaurant_id": "41704620" |
| 47 | + ... } |
| 48 | + ... ) |
| 49 | + ... # Find the restaurant document |
| 50 | + ... cursor = db.restaurants.find({"borough": "Manhattan"}) |
| 51 | + """ |
| 52 | + |
| 53 | + def __init__( |
| 54 | + self, |
| 55 | + image: str = "cassandra:latest", |
| 56 | + port: int = 9042, |
| 57 | + **kwargs |
| 58 | + ) -> None: |
| 59 | + super().__init__(image=image, **kwargs) |
| 60 | + self.port = port |
| 61 | + self.with_exposed_ports(self.port) |
| 62 | + self.cluster: Optional[Cluster] = None |
| 63 | + |
| 64 | + @wait_container_is_ready(NoHostAvailable) |
| 65 | + def _connect(self): |
| 66 | + self.cluster = Cluster([self.get_container_host_ip()], |
| 67 | + port=self.get_exposed_port(self.port)) |
| 68 | + self.cluster.connect() |
| 69 | + |
| 70 | + def start(self) -> "CassandraContainer": |
| 71 | + super().start() |
| 72 | + self._connect() |
| 73 | + return self |
0 commit comments