gleb

gleb

Assert_value - ExUnit's assert on steroids that writes and updates tests for you

Hi everyone,

We are releasing assert_value. assert_value is ExUnit’s assert on steroids that writes and updates tests for you.

You can use assert_value instead of ExUnit’s assert. It makes Elixir tests interactive and lets you create and update expected values with a single key press.

Here is a simple example. Start with a broken test:

assert_value "foo\n" == """
bar
"""

Run tests as usual. assert_value will show the diff and ask you what to do. Here we like the new value and tell assert_value to accept it:

~/> mix test

test/my_test.exs:6:"test example" assert_value "foo\n" == "bar\n" failed

-bar
+foo

Accept new value? [y,n,?] y
.

Finished in 1.0 seconds
1 test, 0 failures

Your test will be automatically updated:

assert_value "foo\n" == """
foo
"""

Benefits:

  • makes writing tests easier by automatically generating expected values
  • makes maintaining tests and refactoring code much easier
  • improves test readability

You will find usage examples and documentation in the README on GitHub.

We appreciate all feedback.

P.S. We also have a ruby version of this library. The elixir version turned out to be a substantial improvement over the ruby version. Because of macros we are able to use more natural, composable, and extensible syntax. Another huge advantage is async tests and assert_value supports them fully.

First 10 of 15 Posts Switch mode

tmbb

tmbb

This is very, very cool. Mutating the test file interactively is a great way of going over the natural laziness of writing tests in cases that are not good for property testing. There seems to be a limitation in which it only works for strings, right? Why don’t you just convert the value into an Erlang term, store it into a file (or even write it inline)? It’s strictly better than using strings in my opinion.

Now, I might have a use for this. I’m the author of the Makeup syntax highlighting library. It needs some automated tests (badly, it’s > 1000k lines of code with almost no tests), as currently all testing is visual integration testing by examining the output (there is some low hanging fruit to be had from property testing, but that’s limited).

assert_value seems like a good tool for the job: I can just dump some source code snippets somewhere, run assert_value on them, compare the output (at least the tokenization, comparing the HTML output is harder). Ultimately, this is waht I’d like to have:

I’m comparing the visual output for my program, and it happens to be in HTML. I’d like to select some code snippets, have them converted into HTML and shown in some form of HTML canvas somewhere so that I could mark them as correct. The most immediate way I can think of implement this is to have the tests start an HTTP server, start a web browser and then ask the user if the output is correct or not.

For example (ridiculous mockup I’ve done in 5mins):

An then repeat for all test cases.

joshtaylor

joshtaylor

This is awesome - had a similar idea recently about updating tests like this, so glad somebody else made it! Awesome work!

smetana

smetana

Co-author here. Thank you!

Left argument can be anything with implemented String.Chars protocol (String, Atom, Integer, Float… etc.). In all other cases you have to serialize left argument to string. Right argument should always be a string heredoc.

We use heredoc because we need to modify test source code. Currently it is hard to search/replace values in the code because Elixir’s AST gives us only line number without column offset. With heredocs it is easy to search for """ and replace everything in-between.

We are planning to support all types of arguments in Elixir 1.6. It will have formatter metadata in AST which will help a lot.

Exactly! assert value can test for expected values stored in files. You can even compare content of two files:

assert_value File.read!("input.txt") == File.read!("reference.txt")

It is smart enough to recognize File.read! as right argument and will update contents of a file. With Elixir macros you can easily create test for bunch of files in some directory:

defmodule Support do
  defmacro build_tests do
    filenames =
      Path.expand("data/*.txt", __DIR__)
      |> Path.wildcard

    for filename <- filenames do
      quote do
        test unquote(filename) do
          assert_value File.read!(unquote(filename)) == File.read!(unquote(filename <> ".ref"))
        end
      end
    end

  end
end

defmodule MyTest do
  use ExUnit.Case
  import AssertValue
  import Support

  build_tests()
end

Having something like this you will have a separate test for each file and any failed test will not break other tests. And you can start with just input files without reference files:

~/>mix test
test/my_test.exs:34:"test test/data/foo.txt" assert_value File.read!("/home/examp... failed

-
+foo

Accept new value? [y,n,?] y
.
test/my_test.exs:34:"test test/data/bar.txt" assert_value File.read!("/home/examp... failed

-
+bar

Accept new value? [y,n,?] y
.

Finished in 3.6 seconds
2 tests, 0 failures

Hope this will help.

michalmuskala

michalmuskala

tmbb

tmbb

Yes. Actually, I think the idea is very simple: you just generate data once, confirm that it’s the correct result and then check for regressions.

The trick is having a good implementation for the real bottleneck, which is human inspection of the results the first time they’re generated. assert_value seems to provide a good UI.

But there are other possible design decisions that might lead to different (and possibly better) UIs. For example:

  • assert_value is synchronous. It stops at each test result that hasn’t been checked. Why not making that async after all test have run? One could gather all test results pending confirmation and show them all at once to the user once the test suite has run. I don’t know if this brings any benefits, just thinking about it.

  • Another possible improvement (although a bit specialized) for programs that generate reproducible HTML would be to show the results in a web browser through an embedded Plug app. The user could inspect the result visually instead of arsing it tag by tag. This is what I discussed above regarding Makeup. Often you want to use serializers like the authors of assert_value suggest, of course.

One could also generalize the concept to imething like property testing, but in which the property is visual inspection by a human (subsequent runs will compare to the reference result, of course).

EDIT: removed last paragraph because I’ve just reread the links and it turns out I had misinterpreted it.

brightball

brightball

As somebody who generally hates unit tests because of exactly the problem this solves…thank you

smetana

smetana

assert_value is asynchronous. While assert_value waits for user input the other tests continue to run. Only interactions with the user are synchronous.

You will want to split things across multiple tests. Each test should invoke Makeup on a single input file and assert the output. You will want to separate tests like this because test terminates when the first assert in it fails and to get maximum parallelism. That’s why my code above generates one test per input file instead of a big test for all files. I should have made this more clear.

The way we could do it is something like GIT_EXTERNAL_DIFF. That would make sense.

tmbb

tmbb

This should certainly be made more clear! I haven’t tried your library yet but I was under the completely wrong impression that it would pause waiting for input.

tmbb

tmbb

Hm… Doesn’t seem ideal for the use case of visually inspecting Makeup’s output. In that case I don’t care about diffs, I want to look at the rendered HTM. But in any case that’s probably not a good idea. Inspecting the list of tokens is probably much more useful than the rendered HTML and that can be done with serializers like your webpage example.

My idea of using a web browser was that you could compare things visually that might be hard to do textually. I admit I don’t have a concrete example for that (even Makeup isn’t probably the best example). Code that generates images is an obvious case, of course. You’d probably never do that in Elixir, so that’s not a problem, of couse. I guess I was fantasizing on an architecture that could be useful someday for something without thinking too hard about it.

gleb

gleb OP

I agree, the intent is quite similar. Thanks for the links!

Where Next?

Trending in Announcing Top

bluzky
You may know https://ui.shadcn.com/, a UI component library for React. I really love it’s design style and components. I’ve built some co...
387 14960 120
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
shahryarjb
The Chelekom project is a library of Phoenix and LiveView components generated via Mix tasks to fit developer needs seamlessly. One of i...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

Other Trending Topics Top

type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
bjorng
We want to introduce a new native datatype to Erlang: native records. Although replacing all tuple records with native records is not our...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New

We're in Beta

About us Mission Statement