我有一个应用远程连接到另一个节点。该应用必须能够使用此节点调用远距离函数。从iex调用时,它可以工作,但是我真的很难正确进行集成测试。我想检查一下远程应用程序的返回结果,以及它是否符合预期。
这是我的genserver的代码(也欢迎使用代码见解,但仍然不太满意):
defmodule MyApp.MyExternalAppModule do
use GenServer
@external_app_node Application.get_env(:my_app, :external_app_node)
@mailer Application.get_env(:my_app, :mailer)
def start_link(_args) do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
end
def insert(field1, field2, field3) do
GenServer.call(__MODULE__, {:insert, field1, field2, field3})
end
def init(%{}) do
{:ok, %{ref: nil}}
end
def handle_call(
{:insert, _field1, _field2, _field3},
_from,
%{ref: ref} = state
)
when is_reference(ref) do
{:reply, :ok, state}
end
def handle_call({:insert, field1, field2, field3}, _from, %{ref: nil}) do
task =
Task.Supervisor.async_nolink(
{MyExternalApp.TaskSupervisor, @external_app_node},
MyExternalApp.MyExternalAppModule,
:my_function,
[field1, field2, field3]
)
{:reply, :ok, %{field1: field1, field2: field2, field3: field3, ref: task.ref}}
end
def handle_info(
{ref, {:ok, _external_element}},
%{ref: ref, field1: field1, field2: field2, field3: field3} = state
) do
Process.demonitor(ref, [:flush])
@mailer.send_mail("(...)success")
{:noreply, %{state | ref: nil}}
end
def handle_info(
{ref, {:error, reason}},
%{ref: ref, field1: field1, field2: field2, field3: field3} = state
)
when is_atom(reason) do
Process.demonitor(ref, [:flush])
@mailer.send_mail("(...)failure")
{:noreply, %{state | ref: nil}}
end
def handle_info(
{ref, {:error, _changeset}},
%{ref: ref, field1: field1, field2: field2, field3: field3} = state
) do
Process.demonitor(ref, [:flush])
@mailer.send_mail("(...)failure")
{:noreply, %{state | ref: nil}}
end
end
测试:
defmodule MyApp.MyExternalAppModuleTest do
use ExUnit.Case, async: true
@my_external_app_module Application.get_env(:my_app, :my_external_app_module)
describe "insert/3" do
test "when my_external_app node is up and the data doesn't exist returns (TODO)" do
assert_receive {_, {:ok, _}}, 3000
assert :ok == @my_external_app_module.insert("field1", "field2", "field3")
end
end
end
因此assert_receive {_, {:ok, _}}, 3000
显然不起作用...我试图以多种方式塑造它,却没有找到它应该如何工作。我想做的是检查是否调用了正确的handle_info,并且数据是否符合预期。
主要是关于assert_receive
的行为。
答案 0 :(得分:0)
我有与此类似的问题,但是在测试中我没有使用assert_receive
,而是通过使用Erlangs的:sys.get_state/1
解决了这个问题,您必须通过的参数是{{ 1}}。此功能将等待,直到处理了该进程的邮箱中的所有消息,然后它将返回该进程的状态。因此,在获得状态后,您可以将其与期望更改的值进行比较。
答案 1 :(得分:0)
解决方案是使用类似的东西来跟踪传入的消息
:erlang.trace(pid, true, [:receive])
然后您用
查看消息assert_received {:trace, ^pid, :receive, {:"$gen_call", _, :something}}
确保call
有效,然后
:timer.sleep(100) # Just to make sure not tu run into a race condition
assert_receive {:trace, ^pid, :receive, {ref, :returned_data}}