Skip to content

Commit

Permalink
Stop container before removing it forcefully
Browse files Browse the repository at this point in the history
  • Loading branch information
rcmadhankumar committed Oct 7, 2024
1 parent 8dc2cc9 commit 4bd02ab
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pytest_container/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -1235,6 +1235,19 @@ def __exit__(
mounts = self.container_runtime.inspect_container(
self._container_id
).mounts

_logger.debug(
"Stopping container %s via %s",
self._container_id,
self.container_runtime.runner_binary,
)
check_output(
[
self.container_runtime.runner_binary,
"stop",
self._container_id,
]
)
_logger.debug(
"Removing container %s via %s",
self._container_id,
Expand Down
10 changes: 10 additions & 0 deletions tests/files/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/sh

mkdir -p /var/volume
touch /var/volume/cleanup_confirmed

trap "echo '1' > /var/volume/cleanup_confirmed" SIGTERM

while true; do
sleep 5
done
28 changes: 28 additions & 0 deletions tests/test_container_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pytest_container import DerivedContainer
from pytest_container import get_extra_build_args
from pytest_container.build import MultiStageBuild
from pytest_container.container import BindMount
from pytest_container.container import ContainerData
from pytest_container.container import ContainerLauncher
from pytest_container.container import EntrypointSelection
Expand Down Expand Up @@ -323,3 +324,30 @@ def test_multistage_build_target(
@pytest.mark.parametrize("container", [LEAP_THAT_ECHOES_STUFF], indirect=True)
def test_container_logs(container: ContainerData) -> None:
assert "foobar" in container.read_container_logs()


def test_container_stops_on_exit(
container_runtime: OciRuntimeBase,
pytestconfig: Config,
tmp_path: Path,
):
_CONTAINER_THAT_TRAPS_SIGTERM = DerivedContainer(
base=BUSYBOX_WITH_ENTRYPOINT,
containerfile="""COPY tests/files/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
CMD ["/usr/local/bin/entrypoint.sh"]
""",
volume_mounts=[
BindMount(host_path=tmp_path, container_path="/var/volume")
],
)
with ContainerLauncher(
_CONTAINER_THAT_TRAPS_SIGTERM,
container_runtime,
pytestconfig.rootpath,
) as launcher:
launcher.launch_container()
connection = launcher.container_data.connection
assert connection.file("/var/volume/cleanup_confirmed").exists

assert (tmp_path / "cleanup_confirmed").read_text().strip() == "1"

0 comments on commit 4bd02ab

Please sign in to comment.