Skip to content

Feature request: specs for constant values #68

@Qqwy

Description

@Qqwy

Currently, tuples and atoms already are converted to specs automatically (They implement the Norm.Conformer.Conformable protocol). I think it would make sense if that same protocol is implemented for other values that are often 'on their own':

  • Binaries. It is very common to use binary strings that follow certain patterns to e.g. parse user input. An example would be to match on routes/paths in a web-application. Some parts of these routes are dynamic, but most are static.
  • Integers. For better or worse, certain integer values are 'constants', expecially when used as part of a one_of in a list of possible options.
  • Possibly ranges, where the spec for a range will check if the input is inside the range. (and the generator will only generate integers inside the range).

For other datatypes, I'd like to see a wrapper function &constant/1 whose implementation is something like

def constant(val) do
  spec(&(&1 == val)) 
  |> with_gen(StreamData.constant(val))
end

One question that remains is what should happen if we want to mix constants with other specs.

For instance, if I have a web-application with a 'posts' route nested under users, we end up with something like:

def id_spec(), do: spec(is_string())

def posts_show_route(), do: spec(["users", id_spec(), "posts", id_spec()])
def posts_route(), do: spec(["users", id_spec(), "posts"])
def user_show_route(), do: spec(["users", id_spec()])
def users_route(), do: spec(["users"])

def routes(), do: one_of(posts_show_route(), posts_route(), users_show_route(), users_route()]

The problem in above example is passing a list immediately to spec(). One could write e.g. constant(["uses", id_spec()]) instead, but what would that mean?

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions