|
| 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 socket |
| 14 | + |
| 15 | +from testcontainers.core.container import DockerContainer |
| 16 | +from testcontainers.core.waiting_utils import wait_container_is_ready |
| 17 | + |
| 18 | + |
| 19 | +class MemcachedNotReady(Exception): |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +class MemcachedContainer(DockerContainer): |
| 24 | + """ |
| 25 | + Test container for Memcached. The example below spins up a Memcached server |
| 26 | +
|
| 27 | + Example: |
| 28 | +
|
| 29 | + .. doctest:: |
| 30 | +
|
| 31 | + >>> from testcontainers.memcached import MemcachedContainer |
| 32 | +
|
| 33 | + >>> with MemcachedContainer() as memcached_container: |
| 34 | + ... host, port = memcached_container.get_host_and_port() |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, image="memcached:1", port_to_expose=11211, **kwargs): |
| 38 | + super().__init__(image, **kwargs) |
| 39 | + self.port_to_expose = port_to_expose |
| 40 | + self.with_exposed_ports(port_to_expose) |
| 41 | + |
| 42 | + @wait_container_is_ready(MemcachedNotReady) |
| 43 | + def _connect(self): |
| 44 | + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 45 | + host = self.get_container_host_ip() |
| 46 | + port = int(self.get_exposed_port(self.port_to_expose)) |
| 47 | + s.connect((host, port)) |
| 48 | + s.sendall(b"stats\n\r") |
| 49 | + data = s.recv(1024) |
| 50 | + if len(data) == 0: |
| 51 | + raise MemcachedNotReady("Memcached not ready yet") |
| 52 | + |
| 53 | + def start(self): |
| 54 | + super().start() |
| 55 | + self._connect() |
| 56 | + return self |
| 57 | + |
| 58 | + def get_host_and_port(self): |
| 59 | + return self.get_container_host_ip(), int(self.get_exposed_port(self.port_to_expose)) |
0 commit comments