Skip to content

Commit

Permalink
stop container on test exit
Browse files Browse the repository at this point in the history
  • Loading branch information
jarlah committed Oct 13, 2023
1 parent 7257e92 commit 269a3cd
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/ex_unit.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ defmodule TestcontainersElixir.ExUnit do
alias DockerEngineAPI.Api
alias DockerEngineAPI.Model

import ExUnit.Callbacks

def container(options \\ []) do
docker_url = "http+unix://%2Fvar%2Frun%2Fdocker.sock/v1.43"
conn = Connection.new(base_url: docker_url)
Expand All @@ -15,11 +17,19 @@ defmodule TestcontainersElixir.ExUnit do
{:ok, container} <- simple_container(conn, image, port),
container_id = container."Id",
:ok <- reap_container(conn, container_id),
{:ok, _} <- Api.Container.container_start(conn, container_id) do
{:ok, _} <- Api.Container.container_start(conn, container_id),
:ok = on_exit(:stop_container, fn -> stop_container(conn, container_id) end) do
{:ok, container_id}
end
end

defp stop_container(conn, container_id) when is_binary(container_id) do
with {:ok, _} <- Api.Container.container_kill(conn, container_id),
{:ok, _} <- Api.Container.container_delete(conn, container_id) do
:ok
end
end

defp simple_container(conn, image, port) when is_binary(image) and is_number(port) do
Api.Container.container_create(conn, %Model.ContainerCreateRequest{
Image: image,
Expand Down

0 comments on commit 269a3cd

Please sign in to comment.