Skip to content

Commit

Permalink
test: add assertion testing if value passes eventually
Browse files Browse the repository at this point in the history
  • Loading branch information
hauleth committed Nov 5, 2024
1 parent 3893fca commit 86a3d91
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
4 changes: 3 additions & 1 deletion 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 @@ -33,7 +35,7 @@ defmodule Supavisor.PromExTest do

Process.sleep(3000)

refute PromEx.get_metrics() =~ "tenant=\"#{@tenant}\""
refute_eventually(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

Check warning on line 1 in test/support/asserts.ex

View workflow job for this annotation

GitHub Actions / Code style

Modules should have a @moduledoc tag.
@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 86a3d91

Please sign in to comment.