Skip to content

Commit

Permalink
Merge pull request #58 from solnic/55-the-in-predicate-raises-an-exce…
Browse files Browse the repository at this point in the history
…ption-for-single-element-lists

Handle in? and not_in? with a single element list
  • Loading branch information
solnic authored Jul 26, 2024
2 parents 8c02237 + 4aebadc commit ba0813b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
5 changes: 5 additions & 0 deletions lib/drops/type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,11 @@ defmodule Drops.Type do
predicate(name, [])
end

@doc false
def predicate(name, args) when name in [:in?, :not_in?] and length(args) == 1 do
{:predicate, {name, [args]}}
end

@doc false
def predicate(name, args) do
{:predicate, {name, args}}
Expand Down
42 changes: 40 additions & 2 deletions test/drops/contract/predicates_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,26 @@ defmodule Drops.PredicatesTest do
end
end

describe "in?/2" do
describe "in?/2 with a single value" do
contract do
schema do
%{required(:test) => type(:string, in?: ["Hello"])}
end
end

test "returns success when the value is in the list", %{contract: contract} do
assert {:ok, %{test: "Hello"}} = contract.conform(%{test: "Hello"})
end

test "returns error when the value is not in the list", %{contract: contract} do
assert_errors(
["test must be one of: Hello"],
contract.conform(%{test: "312"})
)
end
end

describe "in?/2 with multiple values" do
contract do
schema do
%{required(:test) => type(:string, in?: ["Hello", "World"])}
Expand All @@ -671,7 +690,26 @@ defmodule Drops.PredicatesTest do
end
end

describe "not_in?/2" do
describe "not_in?/2 with a single value" do
contract do
schema do
%{required(:test) => type(:string, not_in?: ["Hello"])}
end
end

test "returns success when the value is not in the list", %{contract: contract} do
assert {:ok, %{test: "312"}} = contract.conform(%{test: "312"})
end

test "returns error when the value is in the list", %{contract: contract} do
assert_errors(
["test must not be one of: Hello"],
contract.conform(%{test: "Hello"})
)
end
end

describe "not_in?/2 with multiple values" do
contract do
schema do
%{required(:test) => type(:string, not_in?: ["Hello", "World"])}
Expand Down

0 comments on commit ba0813b

Please sign in to comment.