Skip to content

Commit

Permalink
Make wait_until more flexible
Browse files Browse the repository at this point in the history
  • Loading branch information
NelsonVides committed Aug 23, 2019
1 parent e5c48e7 commit 1da8bee
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions test/async_helper.erl
Original file line number Diff line number Diff line change
Expand Up @@ -49,38 +49,40 @@ helper_loop() ->
end.

% @doc Waits `TimeLeft` for `Fun` to return `Expected Value`, then returns `ExpectedValue`
% If no value is returned or the result doesn't match `ExpetedValue` error is raised
% If no value is returned or the result doesn't match `ExpectedValue` error is raised

wait_until(Fun, ExpectedValue) ->
wait_until(Fun, ExpectedValue, #{}).

%% Example: wait_until(fun () -> ... end, SomeVal, #{time_left => timer:seconds(2)})
wait_until(Fun, ExpectedValue, Opts) ->
Defaults = #{time_left => timer:seconds(5),
DefValidator = fun(NewValue) -> ExpectedValue =:= NewValue end,
Defaults = #{validator => DefValidator,
time_left => timer:seconds(5),
sleep_time => 100,
history => []},
do_wait_until(Fun, ExpectedValue, maps:merge(Defaults, Opts)).
do_wait_until(Fun, maps:merge(Defaults, Opts)).

do_wait_until(_Fun, _ExpectedValue, #{
time_left := TimeLeft,
history := History
}) when TimeLeft =< 0 ->
do_wait_until(_Fun, #{
time_left := TimeLeft,
history := History
}) when TimeLeft =< 0 ->
error({badmatch, lists:reverse(History)});

do_wait_until(Fun, ExpectedValue, Opts) ->
do_wait_until(Fun, #{validator := Validator} = Opts) ->
try Fun() of
ExpectedValue ->
{ok, ExpectedValue};
OtherValue ->
wait_and_continue(Fun, ExpectedValue, OtherValue, Opts)
Value -> case Validator(Value) of
true -> {ok, Value};
_ -> wait_and_continue(Fun, Value, Opts)
end
catch Error:Reason ->
wait_and_continue(Fun, ExpectedValue, {Error, Reason}, Opts)
wait_and_continue(Fun, {Error, Reason}, Opts)
end.

wait_and_continue(Fun, ExpectedValue, FunResult, #{time_left := TimeLeft,
sleep_time := SleepTime,
history := History} = Opts) ->
wait_and_continue(Fun, FunResult, #{time_left := TimeLeft,
sleep_time := SleepTime,
history := History} = Opts) ->
timer:sleep(SleepTime),
do_wait_until(Fun, ExpectedValue, Opts#{time_left => TimeLeft - SleepTime,
history => [FunResult | History]}).
do_wait_until(Fun, Opts#{time_left => TimeLeft - SleepTime,
history => [FunResult | History]}).

0 comments on commit 1da8bee

Please sign in to comment.