![](/img/trans.png)
[英]How to test or serialize struct in Phoenix.Socket.Broadcast payload?
[英]How to test that a Phoenix socket is terminated?
我正在寻找一种方法来测试套接字是否已终止。 被测试的代码执行此操作:
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
我应该如何测试套接字关闭?
当您监视的进程关闭时发送的消息是{:DOWN, ref, :process, pid, reason}
,因此
你的assert_receive
应该有一个5元组
您应该原因终止:normal
,如果你想匹配的原因:normal
。 如果执行此操作,则不必捕获任何退出信号(如果要使用:logout
退出,请参见下文)。
以下对我有用:
def handle_in("logout", _payload, socket) do
{:stop, :normal, socket |> assign(:user, nil)}
end
test "...", %{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
以外,您还必须捕获退出,因为:normal
会导致将退出信号发送到链接到该进程的所有进程,并且在测试,运行测试的过程中被链接到socket.channel_pid
。 以下作品:
def handle_in("logout", _payload, socket) do
{:stop, :logout, socket |> assign(:user, nil)}
end
test "...", %{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
通过Elixir Slack频道收到了很好的答复:
修改测试代码以捕获出口信号。 这是按预期工作的更新测试:
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
并且一切都很安静。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.