我在找一种方法来测试套接字是否会终止。正在测试的代码这样做:
def handle_in("logout", _payload, socket) do
{:stop, :logout, socket |> assign(:user, nil)}
end我的测试代码(改编自http://elixir-lang.org/getting-started/try-catch-and-rescue.html#exits)是这样做的:
test "logout terminates the socket", %{socket: socket} do
try do
push socket, "logout"
catch
huh -> IO.puts("Caught something #{IO.inspect huh}")
:exit, what -> IO.puts("Caught :exit #{IO.inspect what}")
end
assert_receive {:DOWN, monitor_ref, _, :normal}
end但当我做测试的时候,我得到了这个:
1) test logout without login terminates the socket (Main.AuthChannelTest)
test/channels/auth_channel_test.exs:47
** (EXIT from #PID<0.505.0>) :logout
.....09:06:41.139 [error] GenServer #PID<0.507.0> terminating
** (stop) :logout我应该如何测试套接字关闭?
发布于 2016-10-05 17:14:28
当您监视的进程发生故障时发送的消息是{:DOWN, ref, :process, pid, reason},因此
assert_receive中有一个5个元组:normal匹配,则应该以原因:normal结束。如果这样做,就不必捕获任何退出信号(如果您想要使用:logout退出,请参见下面)。以下几点对我来说是可行的:
def handle_in("logout", _payload, socket) do
{:stop, :normal, socket |> assign(:user, nil)}
endtest "...", %{socket: %{channel_pid: channel_pid} = socket} do
monitor_ref = Process.monitor(channel_pid)
push socket, "logout", %{}
assert_receive {:DOWN, ^monitor_ref, _, _, :normal}
end如果您出于某种原因希望使用:logout退出套接字,则还必须捕获退出,因为除:normal之外的任何原因都会将退出信号发送到与进程链接的所有进程,而在测试中,运行测试的进程被链接到socket.channel_pid。以下工作:
def handle_in("logout", _payload, socket) do
{:stop, :logout, socket |> assign(:user, nil)}
endtest "...", %{socket: %{channel_pid: channel_pid} = socket} do
Process.flag(:trap_exit, true)
monitor_ref = Process.monitor(channel_pid)
push socket, "logout", %{}
assert_receive {:DOWN, ^monitor_ref, _, _, :logout}
end发布于 2016-10-05 17:11:59
通过“灵丹妙药”频道得到了一个很好的答案:
修改测试代码以捕获退出信号。下面是正在按预期工作的更新测试:
test "logout terminates the socket", %{socket: socket} do
Process.flag(:trap_exit, true)
push socket, "logout"
socket_pid = socket.channel_pid
assert_receive {:EXIT, ^socket_pid, :logout}
end请注意,这里仍然存在控制台日志噪声,因此我已经将退出原因更改为:normal,并且一切都很安静。
https://stackoverflow.com/questions/39879632
复制相似问题