Skip to content

Instantly share code, notes, and snippets.

@thmsmlr
Created December 26, 2024 21:20
Show Gist options
  • Select an option

  • Save thmsmlr/8b32cc702acb48f39e653afc0902374f to your computer and use it in GitHub Desktop.

Select an option

Save thmsmlr/8b32cc702acb48f39e653afc0902374f to your computer and use it in GitHub Desktop.

Revisions

  1. thmsmlr created this gist Dec 26, 2024.
    40 changes: 40 additions & 0 deletions wait_for.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    @default_timeout 100
    @check_interval 10

    # Test Helpers

    defp wait_for(fun, timeout \\ @default_timeout) do
    start_time = System.monotonic_time(:millisecond)
    ref = make_ref()

    try do
    do_wait_for(fun, start_time, timeout, ref, nil)
    catch
    {:wait_for_timeout, ^ref, last_error} ->
    message = """
    Assertion did not succeed within #{timeout}ms.
    Last failure:
    #{Exception.format(:error, last_error, [])}
    """

    flunk(message)
    end
    end

    defp do_wait_for(fun, start_time, timeout, ref, _last_error) do
    try do
    fun.()
    :ok
    rescue
    error in [ExUnit.AssertionError] ->
    current_time = System.monotonic_time(:millisecond)

    if current_time - start_time < timeout do
    Process.sleep(@check_interval)
    do_wait_for(fun, start_time, timeout, ref, error)
    else
    throw({:wait_for_timeout, ref, error})
    end
    end
    end