Skip to content

Instantly share code, notes, and snippets.

@bryanhunter
Last active March 31, 2018 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanhunter/bec43a2412393399e82ea5b8da3866c9 to your computer and use it in GitHub Desktop.
Save bryanhunter/bec43a2412393399e82ea5b8da3866c9 to your computer and use it in GitHub Desktop.
An example of property-based testing in Elixir 1.6
# Until StreamData ships in Elixir it needs to be added as a dependency.
# https://hexdocs.pm/stream_data/StreamData.html#content
# https://hex.pm/packages/stream_data
# Add this to your mix.exs deps...
# {:stream_data, "~> 0.4.2"}
defmodule ColorNameTest do
use ExUnit.Case, async: true
use ExUnitProperties
property "color_name/3" do
check all red <- StreamData.integer(0..255),
green <- StreamData.integer(0..255),
blue <- StreamData.integer(0..255),
max_runs: 100_000
do
assert color_name(red, green, blue) != :impossible_color
end
end
def color_name(0, 0, 0), do: :black
def color_name(255, 255, 255), do: :white
def color_name(red, green, blue) when red > green and red > blue, do: :red
def color_name(red, green, blue) when green > red and green > blue, do: :green
def color_name(red, green, blue) when blue > red and blue > green, do: :blue
def color_name(_, _, _), do: :impossible_color
end
# Note: when the test above fails, these might come in handy ;)
# def color_name(red, green, blue) when red == green and red > blue, do: :yellow
# def color_name(red, green, blue) when red == blue and red > green, do: :purple
# def color_name(red, green, blue) when green == blue and green > red, do: :cyan
# Oh, and this one...
# def color_name(red = gray, green = gray, blue = gray), do: :gray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment