From 943d3abca471a6b96e0b3392fe904c11428d7cbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Tue, 5 Nov 2024 16:47:44 +0100 Subject: [PATCH] test: add assertion testing if value passes eventually --- test/supavisor/prom_ex_test.exs | 6 ++--- test/support/asserts.ex | 41 +++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 test/support/asserts.ex diff --git a/test/supavisor/prom_ex_test.exs b/test/supavisor/prom_ex_test.exs index df684260..b489f44f 100644 --- a/test/supavisor/prom_ex_test.exs +++ b/test/supavisor/prom_ex_test.exs @@ -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" @@ -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 diff --git a/test/support/asserts.ex b/test/support/asserts.ex new file mode 100644 index 00000000..d0e720b9 --- /dev/null +++ b/test/support/asserts.ex @@ -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