Skip to content

Commit

Permalink
Add test
Browse files Browse the repository at this point in the history
  • Loading branch information
GregorGrasselli committed Jul 12, 2024
1 parent 00a3d4a commit 729c2c8
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions test/cast_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,34 @@ defmodule OpenApiSpec.CastTest do
assert Error.message_with_path(error) == "#/age: Invalid strict_integer. Got: string"
end

test "cast custom error with custom validator" do
defmodule EvenInt do
require OpenApiSpex

alias OpenApiSpex.Cast

OpenApiSpex.schema(%{
description: "An even integer",
type: :integer,
"x-validate": __MODULE__
})

def cast(context = %Cast{value: value}) when is_integer(value) and rem(value, 2) == 0,
do: Cast.ok(context)

def cast(context), do: Cast.error(context, {:custom, "Must be an even integer"})
end

schema = %Schema{type: :object, properties: %{even_number: EvenInt.schema()}}

assert {:error, errors} = cast(value: %{"even_number" => 1}, schema: schema)
assert [error] = errors
assert %Error{} = error
assert error.reason == :custom
assert error.path == [:even_number]
assert Error.message_with_path(error) == "#/even_number: Must be an even integer"
end

test "nil value with xxxOf" do
schema = %Schema{anyOf: [%Schema{nullable: true, type: :string}]}
assert {:ok, nil} = cast(value: nil, schema: schema)
Expand Down

0 comments on commit 729c2c8

Please sign in to comment.