Last active
March 31, 2018 18:41
-
-
Save bryanhunter/bec43a2412393399e82ea5b8da3866c9 to your computer and use it in GitHub Desktop.
An example of property-based testing in Elixir 1.6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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