How do I test this with assert?

I have a function that takes this value and creates a random string. This will create 2 random values for lower letters and 4 random numbers.

test "create the random string" do

result = Create_random_string(%{
        random: [%{a: 2, b: "l"}, %{a: 4, b: "d"}]
      }) 

assert String.match?(result, ~r/[A-Za-z0-9]/)
end

Now I need to test for a particular key there and check if %{a: 2, b: “l”} this has created 2 lower letters. Similarly
if this has created %{a: 4, b: “d”} 4 numbers. how can I test it?

You can get the required info form the string with:

iex(1)> String.graphemes("aaab12ASDFF123") |> Enum.frequencies_by(fn c ->
...(1)>  cond do
...(1)>      c =~ ~r/[0-9]/ -> :num
...(1)>      c =~ ~r/[A-Z]/ -> :upper
...(1)>      c =~ ~r/[a-z]/ -> :lower
...(1)>    end
...(1)>  end)
%{lower: 4, num: 5, upper: 5}

And then you can compare this with your random argument.

2 Likes

I was hoping for something simple that I can use with assert

I can’t think of anything simpler, sorry. But in your tests it could look like:

...
  test "some test" do
    result = Create_random_string(%{
        random: [%{a: 2, b: "l"}, %{a: 4, b: "d"}]
      }) 
    assert frequencies(result) == %{lower: 2, num: 4}
  end

  defp frequencies(string) do
     String.graphemes(string) |> Enum.frequencies_by(fn c ->
      cond do
        c =~ ~r/[0-9]/ -> :num
        c =~ ~r/[A-Z]/ -> :upper
        c =~ ~r/[a-z]/ -> :lower
      end
    end) 
  end
1 Like