Skip to content

Commit b40dfe2

Browse files
committed
Remove LOCALHOST object from test infra
1 parent 9fc118a commit b40dfe2

File tree

8 files changed

+82
-84
lines changed

8 files changed

+82
-84
lines changed

pytest_container/container.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import operator
1212
import os
1313
import socket
14-
import subprocess
1514
import sys
1615
import tempfile
1716
import time
@@ -1035,6 +1034,7 @@ def check_output(self, cmd: str, strip: bool = True) -> str:
10351034
],
10361035
)[1]
10371036

1037+
10381038
@dataclass
10391039
class ContainerLauncher:
10401040
"""Helper context manager to setup, start and teardown a container including

pytest_container/runtime.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
from typing import Optional
2222
from typing import Union
2323

24-
2524
from _pytest.mark.structures import ParameterSet
2625
from pytest import param
2726

test-requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ pytest-xdist
33
coverage
44
pytest-rerunfailures
55
typeguard
6+
ifaddr
67
.

tests/test_container_build.py

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
from pytest_container.container import ContainerData
1414
from pytest_container.container import ContainerLauncher
1515
from pytest_container.container import EntrypointSelection
16+
from pytest_container.helpers import run_command
1617
from pytest_container.inspect import PortForwarding
17-
from pytest_container.runtime import LOCALHOST
1818
from pytest_container.runtime import OciRuntimeBase
1919

2020
from .images import LEAP
@@ -285,9 +285,9 @@ def test_multistage_build_target(
285285
extra_build_args=get_extra_build_args(pytestconfig),
286286
)
287287
assert (
288-
LOCALHOST.check_output(
289-
f"{container_runtime.runner_binary} run --rm {first_target}",
290-
).strip()
288+
run_command(
289+
[container_runtime.runner_binary, "run", "--rm", first_target]
290+
)[1].strip()
291291
== "foobar"
292292
)
293293

@@ -301,9 +301,15 @@ def test_multistage_build_target(
301301

302302
assert first_target != second_target
303303
assert (
304-
LOCALHOST.check_output(
305-
f"{container_runtime.runner_binary} run --rm {second_target} /bin/test.sh",
306-
).strip()
304+
run_command(
305+
[
306+
container_runtime.runner_binary,
307+
"run",
308+
"--rm",
309+
second_target,
310+
"/bin/test.sh",
311+
]
312+
)[1].strip()
307313
== "foobar"
308314
)
309315

@@ -313,10 +319,17 @@ def test_multistage_build_target(
313319
):
314320
assert (
315321
distro
316-
in LOCALHOST.check_output(
317-
f"{container_runtime.runner_binary} run --rm --entrypoint= {target} "
318-
"cat /etc/os-release",
319-
).strip()
322+
in run_command(
323+
[
324+
container_runtime.runner_binary,
325+
"run",
326+
"--rm",
327+
"--entrypoint=",
328+
target,
329+
"cat",
330+
"/etc/os-release",
331+
]
332+
)[1].strip()
320333
)
321334

322335

tests/test_launcher.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from pytest_container.container import ContainerVolume
2020
from pytest_container.container import DerivedContainer
2121
from pytest_container.container import EntrypointSelection
22-
from pytest_container.runtime import LOCALHOST
22+
from pytest_container.helpers import run_command
2323
from pytest_container.runtime import OciRuntimeBase
2424

2525
from .images import CMDLINE_APP_CONTAINER
@@ -101,9 +101,17 @@ def test_launcher_creates_and_cleanes_up_volumes(
101101
assert vol.host_path and os.path.exists(vol.host_path)
102102
elif isinstance(vol, ContainerVolume):
103103
assert vol.volume_id
104-
assert LOCALHOST.run_expect(
105-
[0],
106-
f"{container_runtime.runner_binary} volume inspect {vol.volume_id}",
104+
assert (
105+
run_command(
106+
[
107+
container_runtime.runner_binary,
108+
"volume",
109+
"inspect",
110+
vol.volume_id,
111+
],
112+
ignore_errors=False,
113+
)[0]
114+
== 0
107115
)
108116
else:
109117
assert False, f"invalid volume type {type(vol)}"

tests/test_port_forwarding.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,22 @@
22
:py:attr:`~pytest_container.container.ContainerBase.forwarded_ports`."""
33

44
# pylint: disable=missing-function-docstring
5-
import itertools
5+
import re
66
import socket
77
from typing import List
88

9+
import ifaddr
910
import pytest
1011

1112
from pytest_container.container import ContainerData
1213
from pytest_container.container import ContainerLauncher
1314
from pytest_container.container import DerivedContainer
1415
from pytest_container.container import PortForwarding
1516
from pytest_container.container import lock_host_port_search
17+
from pytest_container.helpers import run_command
1618
from pytest_container.inspect import NetworkProtocol
1719
from pytest_container.pod import Pod
1820
from pytest_container.pod import PodLauncher
19-
from pytest_container.runtime import LOCALHOST
2021
from pytest_container.runtime import OciRuntimeBase
2122
from pytest_container.runtime import Version
2223

@@ -65,8 +66,12 @@ def _create_nginx_container(number: int) -> DerivedContainer:
6566

6667
CONTAINER_IMAGES = [WEB_SERVER]
6768

69+
curl_version_string = run_command(["curl", "--version"])[1]
70+
pattern = r"curl\s+(\d+(?:\.\d+)+)"
71+
match = re.search(pattern, curl_version_string)
72+
assert match is not None, "Curl version not found"
73+
_curl_version = Version.parse(match.group(1))
6874

69-
_curl_version = Version.parse(LOCALHOST.package("curl").version)
7075

7176
#: curl cli with additional retries as a single curl sometimes fails with docker
7277
#: with ``curl: (56) Recv failure: Connection reset by peer`` for reasons…
@@ -175,18 +180,18 @@ def test_multiple_open_ports(container: ContainerData, number: int, host):
175180
)
176181

177182

178-
_INTERFACES = [
179-
name
180-
for name in LOCALHOST.interface.names()
181-
if name[:2] in ("en", "et", "wl")
182-
]
183-
_ADDRESSES = [
184-
addr
185-
for addr in itertools.chain.from_iterable(
186-
LOCALHOST.interface(interface).addresses for interface in _INTERFACES
187-
)
188-
if not addr.startswith("169.254.") and not addr.startswith("fe80:")
189-
]
183+
def _find_all_usable_ips():
184+
for adapter in ifaddr.get_adapters():
185+
if not adapter.name.startswith(("en", "et", "wl")):
186+
continue
187+
for addr in adapter.ips:
188+
if addr.is_IPv4 and not addr.ip.startswith("169.254."):
189+
yield str(addr.ip)
190+
elif addr.is_IPv6 and not addr.ip[0].startswith("fe80:"):
191+
yield addr.ip[0]
192+
193+
194+
_ADDRESSES = list(_find_all_usable_ips())
190195

191196

192197
@pytest.mark.parametrize(

tests/test_runtime.py

Lines changed: 13 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# pylint: disable=missing-function-docstring,missing-module-docstring
22
import os
3+
import shutil
34
from pathlib import Path
45
from typing import Callable
56
from typing import Type
@@ -8,7 +9,7 @@
89

910
import pytest
1011

11-
from pytest_container.runtime import LOCALHOST
12+
from pytest_container import helpers
1213
from pytest_container.runtime import DockerRuntime
1314
from pytest_container.runtime import OciRuntimeBase
1415
from pytest_container.runtime import PodmanRuntime
@@ -27,45 +28,6 @@ def container_runtime_envvar(request):
2728
yield
2829

2930

30-
# pylint: disable-next=unused-argument
31-
def _mock_run_success(*args, **kwargs):
32-
class Succeeded:
33-
"""Class that mocks the returned object of `testinfra`'s `run`."""
34-
35-
@property
36-
def succeeded(self) -> bool:
37-
return True
38-
39-
@property
40-
def rc(self) -> int:
41-
return 0
42-
43-
return Succeeded()
44-
45-
46-
def generate_mock_fail(*, rc: int = 1, stderr: str = "failure!!"):
47-
# pylint: disable-next=unused-argument
48-
def mock_run_fail(cmd: str):
49-
class Failure:
50-
"""Class that mocks the returned object of `testinfra`'s `run`."""
51-
52-
@property
53-
def succeeded(self) -> bool:
54-
return False
55-
56-
@property
57-
def rc(self) -> int:
58-
return rc
59-
60-
@property
61-
def stderr(self) -> str:
62-
return stderr
63-
64-
return Failure()
65-
66-
return mock_run_fail
67-
68-
6931
def _create_mock_exists(
7032
podman_should_exist: bool, docker_should_exist: bool
7133
) -> Callable[[str], bool]:
@@ -96,8 +58,7 @@ def test_runtime_selection(
9658
runtime: OciRuntimeBase,
9759
monkeypatch: pytest.MonkeyPatch,
9860
):
99-
monkeypatch.setattr(LOCALHOST, "run", _mock_run_success)
100-
monkeypatch.setattr(LOCALHOST, "exists", _create_mock_exists(True, True))
61+
monkeypatch.setattr(shutil, "which", _create_mock_exists(True, True))
10162

10263
assert get_selected_runtime() == runtime
10364

@@ -107,7 +68,7 @@ def test_value_err_when_docker_and_podman_missing(
10768
runtime: str, monkeypatch: pytest.MonkeyPatch
10869
) -> None:
10970
monkeypatch.setenv("CONTAINER_RUNTIME", runtime)
110-
monkeypatch.setattr(LOCALHOST, "exists", _create_mock_exists(False, False))
71+
monkeypatch.setattr(shutil, "which", _create_mock_exists(False, False))
11172
with pytest.raises(ValueError) as val_err_ctx:
11273
get_selected_runtime()
11374

@@ -125,7 +86,11 @@ def test_runtime_construction_fails_if_ps_fails(
12586
monkeypatch: pytest.MonkeyPatch,
12687
) -> None:
12788
stderr = "container runtime failed"
128-
monkeypatch.setattr(LOCALHOST, "run", generate_mock_fail(stderr=stderr))
89+
monkeypatch.setattr(
90+
helpers,
91+
"run_command",
92+
lambda _: (1, "", stderr),
93+
)
12994
with pytest.raises(RuntimeError) as rt_err_ctx:
13095
cls()
13196

@@ -145,7 +110,9 @@ def test_buildah_version_parsing(
145110
monkeypatch: pytest.MonkeyPatch,
146111
) -> None:
147112
monkeypatch.setattr(
148-
LOCALHOST, "check_output", lambda _: f"buildah version {version_str}"
113+
helpers,
114+
"run_command",
115+
lambda _: (0, f"buildah version {version_str}", ""),
149116
)
150117

151118
assert _get_buildah_version() == expected_version
@@ -154,7 +121,7 @@ def test_buildah_version_parsing(
154121
def test_get_buildah_version_fails_on_unexpected_stdout(
155122
monkeypatch: pytest.MonkeyPatch,
156123
) -> None:
157-
monkeypatch.setattr(LOCALHOST, "check_output", lambda _: "foobar")
124+
monkeypatch.setattr(helpers, "run_command", lambda _: (0, "foobar", ""))
158125
with pytest.raises(RuntimeError) as rt_err_ctx:
159126
_get_buildah_version()
160127

tests/test_volumes.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import os
33
from os.path import abspath
44
from os.path import join
5+
from pathlib import Path
56
from typing import List
67

78
import pytest
@@ -14,7 +15,6 @@
1415
from pytest_container.container import DerivedContainer
1516
from pytest_container.container import VolumeFlag
1617
from pytest_container.container import get_volume_creator
17-
from pytest_container.runtime import LOCALHOST
1818
from pytest_container.runtime import OciRuntimeBase
1919

2020
from .images import LEAP_URL
@@ -118,8 +118,8 @@ def test_container_host_volumes(container_per_test: ContainerData):
118118
for vol in container_per_test.container.volume_mounts:
119119
assert isinstance(vol, BindMount)
120120
assert vol.host_path
121-
dir_on_host = LOCALHOST.file(vol.host_path)
122-
assert dir_on_host.exists and dir_on_host.is_directory
121+
dir_on_host = Path(vol.host_path)
122+
assert dir_on_host.is_dir()
123123

124124
dir_in_container = container_per_test.connection.file(
125125
vol.container_path
@@ -142,8 +142,8 @@ def test_container_volume_host_writing(container_per_test: ContainerData):
142142
assert isinstance(vol, BindMount)
143143
assert vol.host_path
144144

145-
host_dir = LOCALHOST.file(vol.host_path)
146-
assert not host_dir.listdir()
145+
host_dir = Path(vol.host_path)
146+
assert not list(host_dir.iterdir())
147147

148148
container_dir = container_per_test.connection.file(vol.container_path)
149149
assert not container_dir.listdir()
@@ -265,9 +265,14 @@ def test_concurrent_container_volumes(container_per_test: ContainerData):
265265
def test_bind_mount_cwd(container: ContainerData):
266266
vol = container.container.volume_mounts[0]
267267
assert isinstance(vol, BindMount)
268+
assert vol.host_path is not None
269+
268270
assert container.connection.file("/src/").exists and sorted(
269271
container.connection.file("/src/").listdir()
270-
) == sorted(LOCALHOST.file(vol.host_path).listdir())
272+
) == sorted(
273+
str(p.relative_to(vol.host_path))
274+
for p in Path(vol.host_path).iterdir()
275+
)
271276

272277

273278
def test_bind_mount_fails_when_host_path_not_present() -> None:

0 commit comments

Comments
 (0)