allenwyma

allenwyma

Testing IO from STDIN in Elixir

I’m quite stuck at something I thought would be quite straight forward, but it seems maybe this topic hasn’t come up much in my career in Elixir.

I am trying to run a test to check STOUT and test STDIN for a function:

test "can read and output" do
    input =
    """
    3
    Hello
    Hello World
    Hello A B World
    """
    assert ExUnit.CaptureIO.capture_io(fn ->
             IO.write(input)
            task = Task.async(Example, :start, [])
            Task.await(task)
           end) == """
    3
    Hello
    Hello World
    Hello B A World
    """
  end

Within my code I’ve been trying to read from stdin, but I keep getting :eof when I used IO.read(:line) or ""if I tryIO.read(:all)`.

I’m pretty sure I must be close, but I am missing something somewhere. The reason I’m launching a task is because I’m pretty sure the code will block so I’m unable to write to :stdio.

here’s my code for the function:

def start(pid \\ :stdio) do
    number_of_lines =
      IO.read(pid, :read)
      |> String.trim()
      |> String.to_integer()
    Enum.each(0..number_of_lines, fn _i ->
      sentence =
        IO.read(pid, :line)
        |> IO.inspect()
        |> String.trim()
        |> String.split()
      sentence_to_write =
        if length(sentence) > 2 do
          [hd | tail] = sentence
          {last, rest} = List.pop_at(tail, length(tail))
          new_tail = Enum.reverse(rest) ++ [last]
          [hd | new_tail]
        else
          sentence
        end
      sentence_to_write
      |> Enum.reduce(fn word, acc ->
        acc <> " " <> word
      end)
      |> IO.write(pid)
    end)
  end

The there’s a pid there is I was also thinking I can create a pid that responds to the message protocol for writing to a device, but I kind of gave up around there, thinking there must be a way to do this without creating another process.

Does anyone have any idea about how I can achieve this?

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement