Search code examples
testinghashsetelixirdoctest

Testing HashSets in doctest


I am trying to test HashSet using doctest via iex. If I run the line below, it gives the same result, but the #HashSet<["rockerboo"]>} can not be represented in the syntax. I can't think of a way to represent it properly, and I can't find any examples of it. Thanks!

  @doc """
  Adds user to HashSet in state

  ## Examples
      iex> Elirc.Channel.add_user_to_state("rockerboo", %{users: HashSet.new})
      %{users: #HashSet<["rockerboo"]>}
  """
  def add_user_to_state(user, state) do
    %{state | users: HashSet.put(state.users, user) }
  end

When running mix test, I get the following error.

 Doctest did not compile, got: (TokenMissingError) lib/elirc/channel.ex:99: missing terminator: } (for "{" starting at line 99)
 code: %{users: #HashSet<["rockerboo"]>}

Line 99 is %{state...


Solution

  • You can construct your HashSet in a different way so that it's a valid Elixir expression. For example this worked for me:

    ## Examples
      iex> Elirc.Channel.add_user_to_state("rockerboo", %{users: HashSet.new})
      %{users: ["rockerboo"] |> Enum.into(HashSet.new)}
    

    This is also the approach that is recommended by the ExUnit.DocTest documentation under "Opaque Types"