Skip to content

Commit

Permalink
test: add assertion testing if value passes eventually (#470)
Browse files Browse the repository at this point in the history
  • Loading branch information
hauleth authored Nov 5, 2024
1 parent 3893fca commit 07b4008
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
6 changes: 3 additions & 3 deletions test/supavisor/prom_ex_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ defmodule Supavisor.PromExTest do
use ExUnit.Case, async: true
use Supavisor.DataCase

import Supavisor.Asserts

alias Supavisor.Monitoring.PromEx

@tenant "prom_tenant"
Expand Down Expand Up @@ -31,9 +33,7 @@ defmodule Supavisor.PromExTest do
:ok = GenServer.stop(proxy)
:ok = Supavisor.stop({{:single, @tenant}, user, :transaction, db_name, nil})

Process.sleep(3000)

refute PromEx.get_metrics() =~ "tenant=\"#{@tenant}\""
refute_eventually(10, fn -> PromEx.get_metrics() =~ "tenant=\"#{@tenant}\"" end)
end

test "clean_string/1 removes extra spaces from metric string" do
Expand Down
41 changes: 41 additions & 0 deletions test/support/asserts.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
defmodule Supavisor.Asserts do
@doc """
Asserts that `function` will eventually success. Fails otherwise.
It performs `repeats` checks with `delay` milliseconds between each check.
"""
def assert_eventually(repeats \\ 5, delay \\ 1000, function)

def assert_eventually(0, _, _) do
raise ExUnit.AssertionError, message: "Expected function to return truthy value"
end

def assert_eventually(n, delay, func) do
if func.() do
:ok
else
Process.sleep(delay)
assert_eventually(n - 1, delay, func)
end
end

@doc """
Asserts that `function` will eventually fail. Fails otherwise.
It performs `repeats` checks with `delay` milliseconds between each check.
"""
def refute_eventually(repeats \\ 5, delay \\ 1000, function)

def refute_eventually(0, _, _) do
raise ExUnit.AssertionError, message: "Expected function to return falsey value"
end

def refute_eventually(n, delay, func) do
if func.() do
Process.sleep(delay)
refute_eventually(n - 1, delay, func)
else
:ok
end
end
end

0 comments on commit 07b4008

Please sign in to comment.