Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): Improving typing for common container usage scenarios #523

Merged
merged 2 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions core/testcontainers/core/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import TYPE_CHECKING, Optional

import docker.errors
from typing_extensions import Self

from testcontainers.core.config import (
RYUK_DISABLED,
Expand Down Expand Up @@ -53,29 +54,29 @@ def __init__(
self._name = None
self._kwargs = kwargs

def with_env(self, key: str, value: str) -> "DockerContainer":
def with_env(self, key: str, value: str) -> Self:
self.env[key] = value
return self

def with_bind_ports(self, container: int, host: Optional[int] = None) -> "DockerContainer":
def with_bind_ports(self, container: int, host: Optional[int] = None) -> Self:
self.ports[container] = host
return self

def with_exposed_ports(self, *ports: int) -> "DockerContainer":
def with_exposed_ports(self, *ports: int) -> Self:
for port in ports:
self.ports[port] = None
return self

def with_kwargs(self, **kwargs) -> "DockerContainer":
def with_kwargs(self, **kwargs) -> Self:
self._kwargs = kwargs
return self

def maybe_emulate_amd64(self) -> "DockerContainer":
def maybe_emulate_amd64(self) -> Self:
if is_arm():
return self.with_kwargs(platform="linux/amd64")
return self

def start(self):
def start(self) -> Self:
if not RYUK_DISABLED and self.image != RYUK_IMAGE:
logger.debug("Creating Ryuk container")
Reaper.get_instance()
Expand All @@ -95,10 +96,11 @@ def start(self):
return self

def stop(self, force=True, delete_volume=True) -> None:
self._container.remove(force=force, v=delete_volume)
if self._container:
self._container.remove(force=force, v=delete_volume)
self.get_docker_client().client.close()

def __enter__(self):
def __enter__(self) -> Self:
return self.start()

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
Expand Down Expand Up @@ -138,15 +140,15 @@ def get_exposed_port(self, port: int) -> str:
return port
return mapped_port

def with_command(self, command: str) -> "DockerContainer":
def with_command(self, command: str) -> Self:
self._command = command
return self

def with_name(self, name: str) -> "DockerContainer":
def with_name(self, name: str) -> Self:
self._name = name
return self

def with_volume_mapping(self, host: str, container: str, mode: str = "ro") -> "DockerContainer":
def with_volume_mapping(self, host: str, container: str, mode: str = "ro") -> Self:
mapping = {"bind": container, "mode": mode}
self.volumes[host] = mapping
return self
Expand Down
17 changes: 15 additions & 2 deletions core/testcontainers/core/docker_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
import urllib.parse
from os.path import exists
from pathlib import Path
from typing import Optional, Union
from typing import Callable, Optional, TypeVar, Union

import docker
from docker.models.containers import Container, ContainerCollection
from typing_extensions import ParamSpec

from testcontainers.core.labels import SESSION_ID, create_labels
from testcontainers.core.utils import default_gateway_ip, inside_container, setup_logger
Expand All @@ -30,6 +31,18 @@
TC_FILE = ".testcontainers.properties"
TC_GLOBAL = Path.home() / TC_FILE

_P = ParamSpec("_P")
_T = TypeVar("_T")


def _wrapped_container_collection(function: Callable[_P, _T]) -> Callable[_P, _T]:

@ft.wraps(ContainerCollection.run)
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
return function(*args, **kwargs)

return wrapper


class DockerClient:
"""
Expand All @@ -47,7 +60,7 @@ def __init__(self, **kwargs) -> None:
self.client.api.headers["x-tc-sid"] = SESSION_ID
self.client.api.headers["User-Agent"] = "tc-python/" + importlib.metadata.version("testcontainers")

@ft.wraps(ContainerCollection.run)
@_wrapped_container_collection
def run(
self,
image: str,
Expand Down