AndyL

AndyL

ExUnit / Data-Driven Tests / Macros

Elixir newbie here working on a stemmer for a document indexing engine. The stemming algorithm has dozens of steps with many tests per step. I’ve got a data-driven approach that is helpful, but I think it must be possible to be even more efficient with a little meta-programming. Here is an example of one of my test modules:

defmodule StemEx.StepsTest do

  use ExUnit.Case, async: true

  # ----- step1a -----
  
  step1a_vals = [ 
     ["caresses" , "caress"],
     ["ponies"   , "poni"  ],
     ["ties"     , "ti"    ],
     ["caress"   , "caress"],
     ["cats"     , "cat"   ],
  ]

  for [input, output] <- step1a_vals do
    @input  input
    @output output
    test "step1a: '#{input}' has output of '#{output}'" do
      assert StemEx.Steps.step1a(@input) == @output
    end
  end

  # ----- step1b -----

  step1b_vals = [
     ["feed"     , "feed"    ],
     ["agreed"   , "agree"   ],
     ["plastered", "plaster" ],
     ["bled"     , "bled"    ],
     ["motoring" , "motoring"],
     ["sing"     , "sing"    ],
  ]

  for [input, output] <- step1b_vals do
    @input  input
    @output output
    test "step1b: '#{input}' has output of '#{output}'" do
      assert StemEx.Steps.step1b(@input) == @output
    end
  end
end

This works great but I don’t like to repetitive boilerplate in the for blocks. Ideally I could reduce the blocks to a single call - something like test_loop_for("step1b", step1b_vals).

Would it be possible to use a defmacro to auto-magically generate the loop code? Can someone post an example?? Thanks in advance.

Most Liked

axelson

axelson

Scenic Core Team

For anyone else that comes across this as an example of data-driven tests and wants to improve their test reporting output you can do something like the following:

test "stem transformations" do
  input_list  = String.split(File.read!("test/data/voc.txt")   , "\n")
  output_list = String.split(File.read!("test/data/output.txt"), "\n")
  io_list     = List.zip([input_list, output_list])
  for {input, output} <- io_list do
    actual = StemEx.stem(input)

    message = """
    StemEx.stem(
      input = #{inspect input}
    )
    was expected to output #{output} but instead was #{actual}
    """

    assert actual == output, message
  end
end

This will give you pretty output like:

1) test stem transformations (StemExTest)
   test/stem_ex_test.exs:10
   StemExTest.stem(
     input = "some input"
   )
   was expected to equal false but instead was true

Whereas the default output show something more like:

Assertion with == failed
code:  StemExTest.stem(input) == output
left:  true
right: false

Which isn’t that helpful since you can’t tell what the input is without adding some IO.puts into your test code. There’s probably more elegant ways to accomplish what I’m outlining but I think this is at least a good start!

AndyL

AndyL

I ended up with a solution that looks much like your example. Simpler than metaprogramming (maybe this is metaprogramming?!) Not sure exactly what is going on under the covers - but it seems to give a lot of flexibility for data-driven tests. The tests run very fast and the failure messages are easy to decipher. Looks like you can load datasets from the filesystem - I’ve got a files with ~22K test examples. Just saved a lot of typing! :grinning:

defmodule StemEx.StepsTest do

  use ExUnit.Case, async: true

  functions = %{
    step1a: &StemEx.Steps.step1a/1  ,
    step1b: &StemEx.Steps.step1b/1  ,
  }
  
  values = [
     [:step1a  ,  "caresses"  , "caress"  ],
     [:step1a  ,  "ponies"    , "poni"    ],
     [:step1a  ,  "ties"      , "ti"      ],
     [:step1a  ,  "caress"    , "caress"  ],
     [:step1a  ,  "cats"      , "cat"     ],

     [:step1b  ,  "feed"      , "feed"    ],
     [:step1b  ,  "agreed"    , "agree"   ],
     [:step1b  ,  "plastered" , "plaster" ],
     [:step1b  ,  "bled"      , "bled"    ],
     [:step1b  ,  "motoring"  , "motoring"],
     [:step1b  ,  "sing"      , "sing"    ],
  ]

  for [label, input, output] <- values do
    @label  label
    @input  input
    @output output
    @func   functions[@label]
    test "#{label}: '#{input}' has output of '#{output}'" do
      assert @func.(@input) == @output
    end
  end
end

sheharyarn

sheharyarn

How about Enum.each/2? I do something like this myself. Here’s how it would look:

defmodule StemEx.StepsTest do
  use ExUnit.Case, async: true

  tests = [
    step1a: [
      ["caresses" , "caress"],
      ["ponies"   , "poni"  ],
      ["ties"     , "ti"    ],
      ["caress"   , "caress"],
      ["cats"     , "cat"   ],
    ],

    step1b: [
      ["feed"     , "feed"    ],
      ["agreed"   , "agree"   ],
      ["plastered", "plaster" ],
      ["bled"     , "bled"    ],
      ["motoring" , "motoring"],
      ["sing"     , "sing"    ],
    ]
  ]

  Enum.each tests, fn {name, values} ->
    @name name

    for [input, output] <- values do
      @input  input
      @output output

      test "#{@name}: '#{input}' has output of '#{output}'" do
        result = apply(StemEx.Steps, @name, [@input])
        assert result == @output
      end
    end
  end

end

Where Next?

Popular in Questions Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54260 488
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40165 209
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement