Skip to content

Commit

Permalink
check fort port ready
Browse files Browse the repository at this point in the history
  • Loading branch information
jarlah committed Oct 13, 2023
1 parent 9a1efd1 commit add935e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/port_checker.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: Apache-2.0
defmodule TestcontainersElixir.PortChecker do
def wait_for_port(ip, port, timeout \\ 1000) do
wait_for_port(ip, port, timeout, :os.system_time(:millisecond))
end

defp wait_for_port(ip, port, timeout, start_time) do
if timeout + start_time < :os.system_time(:millisecond) do
{:error, :timeout}
else
if port_open?(ip, port) do
{:ok, :port_is_open}
else
# Sleep for 500 ms, then retry
:timer.sleep(500)
wait_for_port(ip, port, timeout, start_time)
end
end
end

defp port_open?(ip, port, timeout \\ 1000) do
IO.inspect("checking port #{port}")

case :gen_tcp.connect(~c"#{ip}", port, [:binary, active: false], timeout) do
{:ok, socket} ->
:gen_tcp.close(socket)
true

{:error, _reason} ->
false
end
end
end
1 change: 1 addition & 0 deletions lib/reaper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ defmodule TestcontainersElixir.Reaper do
@impl true
def init(connection) do
Process.flag(:trap_exit, true)

with {:ok, _image_create_response} <-
Api.Image.image_create(connection, fromImage: @ryuk_image),
{:ok, %Model.ContainerCreateResponse{Id: container_id}} <-
Expand Down
2 changes: 2 additions & 0 deletions test/simple_test.exs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
defmodule SimpleTest do
use ExUnit.Case
import TestcontainersElixir.ExUnit
alias TestcontainersElixir.PortChecker
alias TestcontainersElixir.Container

test "creates and reaps container" do

Check failure on line 7 in test/simple_test.exs

View workflow job for this annotation

GitHub Actions / Build and test

test creates and reaps container (SimpleTest)
{:ok, container} = container(image: "nginx:latest", port: 80)

port = Container.mapped_port(container, 80)
PortChecker.wait_for_port("localhost", port, 5000)

{:ok, 200, _headers, body_ref} = :hackney.get("http://localhost:#{port}")
{:ok, body} = :hackney.body(body_ref)
Expand Down

0 comments on commit add935e

Please sign in to comment.