Writing Generators

Take a look at the basic generators required to test the system.

Getting started

Since we have a fairly large stateful system to validate, we should start by figuring out what data the system should accept, and what is valid and invalid. This is useful because it sets a baseline for expectations on which to build. It can also hint at useful paths or strategies moving forward. We’ve got a basic idea about the shape of data based on our database schema.

The generators

We’ll have a total of three generators for the initial testing of the application. They are as follows:

  • Title.
  • Author.
  • The ISBN, or International Standard Book Number, is a series of ten or thirteen digits that uniquely identify every book published.

Let’s take a look at these generators.

def title() do
    let s <- utf8() do
      elements([s, String.to_charlist(s)])
    end 
  end

  def author() do
    let s <- utf8() do
      elements([s, String.to_charlist(s)])
    end 
  end

def isbn() do
  let isbn <- [
        oneof(['978', '979']),
        let(x <- range(0, 9999), do: to_charlist(x)),
        let(x <- range(0, 9999), do: to_charlist(x)),
        let(x <- range(0, 999), do: to_charlist(x)),
        frequency([{10, [range(?0, ?9)]}, {1, 'X'}])
      ] do
    to_string(Enum.join(isbn, "-"))
  end
end

Since this is Elixir, and given that the virtual machine has no dedicated string types, both generators will create either multiple lists of characters (string()) or binaries of the same text encoded as UTF-8. This will let us check out whether the entire stack can support both types for the author and title generators.

For the isbn generator we don’t really care about their text formatting and will assume some other part of the system would test, validate, and normalize them. Instead, we use a more random generator that lets us focus on state transitions for the stateful model.

Now let’s test the generators to see if they work.

Get hands-on with 1400+ tech skills courses.