-
-
Save slashdotdash/c1cdc2e58683d897b862c527ec9d0d8f to your computer and use it in GitHub Desktop.
Commanded test event assertions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule TestHelpers.EventAssertions do | |
use ExUnit.Case | |
def wait_for_event(event_type, predicate_fn) do | |
subscription_name = UUID.uuid4 | |
create_subscription(subscription_name) | |
try do | |
do_wait_for_event(event_type, predicate_fn) | |
after | |
remove_subscription(subscription_name) | |
end | |
end | |
def assert_receive_event(event_type, assertion_fn) do | |
assert_receive_event(event_type, assertion_fn, skip: 0) | |
end | |
def assert_receive_event(event_type, assertion_fn, skip: skip) do | |
subscription_name = UUID.uuid4 | |
create_subscription(subscription_name) | |
try do | |
do_assert_receive(event_type, assertion_fn, skip: skip) | |
after | |
remove_subscription(subscription_name) | |
end | |
end | |
defp create_subscription(subscription_name) do | |
{:ok, _subscription} = EventStore.subscribe_to_all_streams(subscription_name, self) | |
end | |
defp remove_subscription(subscription_name) do | |
EventStore.unsubscribe_from_all_streams(subscription_name) | |
end | |
defp do_assert_receive(event_type, assertion_fn, skip: 0) do | |
assert_receive {:events, received_events}, 1_000 | |
expected_type = Atom.to_string(event_type) | |
expected_event = Enum.find(received_events, fn received_event -> | |
case received_event.event_type do | |
^expected_type -> true | |
_ -> false | |
end | |
end) | |
case expected_event do | |
nil -> do_assert_receive(event_type, assertion_fn, skip: 0) | |
received_event -> apply(assertion_fn, [received_event.data]) | |
end | |
end | |
defp do_assert_receive(event_type, assertion_fn, skip: skip) do | |
assert_receive {:events, _skip_event}, 1_000 | |
do_assert_receive(event_type, assertion_fn, skip: skip - 1) | |
end | |
defp do_wait_for_event(event_type, predicate_fn) do | |
assert_receive {:events, received_events}, 1_000 | |
expected_type = Atom.to_string(event_type) | |
expected_event = Enum.find(received_events, fn received_event -> | |
case received_event.event_type do | |
^expected_type -> apply(predicate_fn, [received_event.data]) | |
_ -> false | |
end | |
end) | |
case expected_event do | |
nil -> do_wait_for_event(event_type, predicate_fn) | |
received_event -> received_event | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment