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.

title() ->
    ?LET(S, string(), elements([S, unicode:characters_to_binary(S)])).

author() ->
    ?LET(S, string(), elements([S, unicode:characters_to_binary(S)])).

isbn() ->
    ?LET(ISBN,
         [oneof(["978","979"]),
          ?LET(X, range(0,9999), integer_to_list(X)),
          ?LET(X, range(0,9999), integer_to_list(X)),
          ?LET(X, range(0,999), integer_to_list(X)),
          frequency([{10, range($0,$9)}, {1, "X"}])],
         iolist_to_binary(lists:join("-", ISBN))).

Since this is Erlang, 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 1200+ tech skills courses.