|
| 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 | +from typing import Optional |
| 14 | + |
| 15 | +from testcontainers.core.docker_client import DockerClient |
| 16 | + |
| 17 | + |
| 18 | +class Network(object): |
| 19 | + """ |
| 20 | + Network context manager to conveniently connect containers. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, name, docker_client_kw: Optional[dict] = None, **kwargs) -> None: |
| 24 | + self.name = name |
| 25 | + self._docker = DockerClient(**(docker_client_kw or {})) |
| 26 | + self._kwargs = kwargs |
| 27 | + |
| 28 | + def remove(self) -> None: |
| 29 | + self._network.remove() |
| 30 | + |
| 31 | + def __enter__(self) -> 'Network': |
| 32 | + self._network = self._docker.client.networks.create(self.name, **self._kwargs) |
| 33 | + self.id = self._network.id |
| 34 | + return self |
| 35 | + |
| 36 | + def __exit__(self, exc_type, exc_val, exc_tb) -> None: |
| 37 | + self.remove() |
| 38 | + |
| 39 | + def __del__(self) -> None: |
| 40 | + if self._network is not None: |
| 41 | + try: |
| 42 | + self.remove() |
| 43 | + except: # noqa: E722 |
| 44 | + pass |
0 commit comments