测试从生成的进程中捕获的IO

时间:2016-06-27 22:39:39

标签: io elixir spawn ex-unit

我想在以下方法上测试返回值和IO输出:

defmodule Speaker do
  def speak do
    receive do
      { :say, msg } ->
        IO.puts(msg)
        speak
      _other ->
        speak # throw away the message
    end
  end
end

ExUnit.CaptureIO docs中,有一个示例测试可以执行此操作,如下所示:

test "checking the return value and the IO output" do
  fun = fn ->
    assert Enum.each(["some", "example"], &(IO.puts &1)) == :ok
  end
  assert capture_io(fun) == "some\nexample\n"
end

鉴于此,我认为我可以编写以下测试,执行类似的操作但使用spawn ed过程:

test ".speak with capture io" do
  pid = Kernel.spawn(Speaker, :speak, [])
  fun = fn ->
    assert send(pid, { :say, "Hello" }) == { :say, "Hello" }
  end
  assert capture_io(fun) == "Hello\n"
end

但是,我收到以下错误消息,告诉我没有输出,即使我可以在终端上看到输出:

1) test .speak with capture io (SpeakerTest)
   test/speaker_test.exs:25
   Assertion with == failed
   code: capture_io(fun) == "Hello\n"
   lhs:  ""
   rhs:  "Hello\n"
   stacktrace:
     test/speaker_test.exs:30: (test)

那么,我是否遗漏了一些关于测试spawn ed过程或使用receive宏的方法的问题?如何更改测试以使其通过?

2 个答案:

答案 0 :(得分:5)

CaptureIO可能不适合您在此尝试做的事情。它运行一个函数,并在该函数返回时返回捕获的输出。但是你的功能永远不会回归,所以看起来这不会起作用。我提出了以下解决方法:

test ".speak with capture io" do
  test_process = self()
  pid = spawn(fn ->
    Process.group_leader(self(), test_process)
    Speaker.speak
  end)

  send(pid, {:say, "Hello"})

  assert_receive {:io_request, _, _, {:put_chars, :unicode, "Hello\n"}}

  # Just to cleanup pid which dies upon not receiving a correct response
  # to the :io_request after a timeout
  Process.exit(pid, :kill)
end

它使用Process.group_leader将当前进程设置为测试进程的IO消息接收者,然后断言这些消息到达。

答案 1 :(得分:0)

我遇到了类似的问题,我的Application上有一个注册过程,每隔10秒就会超时,并用IO.binwrite写入stdio,以模拟我在@ Pawel-Obrok上的多次超时回答,但将其更改为使用:io_request回复:io_reply,这样该过程就不会挂起,从而允许我发送多条消息。

defp assert_io() do
  send(MyProcess, :timeout)
  receive do
    {:io_request, _, reply_as, {:put_chars, _, msg}} ->
      assert msg == "Some IO message"
      send(Stats, {:io_reply, reply_as, :ok})

    _ ->
      flunk
  end
end

test "get multiple messages" do
  Process.group_leader(Process.whereis(MyProcess), self())
  assert_io()
  assert_io()
end

如果您想了解有关IO协议的更多信息,请查看the erlang docs about it.