inputelixirex-unit

ExUnit.CaptureIO still waits for input on multiple IO.read calls


Consider the following minimal [?] example:

defmodule Foo do
  def bar() do
    n = IO.read(:line) |> String.trim() |> String.to_integer()
    for _ <- 0..n - 1 do
      IO.read(:line) |> IO.write()
    end
  end
end

import ExUnit.CaptureIO
capture_io("2\nabc\ndef", Foo.bar)

I did look into the documentation, and it puts no limitations on ExUnit.CaptureIO usage, but the aforelisted code hangs, waiting for the first line of input, as if it hasn't been fed. Have I missed something?

If it matters, I'm using Elixir 1.7.3.


Solution

  • The second argument to capture_io needs to be a function to run with the capturing enabled. Here, you're passing in the result of running Foo.bar. That hangs forever, as it is expecting input from stdio, which never comes. Long story short you need to pass it as a function:

    capture_io("2\nabc\ndef", &Foo.bar/0)
    

    because Foo.bar is the same as Foo.bar().