Skip to content

Commit 408f5c2

Browse files
chore(main): project fixes and updates (#807)
TL;DR this is a cleanups and alignments - Update pre-commit ruff version to latest + adaptations needed - Fix some issues with the pyproject.toml file schemas. 1. `tool.poetry.source` requires URL [see](python-poetry/poetry#3855) 2. `tool.ruff.lint` changed flake8-type-checking code [checkout](https://astral.sh/blog/ruff-v0.8.0) 3. `tool.mypy` doest not support `fast_module_lookup` in the TOML (Need to investigate more if we want to add it back) --------- Co-authored-by: David Ankin <[email protected]>
1 parent e8bf224 commit 408f5c2

File tree

18 files changed

+1014
-50
lines changed

18 files changed

+1014
-50
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ repos:
1010
- id: end-of-file-fixer
1111

1212
- repo: https://github.com/astral-sh/ruff-pre-commit
13-
rev: 'v0.3.5'
13+
rev: 'v0.11.5'
1414
hooks:
1515
- id: ruff
1616
# Explicitly setting config to prevent Ruff from using `pyproject.toml` in sub packages.
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
# flake8: noqa
1+
# flake8: noqa: F401
22
from testcontainers.compose.compose import (
3+
ComposeContainer,
34
ContainerIsNotRunning,
5+
DockerCompose,
46
NoSuchPortExposed,
57
PublishedPort,
6-
ComposeContainer,
7-
DockerCompose,
88
)

core/testcontainers/compose/compose.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ def get_config(
293293
config_cmd.append("--no-interpolate")
294294

295295
cmd_output = self._run_command(cmd=config_cmd).stdout
296-
return cast(dict[str, Any], loads(cmd_output))
296+
return cast(dict[str, Any], loads(cmd_output)) # noqa: TC006
297297

298298
def get_containers(self, include_all=False) -> list[ComposeContainer]:
299299
"""

core/testcontainers/core/config.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,11 @@ class ConnectionMode(Enum):
1717
@property
1818
def use_mapped_port(self) -> bool:
1919
"""
20-
Return true if we need to use mapped port for this connection
20+
Return True if mapped ports should be used for this connection mode.
2121
22-
This is true for everything but bridge mode.
22+
Mapped ports are used for all connection modes except 'bridge_ip'.
2323
"""
24-
if self == self.bridge_ip: # type: ignore[comparison-overlap]
25-
return False
26-
return True
24+
return self != ConnectionMode.bridge_ip
2725

2826

2927
def get_docker_socket() -> str:
@@ -137,15 +135,15 @@ def timeout(self) -> int:
137135
testcontainers_config = TestcontainersConfiguration()
138136

139137
__all__ = [
140-
# the public API of this module
141-
"testcontainers_config",
142-
# and all the legacy things that are deprecated:
138+
# Legacy things that are deprecated:
143139
"MAX_TRIES",
144-
"SLEEP_TIME",
145-
"TIMEOUT",
146-
"RYUK_IMAGE",
147-
"RYUK_PRIVILEGED",
148140
"RYUK_DISABLED",
149141
"RYUK_DOCKER_SOCKET",
142+
"RYUK_IMAGE",
143+
"RYUK_PRIVILEGED",
150144
"RYUK_RECONNECTION_TIMEOUT",
145+
"SLEEP_TIME",
146+
"TIMEOUT",
147+
# Public API of this module:
148+
"testcontainers_config",
151149
]

core/testcontainers/core/docker_client.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ def port(self, container_id: str, port: int) -> str:
162162
"""
163163
port_mappings = self.client.api.port(container_id, port)
164164
if not port_mappings:
165-
raise ConnectionError(f"Port mapping for container {container_id} and port {port} is " "not available")
165+
raise ConnectionError(f"Port mapping for container {container_id} and port {port} is not available")
166166
return cast(str, port_mappings[0]["HostPort"])
167167

168168
def get_container(self, container_id: str) -> dict[str, Any]:
@@ -233,7 +233,10 @@ def host(self) -> str:
233233
url = urllib.parse.urlparse(self.client.api.base_url)
234234
except ValueError:
235235
return "localhost"
236-
if "http" in url.scheme or "tcp" in url.scheme and url.hostname:
236+
237+
is_http_scheme = "http" in url.scheme
238+
is_tcp_scheme_with_hostname = "tcp" in url.scheme and url.hostname
239+
if is_http_scheme or is_tcp_scheme_with_hostname:
237240
# see https://github.com/testcontainers/testcontainers-python/issues/415
238241
hostname = url.hostname
239242
if not hostname or (hostname == "localnpipe" and utils.is_windows()):

core/testcontainers/core/waiting_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def wait_for_logs(
122122
if predicate_result:
123123
return duration
124124
if duration > timeout:
125-
raise TimeoutError(f"Container did not emit logs satisfying predicate in {timeout:.3f} " "seconds")
125+
raise TimeoutError(f"Container did not emit logs satisfying predicate in {timeout:.3f} seconds")
126126
if raise_on_exit:
127127
wrapped.reload()
128128
if wrapped.status not in _NOT_EXITED_STATUSES:

core/testcontainers/socat/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
# flake8: noqa
1+
# flake8: noqa: F401
22
from testcontainers.socat.socat import SocatContainer

core/tests/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def _check_for_image(image_short_id: str, cleaned: bool) -> None:
4848
client = DockerClient()
4949
images = client.client.images.list()
5050
found = any(image.short_id.endswith(image_short_id) for image in images)
51-
assert found is not cleaned, f'Image {image_short_id} was {"found" if cleaned else "not found"}'
51+
assert found is not cleaned, f"Image {image_short_id} was {'found' if cleaned else 'not found'}"
5252

5353
return _check_for_image
5454

core/tests/test_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def fake_cgroup(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
6666
def test_get_running_container_id_empty_or_missing(fake_cgroup: Path) -> None:
6767
# non existing does not fail but is only none
6868
assert utils.get_running_in_container_id() is None
69-
fake_cgroup.write_text("12:devices:/system.slice/sshd.service\n" "13:cpuset:\n")
69+
fake_cgroup.write_text("12:devices:/system.slice/sshd.service\n13:cpuset:\n")
7070
# missing docker does also not fail
7171
assert utils.get_running_in_container_id() is None
7272

modules/azurite/testcontainers/azurite/__init__.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def __init__(
6262
self.account_name = account_name or os.environ.get("AZURITE_ACCOUNT_NAME", "devstoreaccount1")
6363
self.account_key = account_key or os.environ.get(
6464
"AZURITE_ACCOUNT_KEY",
65-
"Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/" "K1SZFPTOtr/KBHBeksoGMGw==",
65+
"Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==",
6666
)
6767

6868
raise_for_deprecated_parameter(kwargs, "ports_to_expose", "container.with_exposed_ports")
@@ -76,28 +76,22 @@ def __init__(
7676
def get_connection_string(self) -> str:
7777
host_ip = self.get_container_host_ip()
7878
connection_string = (
79-
f"DefaultEndpointsProtocol=http;" f"AccountName={self.account_name};" f"AccountKey={self.account_key};"
79+
f"DefaultEndpointsProtocol=http;AccountName={self.account_name};AccountKey={self.account_key};"
8080
)
8181

8282
if self.blob_service_port in self.ports:
8383
connection_string += (
84-
f"BlobEndpoint=http://{host_ip}:"
85-
f"{self.get_exposed_port(self.blob_service_port)}"
86-
f"/{self.account_name};"
84+
f"BlobEndpoint=http://{host_ip}:{self.get_exposed_port(self.blob_service_port)}/{self.account_name};"
8785
)
8886

8987
if self.queue_service_port in self.ports:
9088
connection_string += (
91-
f"QueueEndpoint=http://{host_ip}:"
92-
f"{self.get_exposed_port(self.queue_service_port)}"
93-
f"/{self.account_name};"
89+
f"QueueEndpoint=http://{host_ip}:{self.get_exposed_port(self.queue_service_port)}/{self.account_name};"
9490
)
9591

9692
if self.table_service_port in self.ports:
9793
connection_string += (
98-
f"TableEndpoint=http://{host_ip}:"
99-
f"{self.get_exposed_port(self.table_service_port)}"
100-
f"/{self.account_name};"
94+
f"TableEndpoint=http://{host_ip}:{self.get_exposed_port(self.table_service_port)}/{self.account_name};"
10195
)
10296

10397
return connection_string

modules/generic/tests/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,6 @@ def _check_for_image(image_short_id: str, cleaned: bool) -> None:
1717
client = DockerClient()
1818
images = client.client.images.list()
1919
found = any(image.short_id.endswith(image_short_id) for image in images)
20-
assert found is not cleaned, f'Image {image_short_id} was {"found" if cleaned else "not found"}'
20+
assert found is not cleaned, f"Image {image_short_id} was {'found' if cleaned else 'not found'}"
2121

2222
return _check_for_image

modules/google/tests/test_google.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,9 @@ def test_datastore_container_isolation():
6868

6969
# Create a second container and try to fetch the entity to makesure its a different container
7070
with DatastoreContainer() as datastore2:
71-
assert (
72-
datastore.get_datastore_emulator_host() != datastore2.get_datastore_emulator_host()
73-
), "Datastore containers use the same port."
71+
assert datastore.get_datastore_emulator_host() != datastore2.get_datastore_emulator_host(), (
72+
"Datastore containers use the same port."
73+
)
7474
client2 = datastore2.get_datastore_client()
7575
fetched_entity2 = client2.get(key)
7676
assert fetched_entity2 is None, "Entity was found in the datastore."

modules/k3s/testcontainers/k3s/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,6 @@ def config_yaml(self) -> str:
6565
execution = self.get_wrapped_container().exec_run(["cat", "/etc/rancher/k3s/k3s.yaml"])
6666
config_yaml = execution.output.decode("utf-8").replace(
6767
f"https://127.0.0.1:{self.KUBE_SECURE_PORT}",
68-
f"https://{self.get_container_host_ip()}:" f"{self.get_exposed_port(self.KUBE_SECURE_PORT)}",
68+
f"https://{self.get_container_host_ip()}:{self.get_exposed_port(self.KUBE_SECURE_PORT)}",
6969
)
7070
return config_yaml

modules/mqtt/testcontainers/mqtt/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __init__(
5050
super().__init__(image, **kwargs)
5151
# self.password = password
5252
# reusable client context:
53-
self.client: Optional["Client"] = None
53+
self.client: Optional["Client"] = None # noqa: UP037
5454

5555
@wait_container_is_ready()
5656
def get_client(self) -> "Client":

modules/opensearch/testcontainers/opensearch/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from testcontainers.core.utils import raise_for_deprecated_parameter
99
from testcontainers.core.waiting_utils import wait_container_is_ready
1010

11+
MIN_REQUIRED_INITIAL_ADMIN_PASSWORD = [2, 12, 0]
12+
1113

1214
class OpenSearchContainer(DockerContainer):
1315
"""
@@ -65,7 +67,7 @@ def __init__(
6567

6668
def _supports_initial_admin_password(self, image: str) -> bool:
6769
with suppress(Exception):
68-
return [int(n) for n in image.split(":")[-1].split(".")] >= [int(n) for n in "2.12.0".split(".")]
70+
return [int(n) for n in image.split(":")[-1].split(".")] >= MIN_REQUIRED_INITIAL_ADMIN_PASSWORD
6971
return False
7072

7173
def get_config(self) -> dict:

modules/scylla/tests/test_scylla.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ def test_docker_run_scylla():
66
cluster = scylla.get_cluster()
77
with cluster.connect() as session:
88
session.execute(
9-
"CREATE KEYSPACE keyspace1 WITH replication = "
10-
"{'class': 'SimpleStrategy', 'replication_factor': '1'};"
9+
"CREATE KEYSPACE keyspace1 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};"
1110
)
1211
session.execute("CREATE TABLE keyspace1.table1 (key1 int, key2 int, PRIMARY KEY (key1));")
1312
session.execute("INSERT INTO keyspace1.table1 (key1,key2) values (1,2);")

0 commit comments

Comments
 (0)