Skip to content

Commit a064054

Browse files
committed
fix enum validation
1 parent e840429 commit a064054

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

lib/open_api_spex/schema.ex

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,13 @@ defmodule OpenApiSpex.Schema do
459459
def validate(%Schema{nullable: _}, nil, path, _schemas) do
460460
{:error, "#{path}: unexpected null value"}
461461
end
462+
def validate(%Schema{enum: options = [_ | _]}, value, path, _schemas) do
463+
case Enum.member?(options, value) do
464+
true -> :ok
465+
_ ->
466+
{:error, "#{path}: Value not in enum: #{inspect(value)}"}
467+
end
468+
end
462469
def validate(%Schema{type: type}, value, path, _schemas) when type in [:integer, :number] and not is_number(value) do
463470
{:error, "#{path}: expected value of type #{type}"}
464471
end
@@ -472,8 +479,7 @@ defmodule OpenApiSpex.Schema do
472479
def validate(schema = %Schema{type: :string}, value, path, _schemas) do
473480
with :ok <- validate_max_length(schema, value, path),
474481
:ok <- validate_min_length(schema, value, path),
475-
:ok <- validate_pattern(schema, value, path),
476-
:ok <- validate_enum(schema, value, path) do
482+
:ok <- validate_pattern(schema, value, path) do
477483
:ok
478484
end
479485
end
@@ -553,16 +559,6 @@ defmodule OpenApiSpex.Schema do
553559
end
554560
end
555561

556-
@spec validate_enum(Schema.t, String.t, String.t) :: :ok | {:error, String.t}
557-
def validate_enum(%{enum: nil}, _val, _path), do: :ok
558-
def validate_enum(%{enum: options}, value, path) do
559-
case Enum.member?(options, value) do
560-
true -> :ok
561-
_ ->
562-
{:error, "#{path}: Value not in enum: #{Enum.join(options, ", ")}"}
563-
end
564-
end
565-
566562
@spec validate_max_items(Schema.t, list, String.t) :: :ok | {:error, String.t}
567563
defp validate_max_items(%Schema{maxItems: nil}, _val, _path), do: :ok
568564
defp validate_max_items(%Schema{maxItems: n}, value, _path) when length(value) <= n, do: :ok

test/schema_test.exs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,20 @@ defmodule OpenApiSpex.SchemaTest do
138138
assert :ok = Schema.validate(schema, "bar", %{})
139139
end
140140

141+
test "Validate enum with expected value" do
142+
schema = %Schema{
143+
enum: ["foo", %{id: 42}]
144+
}
145+
assert :ok = Schema.validate(schema, %{id: 42}, %{})
146+
end
147+
148+
test "Validate enum with unexpected value" do
149+
schema = %Schema{
150+
enum: ["foo", %{id: 42}]
151+
}
152+
assert {:error, _} = Schema.validate(schema, "baz", %{})
153+
end
154+
141155
test "Validate nullable with expected value" do
142156
schema = %Schema{nullable: true}
143157
assert :ok = Schema.validate(schema, nil, %{})

0 commit comments

Comments
 (0)