From 98fc920b5ce77e44b0b258478491e71747855f1a Mon Sep 17 00:00:00 2001 From: Tobias Casper Date: Tue, 26 Mar 2024 11:10:43 +0100 Subject: [PATCH] test: add tests for `Vx.Type.constraints/2` --- lib/vx/type.ex | 4 +++- test/vx/type_test.exs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/vx/type.ex b/lib/vx/type.ex index 24f93d6..e6467f1 100644 --- a/lib/vx/type.ex +++ b/lib/vx/type.ex @@ -81,8 +81,10 @@ defmodule Vx.Type do when type: t(atom) | custom(module, atom) def constraints(type, name) do type - |> constraints() + |> resolve() + |> Map.fetch!(:constraints) |> Enum.filter(&match?(%Constraint{name: ^name}, &1)) + |> Enum.reverse() end defp resolve(%{__type__: %__MODULE__{} = type}), do: type diff --git a/test/vx/type_test.exs b/test/vx/type_test.exs index f868073..6761d13 100644 --- a/test/vx/type_test.exs +++ b/test/vx/type_test.exs @@ -78,6 +78,41 @@ defmodule Vx.TypeTest do end end + describe "constraints/2" do + setup do + {:ok, + constraints: [ + %Vx.Constraint{name: :foo, value: "foo", fun: fn _ -> :ok end}, + %Vx.Constraint{name: :bar, value: "foo", fun: fn _ -> :ok end}, + %Vx.Constraint{name: :foo, value: "bar", fun: fn _ -> :ok end} + ]} + end + + test "plain type", %{constraints: constraints} do + type = %{ + Vx.Type.new(:foo, fn _ -> :ok end) + | constraints: Enum.reverse(constraints) + } + + assert [ + %Vx.Constraint{name: :foo, value: "foo"}, + %Vx.Constraint{name: :foo, value: "bar"} + ] = Vx.Type.constraints(type, :foo) + end + + test "wrapped type", %{constraints: constraints} do + schema = + Map.update!(Vx.Integer.t(), :__type__, fn type -> + %{type | constraints: Enum.reverse(constraints)} + end) + + assert [ + %Vx.Constraint{name: :foo, value: "foo"}, + %Vx.Constraint{name: :foo, value: "bar"} + ] = Vx.Type.constraints(schema, :foo) + end + end + describe "of/1" do test "plain type" do of = [Vx.String.t(), Vx.Integer.t()]