Skip to content

Commit 81adc99

Browse files
authored
Merge branch 'main' into main
2 parents 8dd629c + a072f3f commit 81adc99

22 files changed

+2038
-370
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
{
2-
".": "4.11.0"
2+
".": "4.12.0"
33
}

CHANGELOG.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,27 @@
11
# Changelog
22

3+
## [4.12.0](https://github.com/testcontainers/testcontainers-python/compare/testcontainers-v4.11.0...testcontainers-v4.12.0) (2025-07-21)
4+
5+
6+
### Features
7+
8+
* **main:** New Testcontainers Python Docs Site ([#822](https://github.com/testcontainers/testcontainers-python/issues/822)) ([a6bdf0e](https://github.com/testcontainers/testcontainers-python/commit/a6bdf0ef84643074fbc7edf3a75936ce3f1d0880))
9+
* make config monkeypatchable, fix config related startup issues ([#833](https://github.com/testcontainers/testcontainers-python/issues/833)) ([ff6a32d](https://github.com/testcontainers/testcontainers-python/commit/ff6a32db803046db8d89ba5a7157bf573d9f25c2))
10+
* **modules:** add OpenFGA module ([#762](https://github.com/testcontainers/testcontainers-python/issues/762)) ([0b7b482](https://github.com/testcontainers/testcontainers-python/commit/0b7b482f9ec807e87fd43d1372226fa43eb4ed7c))
11+
* set multiple variables via keyword args ([#804](https://github.com/testcontainers/testcontainers-python/issues/804)) ([1532df5](https://github.com/testcontainers/testcontainers-python/commit/1532df5e9094d15b9f3e9233e7f5843d8bc24386))
12+
13+
14+
### Bug Fixes
15+
16+
* **core:** mypy ([#810](https://github.com/testcontainers/testcontainers-python/issues/810)) ([b816762](https://github.com/testcontainers/testcontainers-python/commit/b816762b9a548033b065c3f46267c289a560f6ed))
17+
* Enable mypy in the CI ([#842](https://github.com/testcontainers/testcontainers-python/issues/842)) ([ef65bd1](https://github.com/testcontainers/testcontainers-python/commit/ef65bd113b564bce614aaf6df13bbf5339b9bc58))
18+
* just use the getLogger API and do not override logger settings ([#836](https://github.com/testcontainers/testcontainers-python/issues/836)) ([f467c84](https://github.com/testcontainers/testcontainers-python/commit/f467c842b851613b9a087bd5f9a08d8c39577cb8))
19+
20+
21+
### Documentation
22+
23+
* missing compose html from old docs ([#776](https://github.com/testcontainers/testcontainers-python/issues/776)) ([d749fc6](https://github.com/testcontainers/testcontainers-python/commit/d749fc69b32715742d834c003ee6893e2077753a))
24+
325
## [4.11.0](https://github.com/testcontainers/testcontainers-python/compare/testcontainers-v4.10.0...testcontainers-v4.11.0) (2025-06-15)
426

527

conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@
161161

162162
intersphinx_mapping = {
163163
"python": ("https://docs.python.org/3", None),
164-
"selenium": ("https://seleniumhq.github.io/selenium/docs/api/py/", None),
164+
"selenium": ("https://www.selenium.dev/selenium/docs/api/py/", None),
165165
"typing_extensions": ("https://typing-extensions.readthedocs.io/en/latest/", None),
166166
}
167167

core/README.rst

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@ Testcontainers Core
66
.. automodule:: testcontainers.core.container
77
:members:
88
:undoc-members:
9-
9+
1010
.. autoclass:: testcontainers.core.network.Network
1111
:members:
1212

1313
.. autoclass:: testcontainers.core.image.DockerImage
1414

1515
.. autoclass:: testcontainers.core.generic.DbContainer
1616

17+
.. autoclass:: testcontainers.core.wait_strategies.WaitStrategy
18+
1719
.. raw:: html
1820

1921
<hr>

core/testcontainers/compose/compose.py

Lines changed: 113 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
from dataclasses import asdict, dataclass, field, fields, is_dataclass
22
from functools import cached_property
33
from json import loads
4-
from logging import warning
4+
from logging import getLogger, warning
55
from os import PathLike
66
from platform import system
77
from re import split
8-
from subprocess import CompletedProcess
8+
from subprocess import CalledProcessError, CompletedProcess
99
from subprocess import run as subprocess_run
1010
from types import TracebackType
1111
from typing import Any, Callable, Literal, Optional, TypeVar, Union, cast
12-
from urllib.error import HTTPError, URLError
13-
from urllib.request import urlopen
1412

1513
from testcontainers.core.exceptions import ContainerIsNotRunning, NoSuchPortExposed
16-
from testcontainers.core.waiting_utils import wait_container_is_ready
14+
from testcontainers.core.waiting_utils import WaitStrategy
1715

1816
_IPT = TypeVar("_IPT")
1917
_WARNINGS = {"DOCKER_COMPOSE_GET_CONFIG": "get_config is experimental, see testcontainers/testcontainers-python#669"}
2018

19+
logger = getLogger(__name__)
20+
2121

2222
def _ignore_properties(cls: type[_IPT], dict_: Any) -> _IPT:
2323
"""omits extra fields like @JsonIgnoreProperties(ignoreUnknown = true)
@@ -80,6 +80,7 @@ class ComposeContainer:
8080
Health: Optional[str] = None
8181
ExitCode: Optional[int] = None
8282
Publishers: list[PublishedPortModel] = field(default_factory=list)
83+
_docker_compose: Optional["DockerCompose"] = field(default=None, init=False, repr=False)
8384

8485
def __post_init__(self) -> None:
8586
if self.Publishers:
@@ -116,6 +117,41 @@ def _matches_protocol(prefer_ip_version: str, r: PublishedPortModel) -> bool:
116117
r_url = r.URL
117118
return (r_url is not None and ":" in r_url) is (prefer_ip_version == "IPv6")
118119

120+
# WaitStrategy compatibility methods
121+
def get_container_host_ip(self) -> str:
122+
"""Get the host IP for the container."""
123+
# Simplified implementation - wait strategies don't use this yet
124+
return "127.0.0.1"
125+
126+
def get_exposed_port(self, port: int) -> int:
127+
"""Get the exposed port mapping for the given internal port."""
128+
# Simplified implementation - wait strategies don't use this yet
129+
return port
130+
131+
def get_logs(self) -> tuple[bytes, bytes]:
132+
"""Get container logs."""
133+
if not self._docker_compose:
134+
raise RuntimeError("DockerCompose reference not set on ComposeContainer")
135+
if not self.Service:
136+
raise RuntimeError("Service name not set on ComposeContainer")
137+
stdout, stderr = self._docker_compose.get_logs(self.Service)
138+
return stdout.encode(), stderr.encode()
139+
140+
def get_wrapped_container(self) -> "ComposeContainer":
141+
"""Get the underlying container object for compatibility."""
142+
return self
143+
144+
def reload(self) -> None:
145+
"""Reload container information for compatibility with wait strategies."""
146+
# ComposeContainer doesn't need explicit reloading as it's fetched fresh
147+
# each time through get_container(), but we need this method for compatibility
148+
pass
149+
150+
@property
151+
def status(self) -> str:
152+
"""Get container status for compatibility with wait strategies."""
153+
return self.State or "unknown"
154+
119155

120156
@dataclass
121157
class DockerCompose:
@@ -178,6 +214,7 @@ class DockerCompose:
178214
services: Optional[list[str]] = None
179215
docker_command_path: Optional[str] = None
180216
profiles: Optional[list[str]] = None
217+
_wait_strategies: Optional[dict[str, Any]] = field(default=None, init=False, repr=False)
181218

182219
def __post_init__(self) -> None:
183220
if isinstance(self.compose_file_name, str):
@@ -216,6 +253,15 @@ def compose_command_property(self) -> list[str]:
216253
docker_compose_cmd += ["--env-file", env_file]
217254
return docker_compose_cmd
218255

256+
def waiting_for(self, strategies: dict[str, WaitStrategy]) -> "DockerCompose":
257+
"""
258+
Set wait strategies for specific services.
259+
Args:
260+
strategies: Dictionary mapping service names to wait strategies
261+
"""
262+
self._wait_strategies = strategies
263+
return self
264+
219265
def start(self) -> None:
220266
"""
221267
Starts the docker compose environment.
@@ -244,6 +290,11 @@ def start(self) -> None:
244290

245291
self._run_command(cmd=up_cmd)
246292

293+
if self._wait_strategies:
294+
for service, strategy in self._wait_strategies.items():
295+
container = self.get_container(service_name=service)
296+
strategy.wait_until_ready(container)
297+
247298
def stop(self, down: bool = True) -> None:
248299
"""
249300
Stops the docker compose environment.
@@ -320,7 +371,7 @@ def get_containers(self, include_all: bool = False) -> list[ComposeContainer]:
320371
result = self._run_command(cmd=cmd)
321372
stdout = split(r"\r?\n", result.stdout.decode("utf-8"))
322373

323-
containers = []
374+
containers: list[ComposeContainer] = []
324375
# one line per service in docker 25, single array for docker 24.0.2
325376
for line in stdout:
326377
if not line:
@@ -331,6 +382,10 @@ def get_containers(self, include_all: bool = False) -> list[ComposeContainer]:
331382
else:
332383
containers.append(_ignore_properties(ComposeContainer, data))
333384

385+
# Set the docker_compose reference on each container
386+
for container in containers:
387+
container._docker_compose = self
388+
334389
return containers
335390

336391
def get_container(
@@ -355,6 +410,7 @@ def get_container(
355410
if not matching_containers:
356411
raise ContainerIsNotRunning(f"{service_name} is not running in the compose context")
357412

413+
matching_containers[0]._docker_compose = self
358414
return matching_containers[0]
359415

360416
def exec_in_container(
@@ -391,12 +447,18 @@ def _run_command(
391447
context: Optional[str] = None,
392448
) -> CompletedProcess[bytes]:
393449
context = context or str(self.context)
394-
return subprocess_run(
395-
cmd,
396-
capture_output=True,
397-
check=True,
398-
cwd=context,
399-
)
450+
try:
451+
return subprocess_run(
452+
cmd,
453+
capture_output=True,
454+
check=True,
455+
cwd=context,
456+
)
457+
except CalledProcessError as e:
458+
logger.error(f"Command '{e.cmd}' failed with exit code {e.returncode}")
459+
logger.error(f"STDOUT:\n{e.stdout.decode(errors='ignore')}")
460+
logger.error(f"STDERR:\n{e.stderr.decode(errors='ignore')}")
461+
raise e from e
400462

401463
def get_service_port(
402464
self,
@@ -455,16 +517,54 @@ def get_service_host_and_port(
455517
publisher = self.get_container(service_name).get_publisher(by_port=port).normalize()
456518
return publisher.URL, publisher.PublishedPort
457519

458-
@wait_container_is_ready(HTTPError, URLError)
459520
def wait_for(self, url: str) -> "DockerCompose":
460521
"""
461522
Waits for a response from a given URL. This is typically used to block until a service in
462523
the environment has started and is responding. Note that it does not assert any sort of
463524
return code, only check that the connection was successful.
464525
526+
This is a convenience method that internally uses HttpWaitStrategy. For more complex
527+
wait scenarios, consider using the structured wait strategies with `waiting_for()`.
528+
465529
Args:
466530
url: URL from one of the services in the environment to use to wait on.
531+
532+
Example:
533+
# Simple URL wait (legacy style)
534+
compose.wait_for("http://localhost:8080") \
535+
\
536+
# For more complex scenarios, use structured wait strategies:
537+
from testcontainers.core.waiting_utils import HttpWaitStrategy, LogMessageWaitStrategy \
538+
\
539+
compose.waiting_for({ \
540+
"web": HttpWaitStrategy(8080).for_status_code(200), \
541+
"db": LogMessageWaitStrategy("database system is ready to accept connections") \
542+
})
467543
"""
544+
import time
545+
from urllib.error import HTTPError, URLError
546+
from urllib.request import Request, urlopen
547+
548+
# For simple URL waiting when we have multiple containers,
549+
# we'll do a direct HTTP check instead of using the container-based strategy
550+
start_time = time.time()
551+
timeout = 120 # Default timeout
552+
553+
while True:
554+
if time.time() - start_time > timeout:
555+
raise TimeoutError(f"URL {url} not ready within {timeout} seconds")
556+
557+
try:
558+
request = Request(url, method="GET")
559+
with urlopen(request, timeout=1) as response:
560+
if 200 <= response.status < 400:
561+
return self
562+
except (URLError, HTTPError, ConnectionResetError, ConnectionRefusedError, BrokenPipeError, OSError):
563+
# Any connection error means we should keep waiting
564+
pass
565+
566+
time.sleep(1)
567+
468568
with urlopen(url) as response:
469569
response.read()
470570
return self

core/testcontainers/core/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def read_tc_properties() -> dict[str, str]:
9797
@dataclass
9898
class TestcontainersConfiguration:
9999
max_tries: int = int(environ.get("TC_MAX_TRIES", "120"))
100-
sleep_time: int = int(environ.get("TC_POOLING_INTERVAL", "1"))
100+
sleep_time: float = float(environ.get("TC_POOLING_INTERVAL", "1"))
101101
ryuk_image: str = environ.get("RYUK_CONTAINER_IMAGE", "testcontainers/ryuk:0.8.1")
102102
ryuk_privileged: bool = get_bool_env("TESTCONTAINERS_RYUK_PRIVILEGED")
103103
ryuk_disabled: bool = get_bool_env("TESTCONTAINERS_RYUK_DISABLED")
@@ -130,7 +130,7 @@ def tc_properties_get_tc_host(self) -> Union[str, None]:
130130
return self.tc_properties.get("tc.host")
131131

132132
@property
133-
def timeout(self) -> int:
133+
def timeout(self) -> float:
134134
return self.max_tries * self.sleep_time
135135

136136
@property

core/testcontainers/core/container.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
from testcontainers.core.labels import LABEL_SESSION_ID, SESSION_ID
1919
from testcontainers.core.network import Network
2020
from testcontainers.core.utils import is_arm, setup_logger
21-
from testcontainers.core.waiting_utils import wait_container_is_ready, wait_for_logs
21+
from testcontainers.core.wait_strategies import LogMessageWaitStrategy
22+
from testcontainers.core.waiting_utils import WaitStrategy, wait_container_is_ready
2223

2324
if TYPE_CHECKING:
2425
from docker.models.containers import Container
@@ -69,6 +70,7 @@ def __init__(
6970
volumes: Optional[list[tuple[str, str, str]]] = None,
7071
network: Optional[Network] = None,
7172
network_aliases: Optional[list[str]] = None,
73+
_wait_strategy: Optional[WaitStrategy] = None,
7274
**kwargs: Any,
7375
) -> None:
7476
self.env = env or {}
@@ -96,6 +98,7 @@ def __init__(
9698
self.with_network_aliases(*network_aliases)
9799

98100
self._kwargs = kwargs
101+
self._wait_strategy: Optional[WaitStrategy] = _wait_strategy
99102

100103
def with_env(self, key: str, value: str) -> Self:
101104
self.env[key] = value
@@ -165,6 +168,11 @@ def maybe_emulate_amd64(self) -> Self:
165168
return self.with_kwargs(platform="linux/amd64")
166169
return self
167170

171+
def waiting_for(self, strategy: WaitStrategy) -> "DockerContainer":
172+
"""Set a wait strategy to be used after container start."""
173+
self._wait_strategy = strategy
174+
return self
175+
168176
def start(self) -> Self:
169177
if not c.ryuk_disabled and self.image != c.ryuk_image:
170178
logger.debug("Creating Ryuk container")
@@ -195,6 +203,9 @@ def start(self) -> Self:
195203
**{**network_kwargs, **self._kwargs},
196204
)
197205

206+
if self._wait_strategy is not None:
207+
self._wait_strategy.wait_until_ready(self)
208+
198209
logger.info("Container started: %s", self._container.short_id)
199210
return self
200211

@@ -264,6 +275,18 @@ def get_logs(self) -> tuple[bytes, bytes]:
264275
raise ContainerStartException("Container should be started before getting logs")
265276
return self._container.logs(stderr=False), self._container.logs(stdout=False)
266277

278+
def reload(self) -> None:
279+
"""Reload container information for compatibility with wait strategies."""
280+
if self._container:
281+
self._container.reload()
282+
283+
@property
284+
def status(self) -> str:
285+
"""Get container status for compatibility with wait strategies."""
286+
if not self._container:
287+
return "not_started"
288+
return cast("str", self._container.status)
289+
267290
def exec(self, command: Union[str, list[str]]) -> ExecResult:
268291
if not self._container:
269292
raise ContainerStartException("Container should be started before executing a command")
@@ -319,7 +342,7 @@ def _create_instance(cls) -> "Reaper":
319342
)
320343
rc = Reaper._container
321344
assert rc is not None
322-
wait_for_logs(rc, r".* Started!", timeout=20, raise_on_exit=True)
345+
rc.waiting_for(LogMessageWaitStrategy(r".* Started!").with_startup_timeout(20))
323346

324347
container_host = rc.get_container_host_ip()
325348
container_port = int(rc.get_exposed_port(8080))

core/testcontainers/core/generic.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def _create_connection_url(
6262
if self._container is None:
6363
raise ContainerStartException("container has not been started")
6464
host = host or self.get_container_host_ip()
65+
assert port is not None
6566
port = self.get_exposed_port(port)
6667
quoted_password = quote(password, safe=" +")
6768
url = f"{dialect}://{username}:{quoted_password}@{host}:{port}"

0 commit comments

Comments
 (0)