Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add all_of #87

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/norm.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ defmodule Norm do
alias Norm.Core.{
Alt,
AnyOf,
AllOf,
Collection,
Schema,
Selection,
Expand Down Expand Up @@ -245,6 +246,18 @@ defmodule Norm do
AnyOf.new(specs)
end

@doc """
Composes multiple specs into a single spec. The passed in value must conform
to each of the specs or an error is returned.

## Examples
iex> conform!(42, all_of([spec(is_integer), spec(& &1 > 1)]))
42
"""
def all_of(specs) when is_list(specs) and length(specs) > 0 do
AllOf.new(specs)
end

@doc ~S"""
Specifies a generic collection. Collections can be any enumerable type.

Expand Down
8 changes: 8 additions & 0 deletions lib/norm/core/all_of.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,13 @@ defmodule Norm.Core.AllOf do
end
end
end

defimpl Inspect do
import Inspect.Algebra

def inspect(sum, opts) do
concat(["#Norm.AllOf<", to_doc(sum.specs, opts), ">"])
end
end
end

33 changes: 33 additions & 0 deletions test/norm/core/all_of_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
defmodule Norm.Core.AllOfTest do
use Norm.Case, async: true

describe "conforming" do
test "all specs must hold true" do
all = all_of([spec(is_atom), spec(fn x -> x == :foo end)])

assert :foo == conform!(:foo, all)
assert {:error, errors} = conform(:bar, all)
assert errors == [
%{input: :bar, path: [], spec: "fn x -> x == :foo end"}
]

assert {:error, errors} = conform("bar", all)
assert errors == [
%{input: "bar", path: [], spec: "is_atom()"},
%{input: "bar", path: [], spec: "fn x -> x == :foo end"}
]
end
end

describe "generation" do
@tag :skip
test "generated values conform to all of the specs" do
pos_numbers = all_of([spec(is_integer), spec(fn x -> x > 0 end)])

check all num <- gen(pos_numbers) do
assert is_integer(num)
assert num > 0
end
end
end
end